diff --git a/.gitignore b/.gitignore index 5e6e38280a..6f5b141e2c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,78 +1,78 @@ -/.scannerwork/ -/YouPHPTube.code-workspace -/git.php -/iptvsource_one_one.csv -/nbproject/ -/nbproject/private/ -/plugin/AD_Server_Promote_Videos/ -/plugin/AWS_S3/ -/plugin/AudioTrackSwitcher/ -/plugin/AudioVisualizer/ -/plugin/AutoShare/ -/plugin/Backup/ -/plugin/Blackblaze_B2/ -/plugin/Bookmark/ -/plugin/Chat2/ -/plugin/CountryRedirect/ -/plugin/CreateUserManager/ -/plugin/Customize/ -/plugin/DIY/ -/plugin/DiskUploadQuota/ -/plugin/FTPAutoImport/ -/plugin/FTP_Storage/ -/plugin/FlixHouse/ -/plugin/GoogleAds_IMA/ -/plugin/IPDirectConnect/ -/plugin/IPTV/ -/plugin/ImportFromOtherVideoPlatform/ -/plugin/Layout/hamburguerMenu.php -/plugin/Layout/navBarLateral.php -/plugin/Layout/navbar.php -/plugin/Layout/timer.php -/plugin/LifeStreamLayout/ -/plugin/LiveCountdownEvent/ -/plugin/LiveOnlineUsers/ -/plugin/LiveUsers/ -/plugin/Livesearch/ -/plugin/LoginLDAP/ -/plugin/LoginLDAP_DYNA/ -/plugin/MP4ThumbsAndGif/ -/plugin/MP4ThumbsAndGifLocal/ -/plugin/Notifications/ -/plugin/PayPalToWatch/ -/plugin/PayPerView/ -/plugin/PayPerViewLive/ -/plugin/PointsSystem/ -/plugin/PromoteVideos/ -/plugin/ReturnToLastPosition/ -/plugin/SecondLife/ -/plugin/SecondWatch/ -/plugin/SecureVideosDirectory/ -/plugin/SendRecordedToEncoder/ -/plugin/SignUpAgreement/ -/plugin/Subscription/ -/plugin/SubtitleSwitcher/ -/plugin/SupportAuthor/ -/plugin/Tecorio/ -/plugin/User_Controll/ -/plugin/VideoDocuments/ -/plugin/VideoHLS/ -/plugin/VideoResolutionSwitcher/ -/plugin/VideoSpeed/ -/plugin/VideoThumbnails/ -/plugin/Video_Location_Block/ -/plugin/YPTStorage/ -/plugin/YouPHPTV/ -/plugin/ZoomMeetingRecorder/ -/plugin/oncologytube/ -/plugin/predefinedCategory/ -/plugin/FansSubscriptions/ -/videos/ -*.zip -sitemap.xml -/plugin/WebRTCLiveCam/ -/plugin/Wix/ -/plugin/Live/standAloneFiles/WebRTCServer/configuration.php -/plugin/Fishr/ -/plugin/JoshWho/ -.DS_Store +/.scannerwork/ +/YouPHPTube.code-workspace +/git.php +/iptvsource_one_one.csv +/nbproject/ +/nbproject/private/ +/plugin/AD_Server_Promote_Videos/ +/plugin/AWS_S3/ +/plugin/AudioTrackSwitcher/ +/plugin/AudioVisualizer/ +/plugin/AutoShare/ +/plugin/Backup/ +/plugin/Blackblaze_B2/ +/plugin/Bookmark/ +/plugin/Chat2/ +/plugin/CountryRedirect/ +/plugin/CreateUserManager/ +/plugin/Customize/ +/plugin/DIY/ +/plugin/DiskUploadQuota/ +/plugin/FTPAutoImport/ +/plugin/FTP_Storage/ +/plugin/FlixHouse/ +/plugin/GoogleAds_IMA/ +/plugin/IPDirectConnect/ +/plugin/IPTV/ +/plugin/ImportFromOtherVideoPlatform/ +/plugin/Layout/hamburguerMenu.php +/plugin/Layout/navBarLateral.php +/plugin/Layout/navbar.php +/plugin/Layout/timer.php +/plugin/LifeStreamLayout/ +/plugin/LiveCountdownEvent/ +/plugin/LiveOnlineUsers/ +/plugin/LiveUsers/ +/plugin/Livesearch/ +/plugin/LoginLDAP/ +/plugin/LoginLDAP_DYNA/ +/plugin/MP4ThumbsAndGif/ +/plugin/MP4ThumbsAndGifLocal/ +/plugin/Notifications/ +/plugin/PayPalToWatch/ +/plugin/PayPerView/ +/plugin/PayPerViewLive/ +/plugin/PointsSystem/ +/plugin/PromoteVideos/ +/plugin/ReturnToLastPosition/ +/plugin/SecondLife/ +/plugin/SecondWatch/ +/plugin/SecureVideosDirectory/ +/plugin/SendRecordedToEncoder/ +/plugin/SignUpAgreement/ +/plugin/Subscription/ +/plugin/SubtitleSwitcher/ +/plugin/SupportAuthor/ +/plugin/Tecorio/ +/plugin/User_Controll/ +/plugin/VideoDocuments/ +/plugin/VideoHLS/ +/plugin/VideoResolutionSwitcher/ +/plugin/VideoSpeed/ +/plugin/VideoThumbnails/ +/plugin/Video_Location_Block/ +/plugin/YPTStorage/ +/plugin/YouPHPTV/ +/plugin/ZoomMeetingRecorder/ +/plugin/oncologytube/ +/plugin/predefinedCategory/ +/plugin/FansSubscriptions/ +/videos/ +*.zip +sitemap.xml +/plugin/WebRTCLiveCam/ +/plugin/Wix/ +/plugin/Live/standAloneFiles/WebRTCServer/configuration.php +/plugin/Fishr/ +/plugin/JoshWho/ +.DS_Store diff --git a/README.md b/README.md index 111502c408..6904fe0bbd 100644 --- a/README.md +++ b/README.md @@ -1,173 +1,173 @@ - - -[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.3-8892BF.svg?style=flat-square)](https://php.net/) -[![GitHub release](https://img.shields.io/github/v/release/WWBN/AVideo)](https://github.com/WWBN/AVideo/releases) - -## Audio Video Platform -AVideo is a term that means absolutely nothing, or anything video. Since it doesn't mean anything the brand simply is identifiable with audio video. AVideo Platform is an Audio and Video Platform or simply "A Video Platform". - -* AVideo - Audio Video -* AVideo Platform - Audio Video Platform -* OAVP - Online Audio Video Platform -* OVP - Online Video Platform - -AVideo Platform is distributed as SaaS at AVideo.com, as an Enterprise Version, and as an Open-Source Project. - -## AN AVideo Platform Instance - -When we say a clone or copy of AVideo we mean an instance of AVideo Platform Enterprise or Open-Source and every instance of the AVideo Platform can be indexed as a network in the World Wide Broadcast Network Platform System. - -### AVideo trademark is FREE to use -AVideo is a registered trademark owned by WWBN/PeachWiz (World Wide Broadcast Network) the media division of PeachWiz, Inc. and is freely distributable with any Enterprise or Open-Source AVideo Platform products provided by WWBN, and its permitted use is granted with GNU-GPL, CDDL open source licenses. Open-Source License can be viewed in this link. -* Word Mark: AVIDEO -* Translations: "AVideo" has no meaning in any foreign language. -* Description: "AVideo" constitutes Audio Video. -* Goods and Services: IC 009. US 021 023 026 036 038. G & S: Computer search engine software for searching online video content. FIRST USE: 20030602. FIRST USE IN COMMERCE: 20040112 -* Standard Characters: Claimed -* Mark Drawing Code: (4) STANDARD CHARACTER MARK -* Trademark Search Facility Classification Code: LETS-1 A A single letter, multiples of a single letter or in combination with a design -* Serial Number: 77450549 -* Registration Number: 3625659 - -#### About the project re-brand. - Originally the open-source version was offered as YouPHPTube, and marketed as a YouTube Clone (after the popular video sharing site), we decided to rebrand our open-source audio video platform project from YouPHPTube to AVideo Platform which constitutes Audio Video Platform. In some plugins, forks, versions, modules, APIs, documentation, file names, there may be or have been reference to youphptube, youphp.tube, youtube clone, clone script, searchtube, adtube, showtube, searchmercials. WWBN owns Searchmercials, SearchTube, AdTube, ShowTube, AVideo, WWBN among other trademarks. All other trademarks and similarity to any referred to in any files, documents, wikis, plugins, code, modules, apis, integrations, technologies, links belong to their respective owners. Follow us on Facebook -# -# AVideo Platform Open-Source Project -## AVideo Platform Open-Source Consist of THREE main Areas: - - -#### (Management/Encoding/Storage) -1. Management Project(s): AVideo Platform -1. Encoding Project(s): AVideo Encoder & AVideo Encoder Network (Optional) -1. Storage Project(s): AVideo Storage - -Management life cycle is as follows; media is managed at the platform at 1, media is then uploaded to a temporary storage to be encoded at 2, then stored for broadcast at 3, then distributed to devices at 1 to be consumed. - -#### About AVideo Platform Open-Source -Some of the largest brands in the world use the AVideo Platform to manage and distribute their media assets. AVideo Platform open-source project has over 900 developers, and over 4000 AVideo Platform instances throughout the world. Because of the remarkable flexibility of the platform, each of our customers uses our platform in a slightly different way, to address their particular needs and deliver solid targeted value to their organization. - -The AVideo Platform Plugin Design allows you to get exactly the solution that addresses your needs today, while ensuring that your Broadcast Network implementation can grow and expand with you as your needs evolve. - -
- -# Create Your Own Broadcast Network With AVideo Platform - -## AVideo Platform Open-Source Solution enables you to create your own video sharing site. Join the AVideo Developer Community and get platform innovation details, bug fixes, and contribute the continued evolution of AVideo Platform. - -## Along with this re-brand come a slew of value added benefits for all AVideo Platform instances. -* Each AVideo Platform clone is considered a broadcast network -* Each broadcast network is indexed in our World Wide Broadcast Network Platform System -* Each broadcast network can use our ad network -* Each broadcast network can use our Open Systems TV platform (Coming Soon) -* Each broadcast network has channels and each channel has programs Learn more - -And more to come in 2020. Our mission is to take your video sharing site to "The Next Level" Internet TV. - -WWBN offers relevant and practical solutions, as well as valuable innovative technology, designed to increase the efficiency of advertising and broadcasting operations and maximize revenue opportunities for our customers and partners. - -### WHERE WE DELIVER -PROFITABLE STRATEGIES - We provide companies with new business models that evolve around the delivery of video and other digital assets complementing their existing business offerings and adding to their revenues. These new ways of doing business include Turnkey application-integration with capabilities for managing, auditing, and disseminating digital content. - -### To learn more about AVideo Platform visit the AVideo Platform Official Site. -### To learn more about the history of the AVideo Paroject WWBN Project Page - -### To see a demo select one below. -* AVideo Platform Flix Demo - - We provide you a AVideo Flix Style site sample. On this site you can subscribe (with real money on PayPal). this subscription will allow you to watch our private videos. There is an user that you can use to see how it works. user: test and pass: test. -* AVideo Platform Gallery Demo - - We've provided a sample Video Gallery site, which is also our tutorials site. On this sample you can login, subscribe, like, dislike and comment. but you can not upload videos. -* AVideo Platform Full-Access Demo - - We provide you a Demo site sample with full access to the admin account. You will need an admin password to upload and manage videos, it is by default. user: admin and pass: 123. Also there is a non admin user and password (Only for comments). user: test and pass: test. - - - -# Notice: -### We highly recommend you keep your instance of AVideo Platform updated to the latest release. If you have updated your instance to version 8.0, your old plugins will not work, just download them again and you should be fine. - -# First thing... -I would humbly like to thank God for giving me the necessary knowledge, motivation, resources and idea to be able to execute this project. Without God's permission this would never be possible. - -**For of Him, and through Him, and to Him, are all things: to whom be glory for ever. Amen.** -`Apostle Paul in Romans 11:36` - -## This Software must be used for Good, never Evil. It is expressly forbidden to use AVideo Platform Open-Source to build porn sites, violence, racism, terrorism, or anything else that affects human integrity or denigrates the image of anyone. - -## Now you can read the rest... - -## Important Information - -> Streamer can be installed on any Server, including Windows, but the encoder and Livestream should work fine on any Linux distribution. However we recommend Ubuntu 20.04 without any kind of control panel. -> The problem with cPanel, Plesk, Webmin, VestaCP, etc. It's because we need full root access to install some libs, and maybe compile them. Another important point is that to make Livestream work, we need to compile Nginx and the control panels often prevent us from running the commands forcing the installation available only on your panel. - -I don´t want to read I just want you to show me how to install!! - -Ok, check this out! - -For text-based tutorials and the manual, look here. - -There, you can find some hints for troubleshooting as well. - -### AVideo Platform Mobile APP -Android - -## AVideo Platform Certified -#### Need Help With Installation or Plugins? Feel free to ask us for help from the AVideo Platform Certified developers. - -Daniel Neto - -# AVideo - Streamer -AVideo! is an video-sharing website, It is an open source solution that is freely available to everyone. With AVideo you can create your own video sharing site, AVideo will help you import and encode videos from other sites like Youtube, Vimeo, etc. and you can share directly on your website. In addition, you can use Facebook or Google login to register users on your site. The service was created in march 2017. - -
- -View Demo -
- -# AVideo - Encoder -Go get it here - -
- -View Public Encoder -
- -# Why do I need the Encoder? -You may want to install the encoder for a few reasons, such as, if you have a faster server than the public encoder server (which is likely to be the case), or if you'd like a private way of encoding your videos. - -But, the installation is mandatory if you are using a private network. The public encoder will not have access to send the videos to your streamer site. - -If your server does not have a public IP or uses an IP on some of these bands: -- 10.0.0.0/8 -- 127.0.0.0/8 (Localhost) -- 172.16.0.0/12 -- 192.168.0.0/16 - -Surely you need to install an encoder - -# Server Requirements - -In order for you to be able to run AVideo Platform, there are certain tools that need to be installed on your server. Don't worry, they are all FREE. To have a look at complete list of required tools, click the link below. https://github.com/WWBN/AVideo/wiki/AVideo-Platform-Hardware-Requirements - -- PHP 7.3+ -- MySQL 5.0+ -- Apache web server 2.x (with mod_rewrite enabled) - -## Docker local development - -```bash -docker-compose up --build -d -``` - -# Roadmap - -## Version 8.9 - -## Version 8.10 - -## Version 8.11 - -## git clone - -After a git clone command run this - -composer update --prefer-dist --ignore-platform-reqs + + +[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.3-8892BF.svg?style=flat-square)](https://php.net/) +[![GitHub release](https://img.shields.io/github/v/release/WWBN/AVideo)](https://github.com/WWBN/AVideo/releases) + +## Audio Video Platform +AVideo is a term that means absolutely nothing, or anything video. Since it doesn't mean anything the brand simply is identifiable with audio video. AVideo Platform is an Audio and Video Platform or simply "A Video Platform". + +* AVideo - Audio Video +* AVideo Platform - Audio Video Platform +* OAVP - Online Audio Video Platform +* OVP - Online Video Platform + +AVideo Platform is distributed as SaaS at AVideo.com, as an Enterprise Version, and as an Open-Source Project. + +## AN AVideo Platform Instance + +When we say a clone or copy of AVideo we mean an instance of AVideo Platform Enterprise or Open-Source and every instance of the AVideo Platform can be indexed as a network in the World Wide Broadcast Network Platform System. + +### AVideo trademark is FREE to use +AVideo is a registered trademark owned by WWBN/PeachWiz (World Wide Broadcast Network) the media division of PeachWiz, Inc. and is freely distributable with any Enterprise or Open-Source AVideo Platform products provided by WWBN, and its permitted use is granted with GNU-GPL, CDDL open source licenses. Open-Source License can be viewed in this link. +* Word Mark: AVIDEO +* Translations: "AVideo" has no meaning in any foreign language. +* Description: "AVideo" constitutes Audio Video. +* Goods and Services: IC 009. US 021 023 026 036 038. G & S: Computer search engine software for searching online video content. FIRST USE: 20030602. FIRST USE IN COMMERCE: 20040112 +* Standard Characters: Claimed +* Mark Drawing Code: (4) STANDARD CHARACTER MARK +* Trademark Search Facility Classification Code: LETS-1 A A single letter, multiples of a single letter or in combination with a design +* Serial Number: 77450549 +* Registration Number: 3625659 + +#### About the project re-brand. + Originally the open-source version was offered as YouPHPTube, and marketed as a YouTube Clone (after the popular video sharing site), we decided to rebrand our open-source audio video platform project from YouPHPTube to AVideo Platform which constitutes Audio Video Platform. In some plugins, forks, versions, modules, APIs, documentation, file names, there may be or have been reference to youphptube, youphp.tube, youtube clone, clone script, searchtube, adtube, showtube, searchmercials. WWBN owns Searchmercials, SearchTube, AdTube, ShowTube, AVideo, WWBN among other trademarks. All other trademarks and similarity to any referred to in any files, documents, wikis, plugins, code, modules, apis, integrations, technologies, links belong to their respective owners. Follow us on Facebook +# +# AVideo Platform Open-Source Project +## AVideo Platform Open-Source Consist of THREE main Areas: + + +#### (Management/Encoding/Storage) +1. Management Project(s): AVideo Platform +1. Encoding Project(s): AVideo Encoder & AVideo Encoder Network (Optional) +1. Storage Project(s): AVideo Storage + +Management life cycle is as follows; media is managed at the platform at 1, media is then uploaded to a temporary storage to be encoded at 2, then stored for broadcast at 3, then distributed to devices at 1 to be consumed. + +#### About AVideo Platform Open-Source +Some of the largest brands in the world use the AVideo Platform to manage and distribute their media assets. AVideo Platform open-source project has over 900 developers, and over 4000 AVideo Platform instances throughout the world. Because of the remarkable flexibility of the platform, each of our customers uses our platform in a slightly different way, to address their particular needs and deliver solid targeted value to their organization. + +The AVideo Platform Plugin Design allows you to get exactly the solution that addresses your needs today, while ensuring that your Broadcast Network implementation can grow and expand with you as your needs evolve. + +
+ +# Create Your Own Broadcast Network With AVideo Platform + +## AVideo Platform Open-Source Solution enables you to create your own video sharing site. Join the AVideo Developer Community and get platform innovation details, bug fixes, and contribute the continued evolution of AVideo Platform. + +## Along with this re-brand come a slew of value added benefits for all AVideo Platform instances. +* Each AVideo Platform clone is considered a broadcast network +* Each broadcast network is indexed in our World Wide Broadcast Network Platform System +* Each broadcast network can use our ad network +* Each broadcast network can use our Open Systems TV platform (Coming Soon) +* Each broadcast network has channels and each channel has programs Learn more + +And more to come in 2020. Our mission is to take your video sharing site to "The Next Level" Internet TV. + +WWBN offers relevant and practical solutions, as well as valuable innovative technology, designed to increase the efficiency of advertising and broadcasting operations and maximize revenue opportunities for our customers and partners. + +### WHERE WE DELIVER +PROFITABLE STRATEGIES - We provide companies with new business models that evolve around the delivery of video and other digital assets complementing their existing business offerings and adding to their revenues. These new ways of doing business include Turnkey application-integration with capabilities for managing, auditing, and disseminating digital content. + +### To learn more about AVideo Platform visit the AVideo Platform Official Site. +### To learn more about the history of the AVideo Paroject WWBN Project Page + +### To see a demo select one below. +* AVideo Platform Flix Demo + - We provide you a AVideo Flix Style site sample. On this site you can subscribe (with real money on PayPal). this subscription will allow you to watch our private videos. There is an user that you can use to see how it works. user: test and pass: test. +* AVideo Platform Gallery Demo + - We've provided a sample Video Gallery site, which is also our tutorials site. On this sample you can login, subscribe, like, dislike and comment. but you can not upload videos. +* AVideo Platform Full-Access Demo + - We provide you a Demo site sample with full access to the admin account. You will need an admin password to upload and manage videos, it is by default. user: admin and pass: 123. Also there is a non admin user and password (Only for comments). user: test and pass: test. + + + +# Notice: +### We highly recommend you keep your instance of AVideo Platform updated to the latest release. If you have updated your instance to version 8.0, your old plugins will not work, just download them again and you should be fine. + +# First thing... +I would humbly like to thank God for giving me the necessary knowledge, motivation, resources and idea to be able to execute this project. Without God's permission this would never be possible. + +**For of Him, and through Him, and to Him, are all things: to whom be glory for ever. Amen.** +`Apostle Paul in Romans 11:36` + +## This Software must be used for Good, never Evil. It is expressly forbidden to use AVideo Platform Open-Source to build porn sites, violence, racism, terrorism, or anything else that affects human integrity or denigrates the image of anyone. + +## Now you can read the rest... + +## Important Information + +> Streamer can be installed on any Server, including Windows, but the encoder and Livestream should work fine on any Linux distribution. However we recommend Ubuntu 20.04 without any kind of control panel. +> The problem with cPanel, Plesk, Webmin, VestaCP, etc. It's because we need full root access to install some libs, and maybe compile them. Another important point is that to make Livestream work, we need to compile Nginx and the control panels often prevent us from running the commands forcing the installation available only on your panel. + +I don´t want to read I just want you to show me how to install!! + +Ok, check this out! + +For text-based tutorials and the manual, look here. + +There, you can find some hints for troubleshooting as well. + +### AVideo Platform Mobile APP +Android + +## AVideo Platform Certified +#### Need Help With Installation or Plugins? Feel free to ask us for help from the AVideo Platform Certified developers. + +Daniel Neto + +# AVideo - Streamer +AVideo! is an video-sharing website, It is an open source solution that is freely available to everyone. With AVideo you can create your own video sharing site, AVideo will help you import and encode videos from other sites like Youtube, Vimeo, etc. and you can share directly on your website. In addition, you can use Facebook or Google login to register users on your site. The service was created in march 2017. + +
+ +View Demo +
+ +# AVideo - Encoder +Go get it here + +
+ +View Public Encoder +
+ +# Why do I need the Encoder? +You may want to install the encoder for a few reasons, such as, if you have a faster server than the public encoder server (which is likely to be the case), or if you'd like a private way of encoding your videos. + +But, the installation is mandatory if you are using a private network. The public encoder will not have access to send the videos to your streamer site. + +If your server does not have a public IP or uses an IP on some of these bands: +- 10.0.0.0/8 +- 127.0.0.0/8 (Localhost) +- 172.16.0.0/12 +- 192.168.0.0/16 + +Surely you need to install an encoder + +# Server Requirements + +In order for you to be able to run AVideo Platform, there are certain tools that need to be installed on your server. Don't worry, they are all FREE. To have a look at complete list of required tools, click the link below. https://github.com/WWBN/AVideo/wiki/AVideo-Platform-Hardware-Requirements + +- PHP 7.3+ +- MySQL 5.0+ +- Apache web server 2.x (with mod_rewrite enabled) + +## Docker local development + +```bash +docker-compose up --build -d +``` + +# Roadmap + +## Version 8.9 + +## Version 8.10 + +## Version 8.11 + +## git clone + +After a git clone command run this + +composer update --prefer-dist --ignore-platform-reqs diff --git a/admin/backup.php b/admin/backup.php index 4ffef6b1ba..71527a524c 100644 --- a/admin/backup.php +++ b/admin/backup.php @@ -1,48 +1,47 @@ -
-
-
-
-
- -
-
- -
- -
-

- -
- -
- -
-
-
-
-
-
Clone Site
-
-
-
- -
- __('Place here the URL of the site you want to clone')); - echo createTable("CloneSite", $filter); - include $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html'; - ?> -
-
-
- -
+
+
+
+
+
+ +
+
+ +
+ +
+

+ +
+ +
+ +
+
+
+
+
+
Clone Site
+
+
+
+ +
+ __('Place here the URL of the site you want to clone'), ]; + echo createTable("CloneSite", $filter); + include $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html'; + ?> +
+
+
+ +
diff --git a/admin/customize_settings.php b/admin/customize_settings.php index 62d63275a0..605565a709 100644 --- a/admin/customize_settings.php +++ b/admin/customize_settings.php @@ -1,3 +1,3 @@ -node_modules/croppie/croppie.css" rel="stylesheet" type="text/css"/> - -
-
-
-
-
-
- -
-
- - " class="form-control" type="text" value="getWebSiteTitle(); ?>" > -
-
-
-
- -
- - -
- -
-
-
-
-
- -
-
-
-
-
- + + +
+
+
+
+
+
+ +
+
+ + " class="form-control" type="text" value="getWebSiteTitle(); ?>" > +
+
+
+
+ +
+ + +
+ +
+
+
+
+
+ +
+
+
+
+
+ diff --git a/admin/customize_settings_nativeUpdate.json.php b/admin/customize_settings_nativeUpdate.json.php index ae63fa8b2a..7c8469b95a 100644 --- a/admin/customize_settings_nativeUpdate.json.php +++ b/admin/customize_settings_nativeUpdate.json.php @@ -1,53 +1,53 @@ -setWebSiteTitle($_POST['webSiteTitle']); -$imagePath = "videos/userPhoto/"; - -//Check write Access to Directory -if (!file_exists($global['systemRootPath'] . $imagePath)) { - mkdir($global['systemRootPath'] . $imagePath, 0755, true); -} - -if (!is_writable($global['systemRootPath'] . $imagePath)) { - $response = Array( - "status" => 'error', - "message" => 'No write Access' - ); - print json_encode($response); - return; -} -$response = array(); -if (!empty($_POST['logoImgBase64'])) { - $fileData = base64DataToImage($_POST['logoImgBase64']); - $fileName = 'logo.png'; - $photoURL = $imagePath . $fileName; - $bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData); - if ($bytes > 10) { - $response = array( - "status" => 'success', - "url" => $global['systemRootPath'] . $photoURL - ); - $config->setLogo($photoURL); - } else { - $response = array( - "status" => 'error', - "msg" => 'We could not save logo', - "url" => $global['systemRootPath'] . $photoURL - ); - } -} - -echo '{"status":"' . $config->save() . '", "respnseLogo": ' . json_encode($response) . '}'; +setWebSiteTitle($_POST['webSiteTitle']); +$imagePath = "videos/userPhoto/"; + +//Check write Access to Directory +if (!file_exists($global['systemRootPath'] . $imagePath)) { + mkdir($global['systemRootPath'] . $imagePath, 0755, true); +} + +if (!is_writable($global['systemRootPath'] . $imagePath)) { + $response = [ + "status" => 'error', + "message" => 'No write Access', + ]; + print json_encode($response); + return; +} +$response = []; +if (!empty($_POST['logoImgBase64'])) { + $fileData = base64DataToImage($_POST['logoImgBase64']); + $fileName = 'logo.png'; + $photoURL = $imagePath . $fileName; + $bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData); + if ($bytes > 10) { + $response = [ + "status" => 'success', + "url" => $global['systemRootPath'] . $photoURL, + ]; + $config->setLogo($photoURL); + } else { + $response = [ + "status" => 'error', + "msg" => 'We could not save logo', + "url" => $global['systemRootPath'] . $photoURL, + ]; + } +} + +echo '{"status":"' . $config->save() . '", "respnseLogo": ' . json_encode($response) . '}'; diff --git a/admin/customize_settings_plugin.php b/admin/customize_settings_plugin.php index 20c91de39e..c2c9131aaf 100644 --- a/admin/customize_settings_plugin.php +++ b/admin/customize_settings_plugin.php @@ -1,75 +1,73 @@ - - -
-
-
- -
- - -
- -
-
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
- -
-
-
- -
-
- - + + +
+
+
+ +
+ + +
+ +
+
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+ +
+
+
+ +
+
+ + diff --git a/admin/design_colors.php b/admin/design_colors.php index 4c77975f93..143ae5ab75 100644 --- a/admin/design_colors.php +++ b/admin/design_colors.php @@ -1,20 +1,20 @@ -
-
-
- -
- " class="img-responsive"> -
-
- - -
- -
-
+
+
+
+ +
+ " class="img-responsive"> +
+
+ + +
+ +
+
diff --git a/admin/design_first_page.php b/admin/design_first_page.php index 43070ba27d..38dc982a57 100644 --- a/admin/design_first_page.php +++ b/admin/design_first_page.php @@ -1,327 +1,327 @@ - -
-
-
-
- Default -
- > - -
-
-
- -
-
-
-
-
-
- Netflix -
- > - -
-
-
- -
-
-
- -
-
-
- Channel -
- > - -
-
-
- -
-
-
-
-
-
- Gallery -
- > - -
-
-
- -
-
-
-
- \ No newline at end of file + +
+
+
+
+ Default +
+ > + +
+
+
+ +
+
+
+
+
+
+ Netflix +
+ > + +
+
+
+ +
+
+
+ +
+
+
+ Channel +
+ > + +
+
+
+ +
+
+
+
+
+
+ Gallery +
+ > + +
+
+
+ +
+
+
+
+ diff --git a/admin/design_player.php b/admin/design_player.php index 5ee70a010a..581c836d86 100644 --- a/admin/design_player.php +++ b/admin/design_player.php @@ -1,72 +1,72 @@ - -
-
-
-
- Default -
- skin)) ? "checked" : ""; ?>> - -
-
-
- -
-
-
- -
-
-
- -
- skin) ? "checked" : ""; ?>> - -
-
-
- -
-
-
- -
- \ No newline at end of file + +
+
+
+
+ Default +
+ skin)) ? "checked" : ""; ?>> + +
+
+
+ +
+
+
+ +
+
+
+ +
+ skin) ? "checked" : ""; ?>> + +
+
+
+ +
+
+
+ +
+ diff --git a/admin/design_themes.php b/admin/design_themes.php index 5fde7d31ee..a7832184de 100644 --- a/admin/design_themes.php +++ b/admin/design_themes.php @@ -1,54 +1,54 @@ -
- getTheme(); - $delay = 0.2; - foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) { - //echo "$filename size " . filesize($filename) . "\n"; - $file = basename($filename); // $file is set to "index.php" - $fileEx = basename($filename, ".css"); // $file is set to "index" - ?> -
-
-
- -
- > - -
-
-
- " class="img-responsive"> -
-
-
- -
- \ No newline at end of file +
+ getTheme(); + $delay = 0.2; + foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) { + //echo "$filename size " . filesize($filename) . "\n"; + $file = basename($filename); // $file is set to "index.php" + $fileEx = basename($filename, ".css"); // $file is set to "index" + ?> +
+
+
+ +
+ > + +
+
+
+ " class="img-responsive"> +
+
+
+ +
+ diff --git a/admin/functions.php b/admin/functions.php index 6e31c33eef..444138bdb2 100644 --- a/admin/functions.php +++ b/admin/functions.php @@ -1,95 +1,95 @@ - $valueJson) { - $filter[$keyJson] = " "; - } - } - //var_dump($filter);exit; - echo '
'; - echo ''; - echo ''; - echo ''; - $pluginsList = array(); - if (!AVideoPlugin::exists($pluginName)) { - echo ""; - } else { - if (!empty($plugin)) { - $form = jsonToFormElements($plugin, $filter); - //var_dump($form); - echo implode("", $form); - } - - echo ""; - } - echo '
".__('Sorry you do not have the plugin')."
'; -} - -function jsonToFormElements($json, $filter = array()) -{ - //var_dump($json, $filter);exit; - $elements = array(); - foreach ($json as $keyJson => $valueJson) { - if (!empty($filter) && empty($filter[$keyJson])) { - continue; - } - $label = ""; - $help = ""; - if (!empty($filter[$keyJson])) { - $help = "{$filter[$keyJson]}"; - } - $input = ""; - if (is_object($valueJson)) { - if ($valueJson->type === 'textarea') { - $input = ""; - } elseif (is_array($valueJson->type)) { - $input = ""; - } else { - if(!is_string($valueJson->type) || !is_string($valueJson->value)){ - continue; - } - $input = ""; - } - $elements[] = "{$label} {$input}{$help}"; - } elseif (is_bool($valueJson)) { - $id = uniqid(); - $input = '
- - -
'; - $elements[] = "{$input}{$label}
{$help}"; - } else { - $input = ""; - $elements[] = "{$label} {$input}{$help}"; - } - } - return $elements; -} - -function getPluginSwitch($pluginName) -{ - if (!AVideoPlugin::exists($pluginName)) { - $input = ''.__('Buy this plugin now').''; - } else { - $plugin = AVideoPlugin::loadPluginIfEnabled($pluginName); - $pluginForced = AVideoPlugin::loadPlugin($pluginName); - $id = uniqid(); - $uuid = $pluginForced->getUUID(); - $input = '
- - -
'; - } - return $input; -} + $valueJson) { + $filter[$keyJson] = " "; + } + } + //var_dump($filter);exit; + echo '
'; + echo ''; + echo ''; + echo ''; + $pluginsList = []; + if (!AVideoPlugin::exists($pluginName)) { + echo ""; + } else { + if (!empty($plugin)) { + $form = jsonToFormElements($plugin, $filter); + //var_dump($form); + echo implode("", $form); + } + + echo ""; + } + echo '
".__('Sorry you do not have the plugin')."
'; +} + +function jsonToFormElements($json, $filter = []) +{ + //var_dump($json, $filter);exit; + $elements = []; + foreach ($json as $keyJson => $valueJson) { + if (!empty($filter) && empty($filter[$keyJson])) { + continue; + } + $label = ""; + $help = ''; + if (!empty($filter[$keyJson])) { + $help = "{$filter[$keyJson]}"; + } + $input = ''; + if (is_object($valueJson)) { + if ($valueJson->type === 'textarea') { + $input = ""; + } elseif (is_array($valueJson->type)) { + $input = ""; + } else { + if (!is_string($valueJson->type) || !is_string($valueJson->value)) { + continue; + } + $input = ""; + } + $elements[] = "{$label} {$input}{$help}"; + } elseif (is_bool($valueJson)) { + $id = uniqid(); + $input = '
+ + +
'; + $elements[] = "{$input}{$label}
{$help}"; + } else { + $input = ""; + $elements[] = "{$label} {$input}{$help}"; + } + } + return $elements; +} + +function getPluginSwitch($pluginName) +{ + if (!AVideoPlugin::exists($pluginName)) { + $input = ''.__('Buy this plugin now').''; + } else { + $plugin = AVideoPlugin::loadPluginIfEnabled($pluginName); + $pluginForced = AVideoPlugin::loadPlugin($pluginName); + $id = uniqid(); + $uuid = $pluginForced->getUUID(); + $input = '
+ + +
'; + } + return $input; +} diff --git a/admin/general_settings.php b/admin/general_settings.php index 3bebe61cd1..fc2b4554e3 100644 --- a/admin/general_settings.php +++ b/admin/general_settings.php @@ -1,27 +1,27 @@ -
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file +
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/admin/general_settings_encoder.php b/admin/general_settings_encoder.php index 7858ef4bfc..377f3038f5 100644 --- a/admin/general_settings_encoder.php +++ b/admin/general_settings_encoder.php @@ -1,11 +1,11 @@ - __('Let the encoder network (If configured) choose what is the best encoder to use'), - 'doNotShowEncoderResolutionLow' => __('Do not allow encode in Low resolution'), - 'doNotShowEncoderResolutionSD' => __('Do not allow encode in SD resolution'), - 'doNotShowEncoderResolutionHD' => __('Do not allow encode in HD resolution'), - 'makeVideosInactiveAfterEncode' => __('Maybe you need to approve or check something on your video before make it public'), - 'makeVideosUnlistedAfterEncode' => __('Maybe you need to approve or check something on your video before make it public') -); - -createTable("CustomizeAdvanced", $filter); + __('Let the encoder network (If configured) choose what is the best encoder to use'), + 'doNotShowEncoderResolutionLow' => __('Do not allow encode in Low resolution'), + 'doNotShowEncoderResolutionSD' => __('Do not allow encode in SD resolution'), + 'doNotShowEncoderResolutionHD' => __('Do not allow encode in HD resolution'), + 'makeVideosInactiveAfterEncode' => __('Maybe you need to approve or check something on your video before make it public'), + 'makeVideosUnlistedAfterEncode' => __('Maybe you need to approve or check something on your video before make it public'), +]; + +createTable("CustomizeAdvanced", $filter); diff --git a/admin/general_settings_upload.php b/admin/general_settings_upload.php index e773f604d2..094a193e9a 100644 --- a/admin/general_settings_upload.php +++ b/admin/general_settings_upload.php @@ -1,10 +1,10 @@ -'The Encoder Network URL ', - 'useEncoderNetworkRecomendation'=>__('Let the encoder network (if configured) choose what is the best encoder to use'), - 'doNotShowUploadMP4Button'=>__('Users will not be able to directly upload, only use the encoder'), - 'doNotShowImportMP4Button'=>__('Disable the option to import MP4 videos from your local (Server) storage'), - 'doNotShowEncoderButton'=>__('Do not show the button to the encoder'), - 'doNotShowEmbedButton'=>__('Check this if you will not use embed videos on your site') -); -createTable("CustomizeAdvanced", $filter); + 'The Encoder Network URL ', + 'useEncoderNetworkRecomendation' => __('Let the encoder network (if configured) choose what is the best encoder to use'), + 'doNotShowUploadMP4Button' => __('Users will not be able to directly upload, only use the encoder'), + 'doNotShowImportMP4Button' => __('Disable the option to import MP4 videos from your local (Server) storage'), + 'doNotShowEncoderButton' => __('Do not show the button to the encoder'), + 'doNotShowEmbedButton' => __('Check this if you will not use embed videos on your site'), +]; +createTable("CustomizeAdvanced", $filter); diff --git a/admin/general_settings_user.php b/admin/general_settings_user.php index 4eb24dbbfa..706c6c7ec3 100644 --- a/admin/general_settings_user.php +++ b/admin/general_settings_user.php @@ -1,15 +1,15 @@ -__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), - 'disableNativeSignIn'=>__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), - 'disablePersonalInfo'=>__('Disable the My Account personal info like: First and Last Name and address'), - 'newUsersCanStream'=>__('Automatic allow new users to use your Livestream Platform'), - 'doNotIndentifyByEmail'=>__('Do not show user\'s email on the site'), - 'doNotIndentifyByName'=>__('Do not show user\'s name on the site'), - 'doNotIndentifyByUserName'=>__('Do not show user\'s username on the site'), - 'unverifiedEmailsCanNOTLogin'=>__('Users must verify their emails before login'), - 'onlyVerifiedEmailCanUpload'=>__('Users must verify their emails before upload/submit videos'), - 'sendVerificationMailAutomatic'=>__('After sign up we will automatic send a verification email'), - 'userMustBeLoggedIn'=>__('Hide the website to non logged users') -); -createTable("CustomizeUser", $filter); +__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), + 'disableNativeSignIn'=>__('This is useful if you want to use our LDAP plugin or maybe only allow authentication from Social Networks'), + 'disablePersonalInfo'=>__('Disable the My Account personal info like: First and Last Name and address'), + 'newUsersCanStream'=>__('Automatic allow new users to use your Livestream Platform'), + 'doNotIndentifyByEmail'=>__('Do not show user\'s email on the site'), + 'doNotIndentifyByName'=>__('Do not show user\'s name on the site'), + 'doNotIndentifyByUserName'=>__('Do not show user\'s username on the site'), + 'unverifiedEmailsCanNOTLogin'=>__('Users must verify their emails before login'), + 'onlyVerifiedEmailCanUpload'=>__('Users must verify their emails before upload/submit videos'), + 'sendVerificationMailAutomatic'=>__('After sign up we will automatic send a verification email'), + 'userMustBeLoggedIn'=>__('Hide the website to non logged users'), +]; +createTable("CustomizeUser", $filter); diff --git a/admin/health_check.php b/admin/health_check.php index 20c92b920e..d2dd2717f5 100644 --- a/admin/health_check.php +++ b/admin/health_check.php @@ -1,37 +1,37 @@ array(), 'PHP' => array(), 'Apache' => array()); +$messages = ['Server' => [], 'PHP' => [], 'Apache' => []]; $version = phpversion(); $phpMinVersion = '7.3.0'; if (strnatcmp($version, $phpMinVersion) >= 0) { @@ -46,7 +46,7 @@ foreach ($phpExtensions as $value) { if (in_array($value[0], $extensions)) { $messages['PHP'][] = $value[0]; } else { - $messages['PHP'][] = array($value[0], 'sudo apt-get install php-' . str_replace('_', '-', $value[0]) . ' -y && sudo /etc/init.d/apache2 restart'); + $messages['PHP'][] = [$value[0], 'sudo apt-get install php-' . str_replace('_', '-', $value[0]) . ' -y && sudo /etc/init.d/apache2 restart']; } } @@ -54,10 +54,10 @@ foreach ($phpExtensions as $value) { if (isset($_SERVER["HTTPS"])) { $messages['Apache'][] = "HTTPS is enabled"; } else { - $messages['Apache'][] = array("HTTPS is not enabled", 'https://github.com/WWBN/AVideo/wiki/Why-use-HTTPS'); + $messages['Apache'][] = ["HTTPS is not enabled", 'https://github.com/WWBN/AVideo/wiki/Why-use-HTTPS']; } -if(function_exists('apache_get_modules')){ +if (function_exists('apache_get_modules')) { $mods = array_map('strtolower', apache_get_modules()); //var_dump($mods); foreach ($apacheModules as $value) { @@ -74,13 +74,13 @@ if(function_exists('apache_get_modules')){ if ($found) { $messages['Apache'][] = $found; } else { - $messages['Apache'][] = array($value[0], @$value[1]); + $messages['Apache'][] = [$value[0], @$value[1]]; } } } -}else{ +} else { foreach ($apacheModules as $value) { - $messages['Apache'][] = array($value[0], 'We could not check your installed modules. We recommend you to use apache as a module NOT as a FPM'); + $messages['Apache'][] = [$value[0], 'We could not check your installed modules. We recommend you to use apache as a module NOT as a FPM']; } } @@ -89,27 +89,27 @@ foreach ($linuxApps as $value) { if (!empty($response)) { $messages['Server'][] = "{$value[0]} is installed here {$response}"; } else { - $messages['Server'][] = array("{$value[0]} is NOT installed", @$value[1]); + $messages['Server'][] = ["{$value[0]} is NOT installed", @$value[1]]; } } $videosDir = getVideosDir(); if (is_writable($videosDir)) { $messages['Server'][] = "{$videosDir} is writable"; } else { - $messages['Server'][] = array("{$videosDir} is NOT writable", 'sudo chmod -R 777 ' . $videosDir); + $messages['Server'][] = ["{$videosDir} is NOT writable", 'sudo chmod -R 777 ' . $videosDir]; } if (is_writable($global['logfile'])) { $messages['Server'][] = "Log file is writable"; } else { - $messages['Server'][] = array("{$global['logfile']} is NOT writable", 'sudo chmod -R 777 ' . $global['logfile']); + $messages['Server'][] = ["{$global['logfile']} is NOT writable", 'sudo chmod -R 777 ' . $global['logfile']]; } $cacheDir = "{$videosDir}cache/"; if (is_writable($cacheDir)) { $messages['Server'][] = "Cache is writable"; } else { - $messages['Server'][] = array("{$cacheDir} is NOT writable", 'sudo chmod -R 777 ' . $cacheDir); + $messages['Server'][] = ["{$cacheDir} is NOT writable", 'sudo chmod -R 777 ' . $cacheDir]; } $_50GB = 53687091200; @@ -118,14 +118,14 @@ $df = disk_free_space("/"); if ($df > $_50GB) { $messages['Server'][] = "You have enough free disk space " . humanFileSize($df); } else { - $messages['Server'][] = array("Your disk is almost full, you have only " . humanFileSize($df) . ' free'); + $messages['Server'][] = ["Your disk is almost full, you have only " . humanFileSize($df) . ' free']; } $dfVideos = disk_free_space($videosDir); if ($dfVideos > $_50GB) { $messages['Server'][] = "You have enough free disk space for the videos directory " . humanFileSize($dfVideos); } else { - $messages['Server'][] = array("Your videos directory is almost full, you have only " . humanFileSize($dfVideos) . ' free'); + $messages['Server'][] = ["Your videos directory is almost full, you have only " . humanFileSize($dfVideos) . ' free']; } @@ -135,19 +135,19 @@ $verifyURL = addQueryStringParameter($verifyURL, 'screenshot', 1); $result = url_get_contents($verifyURL, '', 5); if (empty($result)) { - $messages['Server'][] = array("We could not verify your server from outside {$global['webSiteRootURL']}"); + $messages['Server'][] = ["We could not verify your server from outside {$global['webSiteRootURL']}"]; } else { $verified = json_decode($result); if (!empty($verified->verified)) { $messages['Server'][] = "Server Checked from outside:
" . implode('
', $verified->msg); } else { - $messages['Server'][] = array("Something is wrong: ", implode('
', $verified->msg)); + $messages['Server'][] = ["Something is wrong: ", implode('
', $verified->msg)]; } /* if(!empty($verified->screenshot)){ $messages['Server'][] = ""; } - * + * */ } ?> @@ -181,18 +181,17 @@ if (empty($result)) {
+ if (!empty($value[1])) { + if (preg_match('/^http/i', $value[1])) { + ?> + } else { + ?>
+ } + } ?>
">
+ echo $value; ?>
+ if (!empty($value[1])) { + if (preg_match('/^http/i', $value[1])) { + ?> + } else { + ?>
+ } + } ?> ">
+ echo $value; ?>
+ if (!empty($value[1])) { + if (preg_match('/^http/i', $value[1])) { + ?> + } else { + ?>
+ } + } ?> ">
+ echo $value; ?>
title = $title; - $this->icon = $icon; - $this->href = $href; - $this->data_toggle = $data_toggle; - $this->data_target = $data_target; - if (!empty($href)) { - $fileName = basename($_SERVER["SCRIPT_NAME"]); - if ($href === $fileName) { - $this->active = true; - } - } - } - - function addItem(MenuAdmin $menu) { - $this->itens[] = $menu; - if ($menu->active) { - $this->show = true; - } - } - -} - -$itens = array(); - -$menu = new MenuAdmin(__("Dashboard"), "fa fa-tachometer-alt", "dashboard"); -$itens[] = $menu; -/* - $menu = new MenuAdmin(__("Premium Featrures"), "fas fa-star", "premium"); - $itens[] = $menu; - */ -$menu = new MenuAdmin(__("Settings"), "fa fa-wrench"); -$menu->addItem(new MenuAdmin(__("Remove Branding"), "far fa-edit", "customize_settings")); -$menu->addItem(new MenuAdmin(__("General Settings"), "fas fa-cog", "general_settings")); -$menu->addItem(new MenuAdmin(__("Site Settings"), "fas fa-sitemap", "site_settings")); -$menu->addItem(new MenuAdmin(__("Social Login Settings"), "fas fa-sign-in-alt", "socialLogin_settings")); -$menu->addItem(new MenuAdmin(__("S3, B2, FTP settings"), "fas fa-hdd", "storage_settings")); -$menu->addItem(new MenuAdmin(__("Payments Settings"), "far fa-money-bill-alt", "payments_settings")); -$itens[] = $menu; - - -$menu = new MenuAdmin(__("Contents"), "fas fa-list-ul"); -$menu->addItem(new MenuAdmin(__("Videos"), "fas fa-play-circle", "videos")); -$menu->addItem(new MenuAdmin(__("Live Stuff"), "fas fa-broadcast-tower", "live")); -$menu->addItem(new MenuAdmin(__("Users"), "glyphicon glyphicon-user", "users")); -$menu->addItem(new MenuAdmin(__("Users Groups"), "fa fa-users", "usersGroups")); -$menu->addItem(new MenuAdmin(__("Categories"), "glyphicon glyphicon-list", "categories")); -$menu->addItem(new MenuAdmin(__("Backup"), "fas fa-undo-alt", "backup")); -$itens[] = $menu; - -$menu = new MenuAdmin(__("Design"), "fas fa-pen-fancy"); -$menu->addItem(new MenuAdmin(__("First Page Style"), "fas fa-columns", "design_first_page")); -$menu->addItem(new MenuAdmin(__("Player Skin"), "fas fa-play-circle", "design_player")); -$menu->addItem(new MenuAdmin(__("Themes"), "fas fa-palette", "design_themes")); -$menu->addItem(new MenuAdmin(__("Colors"), "fas fa-palette", "design_colors")); -//$menu->addItem(new MenuAdmin(__("Custom CSS"), "fab fa-css3-alt", "design_css")); -$itens[] = $menu; - -$menu = new MenuAdmin(__("Monetize"), "fas fa-dollar-sign"); -$menu->addItem(new MenuAdmin(__("Site Advertisement with VAST Video ads"), "fas fa-money-check-alt", "monetize_vast")); -$menu->addItem(new MenuAdmin(__("Pay User per Video View"), "far fa-money-bill-alt", "monetize_user")); -$menu->addItem(new MenuAdmin(__("Create Subscription Plans"), "fas fa-money-bill-alt", "monetize_subscription")); -//$menu->addItem(new MenuAdmin(__("Banner Script code"), "fas fa-money-check-alt", "advertisement_script")); -$itens[] = $menu; - -/* - $menu = new MenuAdmin(__("Update Version"), "glyphicon glyphicon-refresh", "{$global['webSiteRootURL']}update/"); - $itens[] = $menu; - - */ - -$menu = new MenuAdmin(__("Miscellaneous"), "fas fa-th"); -$menu->addItem(new MenuAdmin(__("Plugins"), "fas fa-puzzle-piece", "plugins")); -$menu->addItem(new MenuAdmin(__("Email All Users"), "fas fa-mail-bulk", "mail_all_users")); -$itens[] = $menu; - -$menu = new MenuAdmin(__("Health Check"), "fas fa-notes-medical", "health_check"); -$itens[] = $menu; - -$_GET['page'] = xss_esc(@$_GET['page']); - -$includeHead = ""; -$includeBody = ""; -switch ($_GET['page']) { - case "backup": - $includeBody = $global['systemRootPath'] . 'admin/backup.php'; - break; - case "premium": - $includeBody = $global['systemRootPath'] . 'admin/premium.php'; - break; - case "design_first_page": - $includeBody = $global['systemRootPath'] . 'admin/design_first_page.php'; - break; - case "design_themes": - $includeBody = $global['systemRootPath'] . 'admin/design_themes.php'; - break; - case "design_colors": - $includeBody = $global['systemRootPath'] . 'admin/design_colors.php'; - break; - case "design_player": - $includeBody = $global['systemRootPath'] . 'admin/design_player.php'; - break; - case "customize_settings": - $includeBody = $global['systemRootPath'] . 'admin/customize_settings.php'; - break; - case "storage_settings": - $includeBody = $global['systemRootPath'] . 'admin/storage_settings.php'; - break; - case "general_settings": - $includeBody = $global['systemRootPath'] . 'admin/general_settings.php'; - break; - case "payments_settings": - $includeBody = $global['systemRootPath'] . 'admin/payments_settings.php'; - break; - case "socialLogin_settings": - $includeBody = $global['systemRootPath'] . 'admin/socialLogin_settings.php'; - break; - case "site_settings": - $includeHead = $global['systemRootPath'] . 'view/configurations_head.php'; - $includeBody = $global['systemRootPath'] . 'view/configurations_body.php'; - break; - case "monetize_subscription": - $includeHead = $global['systemRootPath'] . 'plugin/Subscription/page/editor_head.php'; - $includeBody = array(); - $includeBody[] = $global['systemRootPath'] . 'plugin/Subscription/page/editor_body.php'; - $includeBody[] = $global['systemRootPath'] . 'admin/monetize_subscription.php'; - break; - case "monetize_vast": - $includeHead = $global['systemRootPath'] . 'plugin/AD_Server/index_head.php'; - $includeBody = $global['systemRootPath'] . 'plugin/AD_Server/index_body.php'; - break; - case "monetize_user": - $includeBody = $global['systemRootPath'] . 'admin/monetize_user.php'; - break; - case "plugins": - $includeHead = $global['systemRootPath'] . 'view/managerPlugins_head.php'; - $includeBody = $global['systemRootPath'] . 'view/managerPlugins_body.php'; - break; - case "mail_all_users": - $includeBody = $global['systemRootPath'] . 'admin/mail_all_users.php'; - break; - case "users": - $includeHead = $global['systemRootPath'] . 'view/managerUsers_head.php'; - $includeBody = $global['systemRootPath'] . 'view/managerUsers_body.php'; - break; - case "live": - $includeBody = $global['systemRootPath'] . 'admin/live.php'; - break; - case "usersGroups": - $includeHead = $global['systemRootPath'] . 'view/managerUsersGroups_head.php'; - $includeBody = $global['systemRootPath'] . 'view/managerUsersGroups_body.php'; - break; - case "categories": - $includeHead = $global['systemRootPath'] . 'view/managerCategories_head.php'; - $includeBody = $global['systemRootPath'] . 'view/managerCategories_body.php'; - break; - case "videos": - $includeHead = $global['systemRootPath'] . 'view/managerVideos_head.php'; - $includeBody = $global['systemRootPath'] . 'view/managerVideos_body.php'; - break; - case "health_check": - $includeBody = $global['systemRootPath'] . 'admin/health_check.php'; - break; - default : - $includeHead = $global['systemRootPath'] . 'view/charts_head.php'; - $includeBody = $global['systemRootPath'] . 'view/charts_body.php'; - break; -} -?> - - - - - "; - include $includeHead; - echo ""; - } - ?> - - - - - -
-
-
-
-
- $value) { - $uid = uniqid(); - $href = 'data-toggle="collapse" data-parent="#accordion" href="#collapse' . $uid . '"'; - if (!empty($value->href)) { - $href = 'href="' . $global['webSiteRootURL'] . 'admin/?page=' . $value->href . '"'; - } - if (!empty($_REQUEST['page']) && $_REQUEST['page'] == $value->href) { - $panel = 'panel-primary'; - } else { - foreach ($value->itens as $key2 => $value2) { - if (!empty($_REQUEST['page']) && $_REQUEST['page'] === $value2->href) { - $panel = 'panel-primary'; - } - } - } - ?> -
- - itens)) { - $in = ""; - if (!empty($_GET['page'])) { - foreach ($value->itens as $search) { - if ($_GET['page'] === $search->href) { - $in = "in"; - break; - } - } - } - ?> -
-
- - itens as $key2 => $value2) { - if (!empty($_GET['page']) && $_GET['page'] === $value2->href) { - $active = "active"; - } - ?> - - - - -
- title; ?> -
-
-
- -
- -
-
-
- -
- - -
- -
- - -
- -
-
-
- - - - - - +title = $title; + $this->icon = $icon; + $this->href = $href; + $this->data_toggle = $data_toggle; + $this->data_target = $data_target; + if (!empty($href)) { + $fileName = basename($_SERVER["SCRIPT_NAME"]); + if ($href === $fileName) { + $this->active = true; + } + } + } + + public function addItem(MenuAdmin $menu) + { + $this->itens[] = $menu; + if ($menu->active) { + $this->show = true; + } + } +} + +$itens = []; + +$menu = new MenuAdmin(__("Dashboard"), "fa fa-tachometer-alt", "dashboard"); +$itens[] = $menu; +/* + $menu = new MenuAdmin(__("Premium Featrures"), "fas fa-star", "premium"); + $itens[] = $menu; + */ +$menu = new MenuAdmin(__("Settings"), "fa fa-wrench"); +$menu->addItem(new MenuAdmin(__("Remove Branding"), "far fa-edit", "customize_settings")); +$menu->addItem(new MenuAdmin(__("General Settings"), "fas fa-cog", "general_settings")); +$menu->addItem(new MenuAdmin(__("Site Settings"), "fas fa-sitemap", "site_settings")); +$menu->addItem(new MenuAdmin(__("Social Login Settings"), "fas fa-sign-in-alt", "socialLogin_settings")); +$menu->addItem(new MenuAdmin(__("S3, B2, FTP settings"), "fas fa-hdd", "storage_settings")); +$menu->addItem(new MenuAdmin(__("Payments Settings"), "far fa-money-bill-alt", "payments_settings")); +$itens[] = $menu; + + +$menu = new MenuAdmin(__("Contents"), "fas fa-list-ul"); +$menu->addItem(new MenuAdmin(__("Videos"), "fas fa-play-circle", "videos")); +$menu->addItem(new MenuAdmin(__("Live Stuff"), "fas fa-broadcast-tower", "live")); +$menu->addItem(new MenuAdmin(__("Users"), "glyphicon glyphicon-user", "users")); +$menu->addItem(new MenuAdmin(__("Users Groups"), "fa fa-users", "usersGroups")); +$menu->addItem(new MenuAdmin(__("Categories"), "glyphicon glyphicon-list", "categories")); +$menu->addItem(new MenuAdmin(__("Backup"), "fas fa-undo-alt", "backup")); +$itens[] = $menu; + +$menu = new MenuAdmin(__("Design"), "fas fa-pen-fancy"); +$menu->addItem(new MenuAdmin(__("First Page Style"), "fas fa-columns", "design_first_page")); +$menu->addItem(new MenuAdmin(__("Player Skin"), "fas fa-play-circle", "design_player")); +$menu->addItem(new MenuAdmin(__("Themes"), "fas fa-palette", "design_themes")); +$menu->addItem(new MenuAdmin(__("Colors"), "fas fa-palette", "design_colors")); +//$menu->addItem(new MenuAdmin(__("Custom CSS"), "fab fa-css3-alt", "design_css")); +$itens[] = $menu; + +$menu = new MenuAdmin(__("Monetize"), "fas fa-dollar-sign"); +$menu->addItem(new MenuAdmin(__("Site Advertisement with VAST Video ads"), "fas fa-money-check-alt", "monetize_vast")); +$menu->addItem(new MenuAdmin(__("Pay User per Video View"), "far fa-money-bill-alt", "monetize_user")); +$menu->addItem(new MenuAdmin(__("Create Subscription Plans"), "fas fa-money-bill-alt", "monetize_subscription")); +//$menu->addItem(new MenuAdmin(__("Banner Script code"), "fas fa-money-check-alt", "advertisement_script")); +$itens[] = $menu; + +/* + $menu = new MenuAdmin(__("Update Version"), "glyphicon glyphicon-refresh", "{$global['webSiteRootURL']}update/"); + $itens[] = $menu; + + */ + +$menu = new MenuAdmin(__("Miscellaneous"), "fas fa-th"); +$menu->addItem(new MenuAdmin(__("Plugins"), "fas fa-puzzle-piece", "plugins")); +$menu->addItem(new MenuAdmin(__("Email All Users"), "fas fa-mail-bulk", "mail_all_users")); +$itens[] = $menu; + +$menu = new MenuAdmin(__("Health Check"), "fas fa-notes-medical", "health_check"); +$itens[] = $menu; + +$_GET['page'] = xss_esc(@$_GET['page']); + +$includeHead = ''; +$includeBody = ''; +switch ($_GET['page']) { + case "backup": + $includeBody = $global['systemRootPath'] . 'admin/backup.php'; + break; + case "premium": + $includeBody = $global['systemRootPath'] . 'admin/premium.php'; + break; + case "design_first_page": + $includeBody = $global['systemRootPath'] . 'admin/design_first_page.php'; + break; + case "design_themes": + $includeBody = $global['systemRootPath'] . 'admin/design_themes.php'; + break; + case "design_colors": + $includeBody = $global['systemRootPath'] . 'admin/design_colors.php'; + break; + case "design_player": + $includeBody = $global['systemRootPath'] . 'admin/design_player.php'; + break; + case "customize_settings": + $includeBody = $global['systemRootPath'] . 'admin/customize_settings.php'; + break; + case "storage_settings": + $includeBody = $global['systemRootPath'] . 'admin/storage_settings.php'; + break; + case "general_settings": + $includeBody = $global['systemRootPath'] . 'admin/general_settings.php'; + break; + case "payments_settings": + $includeBody = $global['systemRootPath'] . 'admin/payments_settings.php'; + break; + case "socialLogin_settings": + $includeBody = $global['systemRootPath'] . 'admin/socialLogin_settings.php'; + break; + case "site_settings": + $includeHead = $global['systemRootPath'] . 'view/configurations_head.php'; + $includeBody = $global['systemRootPath'] . 'view/configurations_body.php'; + break; + case "monetize_subscription": + $includeHead = $global['systemRootPath'] . 'plugin/Subscription/page/editor_head.php'; + $includeBody = []; + $includeBody[] = $global['systemRootPath'] . 'plugin/Subscription/page/editor_body.php'; + $includeBody[] = $global['systemRootPath'] . 'admin/monetize_subscription.php'; + break; + case "monetize_vast": + $includeHead = $global['systemRootPath'] . 'plugin/AD_Server/index_head.php'; + $includeBody = $global['systemRootPath'] . 'plugin/AD_Server/index_body.php'; + break; + case "monetize_user": + $includeBody = $global['systemRootPath'] . 'admin/monetize_user.php'; + break; + case "plugins": + $includeHead = $global['systemRootPath'] . 'view/managerPlugins_head.php'; + $includeBody = $global['systemRootPath'] . 'view/managerPlugins_body.php'; + break; + case "mail_all_users": + $includeBody = $global['systemRootPath'] . 'admin/mail_all_users.php'; + break; + case "users": + $includeHead = $global['systemRootPath'] . 'view/managerUsers_head.php'; + $includeBody = $global['systemRootPath'] . 'view/managerUsers_body.php'; + break; + case "live": + $includeBody = $global['systemRootPath'] . 'admin/live.php'; + break; + case "usersGroups": + $includeHead = $global['systemRootPath'] . 'view/managerUsersGroups_head.php'; + $includeBody = $global['systemRootPath'] . 'view/managerUsersGroups_body.php'; + break; + case "categories": + $includeHead = $global['systemRootPath'] . 'view/managerCategories_head.php'; + $includeBody = $global['systemRootPath'] . 'view/managerCategories_body.php'; + break; + case "videos": + $includeHead = $global['systemRootPath'] . 'view/managerVideos_head.php'; + $includeBody = $global['systemRootPath'] . 'view/managerVideos_body.php'; + break; + case "health_check": + $includeBody = $global['systemRootPath'] . 'admin/health_check.php'; + break; + default: + $includeHead = $global['systemRootPath'] . 'view/charts_head.php'; + $includeBody = $global['systemRootPath'] . 'view/charts_body.php'; + break; +} +?> + + + + + "; + include $includeHead; + echo ""; + } + ?> + + + + + +
+
+
+
+
+ $value) { + $uid = uniqid(); + $href = 'data-toggle="collapse" data-parent="#accordion" href="#collapse' . $uid . '"'; + if (!empty($value->href)) { + $href = 'href="' . $global['webSiteRootURL'] . 'admin/?page=' . $value->href . '"'; + } + if (!empty($_REQUEST['page']) && $_REQUEST['page'] == $value->href) { + $panel = 'panel-primary'; + } else { + foreach ($value->itens as $key2 => $value2) { + if (!empty($_REQUEST['page']) && $_REQUEST['page'] === $value2->href) { + $panel = 'panel-primary'; + } + } + } ?> +
+ + itens)) { + $in = ''; + if (!empty($_GET['page'])) { + foreach ($value->itens as $search) { + if ($_GET['page'] === $search->href) { + $in = "in"; + break; + } + } + } ?> +
+
+ + itens as $key2 => $value2) { + if (!empty($_GET['page']) && $_GET['page'] === $value2->href) { + $active = "active"; + } ?> + + + + +
+ title; ?> +
+
+
+ +
+ +
+
+
+ +
+ + +
+ +
+ + +
+ +
+
+
+ + + + + + diff --git a/admin/live.php b/admin/live.php index 825bb9d336..f359abfc62 100644 --- a/admin/live.php +++ b/admin/live.php @@ -1,53 +1,49 @@ -
-
-
-
-
- - -
-
-
-
-
-
-
- - -
-
-
-
-
-
-
- 'It will collect usage info but will not display the counter on the live video'); - - createTable("LiveUsers",$filter); - ?> - -
-
-
-
-
-
-
- - -
-
-
+
+
+
+
+
+ + +
+
+
+
+
+
+
+ + +
+
+
+
+
+
+
+ 'It will collect usage info but will not display the counter on the live video', ]; + + createTable("LiveUsers", $filter); + ?> + +
+
+
+
+
+
+
+ + +
+
+
\ No newline at end of file diff --git a/admin/mail_all_users.php b/admin/mail_all_users.php index ba207f2874..e1f7143376 100644 --- a/admin/mail_all_users.php +++ b/admin/mail_all_users.php @@ -1,78 +1,78 @@ - -
-
-
- -
- -
- - -
-
-
- -
- - $value) { - echo ''; - } - ?> -
-
-
-
-
- -
-
- -
-
- -
-
- -
-
- - - + +
+
+
+ +
+ +
+ + +
+
+
+ +
+ + $value) { + echo ''; + } + ?> +
+
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + diff --git a/admin/monetize_subscription.php b/admin/monetize_subscription.php index 808ae6fda6..0dd7404646 100644 --- a/admin/monetize_subscription.php +++ b/admin/monetize_subscription.php @@ -1,16 +1,16 @@ -
-
-
-
Subscription Configuration
-
- 'Show a button on the top to subscribe', - 'displayLeftMenuSubscribeButton' => 'Show a button on the the left menu to subscribe', - 'textSubscribe' => 'The button text label'); - createTable("Subscription", $filter); - ?> -
-
-
-
\ No newline at end of file +
+
+
+
Subscription Configuration
+
+ 'Show a button on the top to subscribe', + 'displayLeftMenuSubscribeButton' => 'Show a button on the the left menu to subscribe', + 'textSubscribe' => 'The button text label', ]; + createTable("Subscription", $filter); + ?> +
+
+
+
diff --git a/admin/monetize_user.php b/admin/monetize_user.php index abac2ed872..0fcc0159a4 100644 --- a/admin/monetize_user.php +++ b/admin/monetize_user.php @@ -1,34 +1,34 @@ -
-
-
-
-
- 'How much will your users receive per each video view', - 'rewardOnlyLoggedUsersView' => 'Check this to allow only count rewards from logged users'); - - createTable("MonetizeUsers",$filter); - ?> - -
-
-
-
-
-
-
- 'Usually for USD we use 2, for cryptocurrencies we use more the 2', - 'currency' => 'Australian Dollar = AUD, Brazilian Real = BRL, Canadian Dollar = CAD, Euro = EUR, U.S. Dollar = USD, etc', - 'currency_symbol' => '$, R$, etc, the format will be {currency} {value} {currency_symbol} for example ($ 10.00 USD) or (R$ 10.00 BRL)', - 'manualAddFundsTransferFromUserId' => 'When some one buy something on your web site, the wallet balance will be transferred to this user ID', - 'enablePlugin_YPTWalletPayPal' => 'You need to enable it to be able to use PayPal to add funds on your wallet', - 'enableManualWithdrawFundsPage' => 'Let users request withdraws from his wallet. the withdraw mus be done manually'); - createTable("YPTWallet", $filter); - ?> -
-
-
-
\ No newline at end of file +
+
+
+
+
+ 'How much will your users receive per each video view', + 'rewardOnlyLoggedUsersView' => 'Check this to allow only count rewards from logged users', ]; + + createTable("MonetizeUsers", $filter); + ?> + +
+
+
+
+
+
+
+ 'Usually for USD we use 2, for cryptocurrencies we use more the 2', + 'currency' => 'Australian Dollar = AUD, Brazilian Real = BRL, Canadian Dollar = CAD, Euro = EUR, U.S. Dollar = USD, etc', + 'currency_symbol' => '$, R$, etc, the format will be {currency} {value} {currency_symbol} for example ($ 10.00 USD) or (R$ 10.00 BRL)', + 'manualAddFundsTransferFromUserId' => 'When some one buy something on your web site, the wallet balance will be transferred to this user ID', + 'enablePlugin_YPTWalletPayPal' => 'You need to enable it to be able to use PayPal to add funds on your wallet', + 'enableManualWithdrawFundsPage' => 'Let users request withdraws from his wallet. the withdraw mus be done manually', ]; + createTable("YPTWallet", $filter); + ?> +
+
+
+
diff --git a/admin/payments_settings.php b/admin/payments_settings.php index ccf51f5291..5b918eebbc 100644 --- a/admin/payments_settings.php +++ b/admin/payments_settings.php @@ -1,29 +1,29 @@ -
-
-
-
-
- __('Usually for USD we use 2, for cryptocurrencies we use more the 2'), - 'currency' => __('Australian Dollar = AUD, Brazilian Real = BRL, Canadian Dollar = CAD, Euro = EUR, U.S. Dollar = USD, etc'), - 'currency_symbol' => __('$, R$, etc, the format will be {currency} {value} {currency_symbol} for example ($ 10.00 USD) or (R$ 10.00 BRL)'), - 'manualAddFundsTransferFromUserId' => __('When some one buy something on your web site, the wallet balance will be transferred to this user ID'), - 'enablePlugin_YPTWalletPayPal' => __('You need to enable it to be able to use PayPal to add funds on your wallet'), - 'enableManualWithdrawFundsPage' => __('Let users request withdraws from his wallet. the withdraw mus be done manually')); - createTable("YPTWallet", $filter); - ?> -
-
-
-
-
-
PayPal
-
- -
-
-
-
+
+
+
+
+
+ __('Usually for USD we use 2, for cryptocurrencies we use more the 2'), + 'currency' => __('Australian Dollar = AUD, Brazilian Real = BRL, Canadian Dollar = CAD, Euro = EUR, U.S. Dollar = USD, etc'), + 'currency_symbol' => __('$, R$, etc, the format will be {currency} {value} {currency_symbol} for example ($ 10.00 USD) or (R$ 10.00 BRL)'), + 'manualAddFundsTransferFromUserId' => __('When some one buy something on your web site, the wallet balance will be transferred to this user ID'), + 'enablePlugin_YPTWalletPayPal' => __('You need to enable it to be able to use PayPal to add funds on your wallet'), + 'enableManualWithdrawFundsPage' => __('Let users request withdraws from his wallet. the withdraw mus be done manually'), ]; + createTable("YPTWallet", $filter); + ?> +
+
+
+
+
+
PayPal
+
+ +
+
+
+
diff --git a/admin/playerUpdate.json.php b/admin/playerUpdate.json.php index a42e12dc2f..f64019d587 100644 --- a/admin/playerUpdate.json.php +++ b/admin/playerUpdate.json.php @@ -1,25 +1,25 @@ -skin = $_POST['skin']; - -$p = new Plugin($pluginDB['id']); -$p->setObject_data(json_encode($pluginDO)); - -$obj = new stdClass(); -$obj->save = $p->save(); - -echo (json_encode($obj)); +skin = $_POST['skin']; + +$p = new Plugin($pluginDB['id']); +$p->setObject_data(json_encode($pluginDO)); + +$obj = new stdClass(); +$obj->save = $p->save(); + +echo(json_encode($obj)); diff --git a/admin/premium.php b/admin/premium.php index ce124f6e52..568da727a3 100644 --- a/admin/premium.php +++ b/admin/premium.php @@ -1,39 +1,39 @@ -
-
-
-
-
- -
-
-
-
-
-
-
- -
-
-
-
-
-
-
- -
-
-
-
-
-
-
- -
-
-
-
- +
+
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+
+
+ diff --git a/admin/save.json.php b/admin/save.json.php index 6ee7864eb7..3dd73ad76c 100644 --- a/admin/save.json.php +++ b/admin/save.json.php @@ -1,48 +1,50 @@ - $value) { - if (isset($pluginValues[$key])) { - if (is_bool($pluginDO->$key)) { - $pluginDO->$key = empty($pluginValues[$key])?false:true; - } else { - //$pluginDO->$key = str_replace('"', '\\"', $pluginValues[$key]); - $pluginDO->$key = $pluginValues[$key]; - } - } -} - -$p = new Plugin($pluginDB['id']); -$p->setObject_data(json_encode($pluginDO)); - -$obj = new stdClass(); -$obj->save = $p->save(); -if ($obj->save === false) _error_log("[ERROR] Error saving plugin $pluginName data. Maybe plugin is not enabled?", AVideoLog::$ERROR); - -echo (json_encode($obj)); + $value) { + if (isset($pluginValues[$key])) { + if (is_bool($pluginDO->$key)) { + $pluginDO->$key = empty($pluginValues[$key]) ? false : true; + } else { + //$pluginDO->$key = str_replace('"', '\\"', $pluginValues[$key]); + $pluginDO->$key = $pluginValues[$key]; + } + } +} + +$p = new Plugin($pluginDB['id']); +$p->setObject_data(json_encode($pluginDO)); + +$obj = new stdClass(); +$obj->save = $p->save(); +if ($obj->save === false) { + _error_log("[ERROR] Error saving plugin $pluginName data. Maybe plugin is not enabled?", AVideoLog::$ERROR); +} + +echo(json_encode($obj)); diff --git a/admin/socialLogin_settings.php b/admin/socialLogin_settings.php index d54ea24dba..aaf3724312 100644 --- a/admin/socialLogin_settings.php +++ b/admin/socialLogin_settings.php @@ -1,106 +1,106 @@ -
-
-
-
-
- __('The form to signup will not exists'), - 'disableNativeSignIn' => __('The regular form to signin will not exist, if you check this will only have social login or LDAP option'), - 'userMustBeLoggedIn' => __('The site will display only a login form to un authenticated users')); - createTable("CustomizeUser", $filter); - ?> -
-
-
-
-
-
Facebook
-
- - -
- : objects/login.json.php?type=Facebook
- : plugin/MobileManager/oauth2.php?type=Facebook -
-
-
-
-
-
-
Google
-
- - -
- : objects/login.json.php?type=Google
- : plugin/MobileManager/oauth2.php?type=Google -
-
-
-
- -
-
-
Linkedin
-
- - -
- : objects/login.json.php?type=Linkedin
- : plugin/MobileManager/oauth2.php?type=Linkedin -
-
-
-
-
-
-
Twitter
-
- - -
- : objects/login.json.php?type=Twitter
- : plugin/MobileManager/oauth2.php?type=Twitter -
-
-
-
-
-
-
Yahoo
-
- - -
- : objects/login.json.php?type=Yahoo
- : plugin/MobileManager/oauth2.php?type=Yahoo -
-
-
-
-
-
-
LDAP
-
- - - - - -
-
-
-
+
+
+
+
+
+ __('The form to signup will not exists'), + 'disableNativeSignIn' => __('The regular form to signin will not exist, if you check this will only have social login or LDAP option'), + 'userMustBeLoggedIn' => __('The site will display only a login form to un authenticated users'), ]; + createTable("CustomizeUser", $filter); + ?> +
+
+
+
+
+
Facebook
+
+ + +
+ : objects/login.json.php?type=Facebook
+ : plugin/MobileManager/oauth2.php?type=Facebook +
+
+
+
+
+
+
Google
+
+ + +
+ : objects/login.json.php?type=Google
+ : plugin/MobileManager/oauth2.php?type=Google +
+
+
+
+ +
+
+
Linkedin
+
+ + +
+ : objects/login.json.php?type=Linkedin
+ : plugin/MobileManager/oauth2.php?type=Linkedin +
+
+
+
+
+
+
Twitter
+
+ + +
+ : objects/login.json.php?type=Twitter
+ : plugin/MobileManager/oauth2.php?type=Twitter +
+
+
+
+
+
+
Yahoo
+
+ + +
+ : objects/login.json.php?type=Yahoo
+ : plugin/MobileManager/oauth2.php?type=Yahoo +
+
+
+
+
+
+
LDAP
+
+ + + + + +
+
+
+
diff --git a/admin/storage_settings.php b/admin/storage_settings.php index 3895780246..f1545e32bf 100644 --- a/admin/storage_settings.php +++ b/admin/storage_settings.php @@ -1,32 +1,32 @@ -
-
-
-
S3 Storage
-
- -
-
-
-
-
-
B2 Storage
-
- -
-
-
-
-
-
FTP
-
- -
-
-
-
\ No newline at end of file +
+
+
+
S3 Storage
+
+ +
+
+
+
+
+
B2 Storage
+
+ +
+
+
+
+
+
FTP
+
+ +
+
+
+
diff --git a/admin/themeUpdate.json.php b/admin/themeUpdate.json.php index a384f01177..cb19f95437 100644 --- a/admin/themeUpdate.json.php +++ b/admin/themeUpdate.json.php @@ -1,15 +1,15 @@ -setTheme($_POST['theme']); - -echo '{"status":"' . $config->save() . '"}'; +setTheme($_POST['theme']); + +echo '{"status":"' . $config->save() . '"}'; diff --git a/composer.json b/composer.json index df41805fd2..515ac5f7ed 100644 --- a/composer.json +++ b/composer.json @@ -1,47 +1,47 @@ -{ - "name": "wwbn/avideo", - "description": "Audio Video Platform", - "type": "project", - "config": { - "platform-check": false, - "vendor-dir": "vendor", - "platform": { - "php": "7.3" - } - }, - "require": { - "php": "^7.3|^8", - "ext-curl": "*", - "ext-json": "*", - "chrisjean/php-ico": "^1.0", - "ezyang/htmlpurifier": "^4.13", - "google/apiclient": "^2.11", - "google/apiclient-services": "*", - "google/auth": "^1.14.3", - "guzzlehttp/guzzle": "^6.5", - "guzzlehttp/psr7": "^1.7", - "hybridauth/hybridauth": "^3.3", - "james-heinrich/getid3": "^1.9", - "monolog/monolog": "^1.17", - "phpmailer/phpmailer": "^6.2", - "psr/cache": "^1.0", - "psr/http-message": "^1.0", - "cboden/ratchet": "^0.4.3", - "ratchet/pawl": "^0.3.5", - "singpolyma/openpgp-php": "^0.5.0", - "aws/aws-sdk-php": "^3.180", - "gliterd/backblaze-b2": "^1.1", - "paypal/rest-api-sdk-php": "*", - "paypal/paypal-payouts-sdk": "^1.0", - "paypal/paypal-checkout-sdk": "^1.0", - "emojione/assets": "^4.5", - "mervick/emojionearea": "^3.4", - "emojione/emojione": "^4.5", - "abraham/twitteroauth": "^1.0", - "symfony/http-client": "^5.3", - "nyholm/psr7": "^1.4", - "norkunas/onesignal-php-api": "^2.7", - "stripe/stripe-php": "^7.97", - "symfony/translation": "^5.3" - } -} +{ + "name": "wwbn/avideo", + "description": "Audio Video Platform", + "type": "project", + "config": { + "platform-check": false, + "vendor-dir": "vendor", + "platform": { + "php": "7.3" + } + }, + "require": { + "php": "^7.3|^8", + "ext-curl": "*", + "ext-json": "*", + "chrisjean/php-ico": "^1.0", + "ezyang/htmlpurifier": "^4.13", + "google/apiclient": "^2.11", + "google/apiclient-services": "*", + "google/auth": "^1.14.3", + "guzzlehttp/guzzle": "^6.5", + "guzzlehttp/psr7": "^1.7", + "hybridauth/hybridauth": "^3.3", + "james-heinrich/getid3": "^1.9", + "monolog/monolog": "^1.17", + "phpmailer/phpmailer": "^6.2", + "psr/cache": "^1.0", + "psr/http-message": "^1.0", + "cboden/ratchet": "^0.4.3", + "ratchet/pawl": "^0.3.5", + "singpolyma/openpgp-php": "^0.5.0", + "aws/aws-sdk-php": "^3.180", + "gliterd/backblaze-b2": "^1.1", + "paypal/rest-api-sdk-php": "*", + "paypal/paypal-payouts-sdk": "^1.0", + "paypal/paypal-checkout-sdk": "^1.0", + "emojione/assets": "^4.5", + "mervick/emojionearea": "^3.4", + "emojione/emojione": "^4.5", + "abraham/twitteroauth": "^1.0", + "symfony/http-client": "^5.3", + "nyholm/psr7": "^1.4", + "norkunas/onesignal-php-api": "^2.7", + "stripe/stripe-php": "^7.97", + "symfony/translation": "^5.3" + } +} diff --git a/feed/index.php b/feed/index.php index 7620737e7f..c5d506ee2a 100644 --- a/feed/index.php +++ b/feed/index.php @@ -1,54 +1,53 @@ -getWebSiteTitle(); -$link = $global['webSiteRootURL']; -$logo = getCDN()."videos/userPhoto/logo.png"; -$description = ""; - -$extraPluginFile = $global['systemRootPath'] . 'plugin/Customize/Objects/ExtraConfig.php'; -if (file_exists($extraPluginFile) && AVideoPlugin::isEnabledByName("Customize")) { - require_once $extraPluginFile; - $ec = new ExtraConfig(); - $description = $ec->getDescription(); -} - -if(!empty($_GET['channelName'])){ - $user = User::getChannelOwner($_GET['channelName']); - $showOnlyLoggedUserVideos = $user['id']; - $title = User::getNameIdentificationById($user['id']); - $link = User::getChannelLink($user['id']); - $logo = User::getPhoto($user['id']); -} - -$cacheName = "feedCache".json_encode($_GET); -$rows = ObjectYPT::getCache($cacheName, 0); -if(empty($rows)){ - // send $_GET['catName'] to be able to filter by category - $rows = Video::getAllVideos("viewable", $showOnlyLoggedUserVideos); - ObjectYPT::setCache($cacheName, $rows); -}else{ - $rows = object_to_array($rows); -} -if(!empty($_REQUEST['roku'])){ - include $global['systemRootPath'] . 'feed/roku.json.php'; -}else if(empty($_REQUEST['mrss'])){ - include $global['systemRootPath'] . 'feed/rss.php'; -}else{ - include $global['systemRootPath'] . 'feed/mrss.php'; -} - -function feedText($text){ - return str_replace(array('&&'), array('&'), str_replace(array('&','<','>'), array('&','<','>'), (strip_tags(br2nl($text))))); -} - -?> \ No newline at end of file +getWebSiteTitle(); +$link = $global['webSiteRootURL']; +$logo = getCDN()."videos/userPhoto/logo.png"; +$description = ''; + +$extraPluginFile = $global['systemRootPath'] . 'plugin/Customize/Objects/ExtraConfig.php'; +if (file_exists($extraPluginFile) && AVideoPlugin::isEnabledByName("Customize")) { + require_once $extraPluginFile; + $ec = new ExtraConfig(); + $description = $ec->getDescription(); +} + +if (!empty($_GET['channelName'])) { + $user = User::getChannelOwner($_GET['channelName']); + $showOnlyLoggedUserVideos = $user['id']; + $title = User::getNameIdentificationById($user['id']); + $link = User::getChannelLink($user['id']); + $logo = User::getPhoto($user['id']); +} + +$cacheName = "feedCache".json_encode($_GET); +$rows = ObjectYPT::getCache($cacheName, 0); +if (empty($rows)) { + // send $_GET['catName'] to be able to filter by category + $rows = Video::getAllVideos("viewable", $showOnlyLoggedUserVideos); + ObjectYPT::setCache($cacheName, $rows); +} else { + $rows = object_to_array($rows); +} +if (!empty($_REQUEST['roku'])) { + include $global['systemRootPath'] . 'feed/roku.json.php'; +} elseif (empty($_REQUEST['mrss'])) { + include $global['systemRootPath'] . 'feed/rss.php'; +} else { + include $global['systemRootPath'] . 'feed/mrss.php'; +} + +function feedText($text) +{ + return str_replace(['&&'], ['&'], str_replace(['&','<','>'], ['&','<','>'], (strip_tags(br2nl($text))))); +} diff --git a/feed/mrss.php b/feed/mrss.php index 5f12658da7..a8094fb6e4 100644 --- a/feed/mrss.php +++ b/feed/mrss.php @@ -1,85 +1,81 @@ -'; - ?> - - - <?php echo feedText($title); ?> - - - - <?php echo feedText($title); ?> - - - 144 - 40 - AVideo version rss - - - '; - break; - } - } - ?> - - <?php echo feedText($row['title']); ?> - - - - - - - " bitrate="128" - type="" expression="full" - duration=""> - - ]]> - - - - - - - - - '; -}else{ - //echo ''; -} -if(!is_string($feed)){ - $feed = json_encode($feed); -} -echo $feed; -?> \ No newline at end of file +'; ?> + + + <?php echo feedText($title); ?> + + + + <?php echo feedText($title); ?> + + + 144 + 40 + AVideo version rss + + + '; + break; + } + } ?> + + <?php echo feedText($row['title']); ?> + + + + + + + " bitrate="128" + type="" expression="full" + duration=""> + + ]]> + + + + + + + + + '; +} else { + //echo ''; +} +if (!is_string($feed)) { + $feed = json_encode($feed); +} +echo $feed; diff --git a/feed/roku.json.php b/feed/roku.json.php index 77714053e3..8ce9564479 100644 --- a/feed/roku.json.php +++ b/feed/roku.json.php @@ -1,119 +1,117 @@ -providerName = $title; - $obj->language = "en"; - $obj->lastUpdated = date('c'); - $obj->movies = array(); - - $cacheName = "feedCache_ROKU_movies".json_encode($_REQUEST); - - $movies = ObjectYPT::getCache($cacheName, 0); - - if (empty($movies)) { - foreach ($rows as $row) { - $videoSource = Video::getSourceFileURL($row['filename']); - $videoResolution = Video::getResolutionFromFilename($videoSource); - //var_dump($videoSource); - if (empty($videoSource)) { - _error_log("Roku Empty video source {$row['id']}, {$row['clean_title']}, {$row['filename']}"); - continue; - } - - $movie = new stdClass(); - $movie->id = 'video_'.$row['id']; - $movie->title = UTF8encode($row['title']); - $movie->longDescription = "=> " . _substr(strip_tags(br2nl(UTF8encode($row['description']))), 0, 490); - $movie->shortDescription = _substr($movie->longDescription, 0, 200); - $movie->thumbnail = Video::getRokuImage($row['id']); - $movie->tags = array(_substr(UTF8encode($row['category']), 0, 20)); - $movie->genres = array("special"); - $movie->releaseDate = date('c', strtotime($row['created'])); - $movie->categories_id = $row['categories_id']; - $rrating = $row['rrating']; - if(!empty($rrating)){ - $movie->rating = new stdClass(); - $movie->rating->rating = rokuRating($rrating); - $movie->rating->ratingSource = 'MPAA'; - } - - - $content = new stdClass(); - $content->dateAdded = date('c', strtotime($row['created'])); - $content->captions = array(); - $content->duration = durationToSeconds($row['duration']); - $content->language = "en"; - $content->adBreaks = array("00:00:00"); - - $video = new stdClass(); - $video->url = $videoSource; - $video->quality = getResolutionTextRoku($videoResolution); - $video->videoType = Video::getVideoTypeText($row['filename']); - $content->videos = array($video); - - $movie->content = $content; - - $obj->movies[] = $movie; - - } - ObjectYPT::setCache($cacheName, $obj->movies); - } else { - $obj->movies = $movies; - } - - - $itemIds = array(); - foreach ($obj->movies as $value) { - $itemIds[] = $value->id; - } - $obj->playlists = array(array('name'=>'all', 'itemIds'=>$itemIds)); - - $obj->categories = array(array('name'=>'All', 'playlistName'=>'all', 'order'=>'most_recent')); - - $output = _json_encode($obj, JSON_UNESCAPED_UNICODE); - if (empty($output) && json_last_error()) { - $output = json_encode(json_last_error_msg()); - var_dump($obj); - }else{ - ObjectYPT::setCache($cacheFeedName, $output); - } -}else{ - //echo ''; -} -if(!is_string($output)){ - $output = json_encode($output); -} -die($output); -?> \ No newline at end of file +providerName = $title; + $obj->language = "en"; + $obj->lastUpdated = date('c'); + $obj->movies = []; + + $cacheName = "feedCache_ROKU_movies".json_encode($_REQUEST); + + $movies = ObjectYPT::getCache($cacheName, 0); + + if (empty($movies)) { + foreach ($rows as $row) { + $videoSource = Video::getSourceFileURL($row['filename']); + $videoResolution = Video::getResolutionFromFilename($videoSource); + //var_dump($videoSource); + if (empty($videoSource)) { + _error_log("Roku Empty video source {$row['id']}, {$row['clean_title']}, {$row['filename']}"); + continue; + } + + $movie = new stdClass(); + $movie->id = 'video_'.$row['id']; + $movie->title = UTF8encode($row['title']); + $movie->longDescription = "=> " . _substr(strip_tags(br2nl(UTF8encode($row['description']))), 0, 490); + $movie->shortDescription = _substr($movie->longDescription, 0, 200); + $movie->thumbnail = Video::getRokuImage($row['id']); + $movie->tags = [_substr(UTF8encode($row['category']), 0, 20)]; + $movie->genres = ["special"]; + $movie->releaseDate = date('c', strtotime($row['created'])); + $movie->categories_id = $row['categories_id']; + $rrating = $row['rrating']; + if (!empty($rrating)) { + $movie->rating = new stdClass(); + $movie->rating->rating = rokuRating($rrating); + $movie->rating->ratingSource = 'MPAA'; + } + + + $content = new stdClass(); + $content->dateAdded = date('c', strtotime($row['created'])); + $content->captions = []; + $content->duration = durationToSeconds($row['duration']); + $content->language = "en"; + $content->adBreaks = ["00:00:00"]; + + $video = new stdClass(); + $video->url = $videoSource; + $video->quality = getResolutionTextRoku($videoResolution); + $video->videoType = Video::getVideoTypeText($row['filename']); + $content->videos = [$video]; + + $movie->content = $content; + + $obj->movies[] = $movie; + } + ObjectYPT::setCache($cacheName, $obj->movies); + } else { + $obj->movies = $movies; + } + + + $itemIds = []; + foreach ($obj->movies as $value) { + $itemIds[] = $value->id; + } + $obj->playlists = [['name' => 'all', 'itemIds'=>$itemIds]]; + + $obj->categories = [['name' => 'All', 'playlistName' => 'all', 'order' => 'most_recent']]; + + $output = _json_encode($obj, JSON_UNESCAPED_UNICODE); + if (empty($output) && json_last_error()) { + $output = json_encode(json_last_error_msg()); + var_dump($obj); + } else { + ObjectYPT::setCache($cacheFeedName, $output); + } +} else { + //echo ''; +} +if (!is_string($output)) { + $output = json_encode($output); +} +die($output); diff --git a/feed/rss.php b/feed/rss.php index 47126efb26..5edfa68b0a 100644 --- a/feed/rss.php +++ b/feed/rss.php @@ -1,73 +1,70 @@ -' - ?> - - - " rel="self" type="application/rss+xml" /> - <?php echo feedText($title); ?> - - - hourly - 1 - - - <?php echo feedText($title); ?> - - - 144 - 40 - AVideo version rss - - - '; - break; - } - } - ?> - - <?php echo feedText($row['title']); ?> - - - - - - - - - - '; -} -if(!is_string($feed)){ - $feed = json_encode($feed); -} -echo $feed; -?> +' + ?> + + + " rel="self" type="application/rss+xml" /> + <?php echo feedText($title); ?> + + + hourly + 1 + + + <?php echo feedText($title); ?> + + + 144 + 40 + AVideo version rss + + + '; + break; + } + } ?> + + <?php echo feedText($row['title']); ?> + + + + + + + + + + '; +} +if (!is_string($feed)) { + $feed = json_encode($feed); +} +echo $feed; diff --git a/git.json.php b/git.json.php index 3c251a58f2..be0ec98f88 100644 --- a/git.json.php +++ b/git.json.php @@ -1,20 +1,19 @@ -&1", $output, $return_val); - -$obj = new stdClass(); - -$obj->output = $output; - -foreach ($output as $value){ - - preg_match("/Date:(.*)/i", $value, $match); - if(!empty($match[1])){ - $obj->date = strtotime($match[1]); - $obj->dateString = trim($match[1]); - $obj->dateMySQL = date("Y-m-d H:i:s", $obj->date); - } -} - -echo json_encode($obj); +&1", $output, $return_val); + +$obj = new stdClass(); + +$obj->output = $output; + +foreach ($output as $value) { + preg_match("/Date:(.*)/i", $value, $match); + if (!empty($match[1])) { + $obj->date = strtotime($match[1]); + $obj->dateString = trim($match[1]); + $obj->dateMySQL = date("Y-m-d H:i:s", $obj->date); + } +} + +echo json_encode($obj); diff --git a/index.php b/index.php index a60f6d836a..2c614fffe4 100644 --- a/index.php +++ b/index.php @@ -1,116 +1,116 @@ - - - - <?php echo __("Error Page"); ?> - - - - - -
- -
-

-

-
-

-

-

- -

- -

- "); echo htmlentities(""); echo __(" and change AllowOverride None to AllowOverride All"); ?> -

-

sudo nano /etc/apache2/apache2.conf

- -

- -

-


-          Options Indexes FollowSymLinks
-          AllowOverride All
-          Require all granted
-  "); ?>

- -

"); ?> -

sudo a2enmod rewrite

- -

- -

sudo /etc/init.d/apache2 restart

- -

- -

sudo service apache2 restart

- -
-
- - - \ No newline at end of file + + + + <?php echo __("Error Page"); ?> + + + + + +
+ +
+

+

+
+

+

+

+ +

+ +

+ "); echo htmlentities(""); echo __(" and change AllowOverride None to AllowOverride All"); ?> +

+

sudo nano /etc/apache2/apache2.conf

+ +

+ +

+


+          Options Indexes FollowSymLinks
+          AllowOverride All
+          Require all granted
+  "); ?>

+ +

"); ?> +

sudo a2enmod rewrite

+ +

+ +

sudo /etc/init.d/apache2 restart

+ +

+ +

sudo service apache2 restart

+ +
+
+ + +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 +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__); diff --git a/install/database.sql b/install/database.sql index b1870bd17f..da6fe2a4eb 100644 --- a/install/database.sql +++ b/install/database.sql @@ -1,600 +1,600 @@ --- MySQL Workbench Forward Engineering - -SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; -SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; -SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; - --- ----------------------------------------------------- --- Table `users` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `users` ( - `id` INT NOT NULL AUTO_INCREMENT, - `user` VARCHAR(45) NOT NULL, - `name` VARCHAR(45) NULL, - `email` VARCHAR(254) NULL, - `password` VARCHAR(145) NOT NULL, - `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - `modified` DATETIME NOT NULL, - `isAdmin` TINYINT(1) NOT NULL DEFAULT 0, - `status` ENUM('a', 'i') NOT NULL DEFAULT 'a', - `photoURL` VARCHAR(255) NULL, - `lastLogin` DATETIME NULL, - `recoverPass` VARCHAR(255) NULL, - `backgroundURL` VARCHAR(255) NULL, - `canStream` TINYINT(1) NULL, - `canUpload` TINYINT(1) NULL, - `canCreateMeet` TINYINT(1) NULL, - `canViewChart` TINYINT(1) NOT NULL DEFAULT 0, - `about` TEXT NULL, - `channelName` VARCHAR(45) NULL, - `emailVerified` TINYINT(1) NOT NULL DEFAULT 0, - `analyticsCode` VARCHAR(45) NULL DEFAULT NULL, - `externalOptions` TEXT NULL, - `first_name` VARCHAR(255) NULL DEFAULT NULL, - `last_name` VARCHAR(255) NULL DEFAULT NULL, - `address` VARCHAR(255) NULL DEFAULT NULL, - `zip_code` VARCHAR(45) NULL DEFAULT NULL, - `country` VARCHAR(100) NULL DEFAULT NULL, - `region` VARCHAR(100) NULL DEFAULT NULL, - `city` VARCHAR(100) NULL DEFAULT NULL, - `donationLink` VARCHAR(225) NULL DEFAULT NULL, - `extra_info` TEXT NULL DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE INDEX `user_UNIQUE` (`user` ASC)) -ENGINE = InnoDB; - - -CREATE TABLE IF NOT EXISTS `users_blob` ( - `id` INT NOT NULL AUTO_INCREMENT, - `blob` LONGBLOB NULL, - `users_id` INT NOT NULL, - `created` DATETIME NULL, - `modified` DATETIME NULL, - `type` VARCHAR(45) NULL, - PRIMARY KEY (`id`), - INDEX `fk_users_document_image_users1_idx` (`users_id` ASC), - CONSTRAINT `fk_users_document_image_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `categories` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `categories` ( - `id` INT NOT NULL AUTO_INCREMENT, - `name` VARCHAR(45) NOT NULL, - `clean_name` VARCHAR(45) NOT NULL, - `description` TEXT NULL, - `nextVideoOrder` INT(2) NOT NULL DEFAULT '0', - `parentId` INT NOT NULL DEFAULT '0', - `created` DATETIME NOT NULL, - `modified` DATETIME NOT NULL, - `iconClass` VARCHAR(45) NOT NULL DEFAULT 'fa fa-folder', - `users_id` INT(11) NOT NULL DEFAULT 1, - `private` TINYINT(1) NULL DEFAULT 0, - `allow_download` TINYINT(1) NULL DEFAULT 1, - `order` INT(11) NULL DEFAULT NULL, - `suggested` TINYINT(1) NULL DEFAULT NULL, - PRIMARY KEY (`id`), - INDEX `fk_categories_users1_idx` (`users_id` ASC), - INDEX `clean_name_INDEX2` (`clean_name` ASC), - INDEX `sortcategoryOrderIndex` (`order` ASC), - INDEX `category_name_idx` (`name` ASC), - INDEX `categoriesindex9suggested` (`suggested` ASC), - FULLTEXT INDEX `index7cname` (`name`), - FULLTEXT INDEX `index8cdescr` (`description`), - UNIQUE INDEX `clean_name_UNIQUE` (`clean_name` ASC), - CONSTRAINT `fk_categories_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - -CREATE TABLE IF NOT EXISTS `sites` ( - `id` INT(11) NOT NULL AUTO_INCREMENT, - `name` VARCHAR(255) NULL DEFAULT NULL, - `url` VARCHAR(255) NOT NULL, - `created` DATETIME NULL DEFAULT NULL, - `modified` DATETIME NULL DEFAULT NULL, - `status` CHAR(1) NULL DEFAULT NULL, - `secret` VARCHAR(255) NOT NULL, - PRIMARY KEY (`id`)) -ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `videos` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `videos` ( - `id` INT NOT NULL AUTO_INCREMENT, - `title` VARCHAR(190) NOT NULL, - `clean_title` VARCHAR(190) NOT NULL, - `description` TEXT NULL, - `views_count` INT NOT NULL DEFAULT 0, - `views_count_25` INT(11) NULL DEFAULT 0, - `views_count_50` INT(11) NULL DEFAULT 0, - `views_count_75` INT(11) NULL DEFAULT 0, - `views_count_100` INT(11) NULL DEFAULT 0, - `status` VARCHAR(16) NOT NULL DEFAULT 'e' , - `created` DATETIME NOT NULL, - `modified` DATETIME NOT NULL, - `users_id` INT NOT NULL, - `categories_id` INT NOT NULL, - `filename` VARCHAR(255) NOT NULL, - `duration` VARCHAR(15) NOT NULL, - `type` ENUM('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'zip') NOT NULL DEFAULT 'video', - `videoDownloadedLink` VARCHAR(255) NULL, - `order` INT UNSIGNED NOT NULL DEFAULT 1, - `rotation` SMALLINT NULL DEFAULT 0, - `zoom` FLOAT NULL DEFAULT 1, - `youtubeId` VARCHAR(45) NULL, - `videoLink` VARCHAR(255) NULL, - `next_videos_id` INT NULL, - `isSuggested` INT(1) NOT NULL DEFAULT 0, - `trailer1` VARCHAR(255) NULL DEFAULT NULL, - `trailer2` VARCHAR(255) NULL DEFAULT NULL, - `trailer3` VARCHAR(255) NULL DEFAULT NULL, - `rate` FLOAT(4,2) NULL DEFAULT NULL, - `can_download` TINYINT(1) NULL DEFAULT NULL, - `can_share` TINYINT(1) NULL DEFAULT NULL, - `rrating` VARCHAR(45) NULL DEFAULT NULL, - `externalOptions` TEXT NULL DEFAULT NULL, - `only_for_paid` TINYINT(1) NULL DEFAULT NULL, - `serie_playlists_id` INT(11) NULL DEFAULT NULL, - `sites_id` INT(11) NULL, - `video_password` VARCHAR(45) NULL DEFAULT NULL, - `encoderURL` VARCHAR(255) NULL DEFAULT NULL, - `filepath` VARCHAR(255) NULL DEFAULT NULL, - `filesize` BIGINT(19) UNSIGNED NULL DEFAULT 0, - `live_transmitions_history_id` INT(11) NULL DEFAULT NULL, - `total_seconds_watching` INT(11) NULL DEFAULT 0, - `duration_in_seconds` INT NULL DEFAULT NULL, - `likes` INT(11) NULL DEFAULT NULL, - `dislikes` INT(11) NULL DEFAULT NULL, - PRIMARY KEY (`id`), - INDEX `fk_videos_users_idx` (`users_id` ASC), - INDEX `fk_videos_categories1_idx` (`categories_id` ASC), - UNIQUE INDEX `clean_title_UNIQUE` (`clean_title` ASC), - INDEX `index5` (`order` ASC), - INDEX `fk_videos_videos1_idx` (`next_videos_id` ASC), - INDEX `fk_videos_sites1_idx` (`sites_id` ASC), - INDEX `clean_title_INDEX` (`clean_title` ASC), - INDEX `video_filename_INDEX` (`filename` ASC), - INDEX `video_status_idx` (`status` ASC), - INDEX `video_type_idx` (`type` ASC) , - INDEX `videos_likes_index` (`likes` ASC), - INDEX `videos_dislikes_index` (`dislikes` ASC), - INDEX `fk_videos_live_transmitions_history1_idx` (`live_transmitions_history_id` ASC), - INDEX `total_sec_watchinindex` (`total_seconds_watching` ASC), - FULLTEXT INDEX `index17vname` (`title`), - FULLTEXT INDEX `index18vdesc` (`description`), - CONSTRAINT `fk_videos_sites1` - FOREIGN KEY (`sites_id`) - REFERENCES `sites` (`id`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_videos_users` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_videos_categories1` - FOREIGN KEY (`categories_id`) - REFERENCES `categories` (`id`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT `fk_videos_videos1` - FOREIGN KEY (`next_videos_id`) - REFERENCES `videos` (`id`) - ON DELETE NO ACTION - ON UPDATE NO ACTION, -CONSTRAINT `fk_videos_playlists1` - FOREIGN KEY (`serie_playlists_id`) - REFERENCES `playlists` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - -CREATE TABLE IF NOT EXISTS `videos_metadata` ( - `id` INT NOT NULL AUTO_INCREMENT, - `videos_id` INT NOT NULL, - `resolution` VARCHAR(12) NOT NULL, - `format` VARCHAR(12) NOT NULL, - `stream_id` INT NOT NULL, - `name` VARCHAR(128) NOT NULL, - `value` VARCHAR(255) NOT NULL, - PRIMARY KEY (`id`), - UNIQUE (`videos_id`, `resolution`, `format`, `stream_id`, `name`), - INDEX `fk_videos_metadata_videos1_idx` (`videos_id` ASC), - CONSTRAINT `fk_videos_metadata_videos1` - FOREIGN KEY (`videos_id`) - REFERENCES `videos` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE -) ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `comments` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `comments` ( - `id` INT NOT NULL AUTO_INCREMENT, - `comment` TEXT NOT NULL, - `videos_id` INT NOT NULL, - `users_id` INT NOT NULL, - `created` DATETIME NOT NULL, - `modified` DATETIME NOT NULL, - `comments_id_pai` INT NULL, - `pin` INT(1) NOT NULL DEFAULT 0 COMMENT 'If = 1 will be on the top', - PRIMARY KEY (`id`), - INDEX `fk_comments_videos1_idx` (`videos_id` ASC), - INDEX `fk_comments_users1_idx` (`users_id` ASC), - INDEX `fk_comments_comments1_idx` (`comments_id_pai` ASC), - CONSTRAINT `fk_comments_videos1` - FOREIGN KEY (`videos_id`) - REFERENCES `videos` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_comments_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_comments_comments1` - FOREIGN KEY (`comments_id_pai`) - REFERENCES `comments` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `configurations` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `configurations` ( - `id` INT NOT NULL, - `video_resolution` VARCHAR(12) NOT NULL, - `users_id` INT NOT NULL, - `version` VARCHAR(10) NOT NULL, - `webSiteTitle` VARCHAR(45) NOT NULL DEFAULT 'AVideo', - `language` VARCHAR(6) NOT NULL DEFAULT 'en', - `contactEmail` VARCHAR(254) NOT NULL, - `modified` DATETIME NOT NULL, - `created` DATETIME NOT NULL, - `authGoogle_id` VARCHAR(255) NULL, - `authGoogle_key` VARCHAR(255) NULL, - `authGoogle_enabled` TINYINT(1) NOT NULL DEFAULT 0, - `authFacebook_id` VARCHAR(255) NULL, - `authFacebook_key` VARCHAR(255) NULL, - `authFacebook_enabled` TINYINT(1) NOT NULL DEFAULT 0, - `authCanUploadVideos` TINYINT(1) NOT NULL DEFAULT 0, - `authCanViewChart` TINYINT(2) NOT NULL DEFAULT 0, - `authCanComment` TINYINT(1) NOT NULL DEFAULT 1, - `head` TEXT NULL, - `logo` VARCHAR(255) NULL, - `logo_small` VARCHAR(255) NULL, - `adsense` TEXT NULL, - `mode` ENUM('Youtube', 'Gallery') NULL DEFAULT 'Youtube', - `disable_analytics` TINYINT(1) NULL DEFAULT 0, - `disable_youtubeupload` TINYINT(1) NULL DEFAULT 0, - `allow_download` TINYINT(1) NULL DEFAULT 0, - `session_timeout` INT NULL DEFAULT 3600, - `autoplay` TINYINT(1) NULL, - `theme` VARCHAR(45) NULL DEFAULT 'default', - `smtp` TINYINT(1) NULL, - `smtpAuth` TINYINT(1) NULL, - `smtpSecure` VARCHAR(255) NULL COMMENT '\'ssl\'; // secure transfer enabled REQUIRED for Gmail', - `smtpHost` VARCHAR(255) NULL COMMENT '\"smtp.gmail.com\"', - `smtpUsername` VARCHAR(255) NULL COMMENT '\"email@gmail.com\"', - `smtpPassword` VARCHAR(255) NULL, - `smtpPort` INT NULL, - `encoderURL` VARCHAR(255) NULL, - PRIMARY KEY (`id`), - INDEX `fk_configurations_users1_idx` (`users_id` ASC), - CONSTRAINT `fk_configurations_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE NO ACTION - ON UPDATE NO ACTION) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `videos_statistics` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `videos_statistics` ( - `id` INT NOT NULL AUTO_INCREMENT, - `when` DATETIME NOT NULL, - `ip` VARCHAR(45) NULL, - `users_id` INT NULL, - `videos_id` INT NOT NULL, - `created` DATETIME NULL DEFAULT NULL, - `modified` DATETIME NULL DEFAULT NULL, - `lastVideoTime` INT(11) NULL DEFAULT NULL, - `session_id` VARCHAR(45) NOT NULL, - `seconds_watching_video` INT(11) NULL DEFAULT NULL, - `json` TEXT NULL DEFAULT NULL, - PRIMARY KEY (`id`), - INDEX `fk_videos_statistics_users1_idx` (`users_id` ASC), - INDEX `fk_videos_statistics_videos1_idx` (`videos_id` ASC), - INDEX `when_statisci` (`when` ASC), - INDEX `session_id_statistics` (`session_id` ASC), - INDEX `sec_watchin_videos` (`seconds_watching_video` ASC), - CONSTRAINT `fk_videos_statistics_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_videos_statistics_videos1` - FOREIGN KEY (`videos_id`) - REFERENCES `videos` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `likes` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `likes` ( - `id` INT NOT NULL AUTO_INCREMENT, - `like` INT(1) NOT NULL DEFAULT 0 COMMENT '1 = Like\n0 = Does not metter\n-1 = Dislike', - `created` DATETIME NULL, - `modified` DATETIME NULL, - `videos_id` INT NOT NULL, - `users_id` INT NOT NULL, - PRIMARY KEY (`id`), - INDEX `fk_likes_videos1_idx` (`videos_id` ASC), - INDEX `fk_likes_users1_idx` (`users_id` ASC), - INDEX `likes_likes_idx` (`like` ASC), - CONSTRAINT `fk_likes_videos1` - FOREIGN KEY (`videos_id`) - REFERENCES `videos` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_likes_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `users_groups` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `users_groups` ( - `id` INT NOT NULL AUTO_INCREMENT, - `group_name` VARCHAR(255) NULL, - `created` DATETIME NULL, - `modified` DATETIME NULL, - PRIMARY KEY (`id`)) -ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `users_has_users_groups` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `users_has_users_groups` ( - `users_id` INT NOT NULL, - `users_groups_id` INT NOT NULL, - PRIMARY KEY (`users_id`, `users_groups_id`), - INDEX `fk_users_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), - INDEX `fk_users_has_users_groups_users1_idx` (`users_id` ASC), - UNIQUE INDEX `index_user_groups_unique` (`users_groups_id` ASC, `users_id` ASC), - CONSTRAINT `fk_users_has_users_groups_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_users_has_users_groups_users_groups1` - FOREIGN KEY (`users_groups_id`) - REFERENCES `users_groups` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `videos_group_view` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `videos_group_view` ( - `id` INT NOT NULL AUTO_INCREMENT, - `users_groups_id` INT NOT NULL, - `videos_id` INT NOT NULL, - INDEX `fk_videos_group_view_users_groups1_idx` (`users_groups_id` ASC), - INDEX `fk_videos_group_view_videos1_idx` (`videos_id` ASC), - PRIMARY KEY (`id`), - CONSTRAINT `fk_videos_group_view_users_groups1` - FOREIGN KEY (`users_groups_id`) - REFERENCES `users_groups` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_videos_group_view_videos1` - FOREIGN KEY (`videos_id`) - REFERENCES `videos` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `subscribes` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `subscribes` ( - `id` INT NOT NULL AUTO_INCREMENT, - `email` VARCHAR(100) NOT NULL, - `status` ENUM('a', 'i') NOT NULL DEFAULT 'a', - `created` DATETIME NULL, - `modified` DATETIME NULL, - `ip` VARCHAR(45) NULL, - `users_id` INT NOT NULL DEFAULT 1 COMMENT 'subscribes to user channel', - `notify` TINYINT(1) NOT NULL DEFAULT 1, - `subscriber_users_id` INT(11) NOT NULL, - PRIMARY KEY (`id`), - INDEX `fk_subscribes_users1_idx` (`users_id` ASC), - INDEX `fk_subscribes_users2_idx` (`subscriber_users_id` ASC), - CONSTRAINT `fk_subscribes_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_subscribes_users2` - FOREIGN KEY (`subscriber_users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `playlists` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `playlists` ( - `id` INT(11) NOT NULL AUTO_INCREMENT, - `name` VARCHAR(45) NOT NULL, - `created` DATETIME NULL DEFAULT NULL, - `modified` DATETIME NULL DEFAULT NULL, - `users_id` INT(11) NOT NULL, - `status` ENUM('public', 'private', 'unlisted', 'favorite', 'watch_later') NOT NULL DEFAULT 'public', - `showOnTV` TINYINT NULL, - PRIMARY KEY (`id`), - INDEX `fk_playlists_users1_idx` (`users_id` ASC), - INDEX `showOnTVindex3` (`showOnTV` ASC), - CONSTRAINT `fk_playlists_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `playlists_has_videos` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `playlists_has_videos` ( - `playlists_id` INT NOT NULL, - `videos_id` INT NOT NULL, - `order` INT NULL, - PRIMARY KEY (`playlists_id`, `videos_id`), - INDEX `fk_playlists_has_videos_videos1_idx` (`videos_id` ASC), - INDEX `fk_playlists_has_videos_playlists1_idx` (`playlists_id` ASC), - CONSTRAINT `fk_playlists_has_videos_playlists1` - FOREIGN KEY (`playlists_id`) - REFERENCES `playlists` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_playlists_has_videos_videos1` - FOREIGN KEY (`videos_id`) - REFERENCES `videos` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `plugins` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `plugins` ( - `id` INT NOT NULL AUTO_INCREMENT, - `uuid` VARCHAR(45) NOT NULL, - `status` ENUM('active', 'inactive') NOT NULL DEFAULT 'active', - `created` DATETIME NULL, - `modified` DATETIME NULL, - `object_data` TEXT NULL, - `name` VARCHAR(255) NOT NULL, - `dirName` VARCHAR(255) NOT NULL, - `pluginversion` VARCHAR(6) NULL, - PRIMARY KEY (`id`), - UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC)) -ENGINE = InnoDB; - - --- ----------------------------------------------------- --- Table `comments_likes` --- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `comments_likes` ( - `id` INT NOT NULL AUTO_INCREMENT, - `like` INT(1) NOT NULL, - `created` DATETIME NULL, - `modified` DATETIME NULL, - `users_id` INT NOT NULL, - `comments_id` INT NOT NULL, - PRIMARY KEY (`id`), - INDEX `fk_comments_likes_users1_idx` (`users_id` ASC), - INDEX `fk_comments_likes_comments1_idx` (`comments_id` ASC), - CONSTRAINT `fk_comments_likes_users1` - FOREIGN KEY (`users_id`) - REFERENCES `users` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_comments_likes_comments1` - FOREIGN KEY (`comments_id`) - REFERENCES `comments` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - --- ----------------------------------------------------- --- Table `category_type_cache` --- ----------------------------------------------------- -CREATE TABLE `category_type_cache` ( - `categoryId` int(11) NOT NULL, - `type` int(2) NOT NULL COMMENT '0=both, 1=audio, 2=video' DEFAULT 0, - `manualSet` int(1) NOT NULL COMMENT '0=auto, 1=manual' DEFAULT 0 - -) ENGINE=InnoDB; - -CREATE TABLE IF NOT EXISTS `categories_has_users_groups` ( - `id` INT NOT NULL AUTO_INCREMENT, - `categories_id` INT(11) NOT NULL, - `users_groups_id` INT(11) NOT NULL, - `created` DATETIME NULL, - `modified` DATETIME NULL, - `status` CHAR(1) NOT NULL DEFAULT 'a', - PRIMARY KEY (`id`), - INDEX `fk_categories_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), - INDEX `fk_categories_has_users_groups_categories1_idx` (`categories_id` ASC), - CONSTRAINT `fk_categories_has_users_groups_categories1` - FOREIGN KEY (`categories_id`) - REFERENCES `categories` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE, - CONSTRAINT `fk_categories_has_users_groups_users_groups1` - FOREIGN KEY (`users_groups_id`) - REFERENCES `users_groups` (`id`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB; - -CREATE TABLE IF NOT EXISTS `users_extra_info` ( - `id` INT NOT NULL AUTO_INCREMENT, - `field_name` VARCHAR(45) NOT NULL, - `field_type` VARCHAR(45) NOT NULL, - `field_options` TEXT NULL, - `field_default_value` VARCHAR(45) NULL, - `parameters` TEXT NULL, - `created` DATETIME NULL, - `modified` DATETIME NULL, - `status` CHAR(1) NOT NULL DEFAULT 'a', - `order` INT NOT NULL DEFAULT 0, - PRIMARY KEY (`id`), - INDEX `ordersortusers_extra_info` USING BTREE (`order`)) -ENGINE = InnoDB; - -ALTER TABLE `category_type_cache` - ADD UNIQUE KEY `categoryId` (`categoryId`); - -ALTER TABLE `plugins` -ADD INDEX `plugin_status` (`status` ASC); - -ALTER TABLE `videos` -ADD INDEX `videos_status_index` (`status` ASC), -ADD INDEX `is_suggested_index` (`isSuggested` ASC), -ADD INDEX `views_count_index` (`views_count` ASC), -ADD INDEX `filename_index` (`filename` ASC); - -COMMIT; - -SET SQL_MODE=@OLD_SQL_MODE; -SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; -SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; +-- MySQL Workbench Forward Engineering + +SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; +SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; +SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; + +-- ----------------------------------------------------- +-- Table `users` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `users` ( + `id` INT NOT NULL AUTO_INCREMENT, + `user` VARCHAR(45) NOT NULL, + `name` VARCHAR(45) NULL, + `email` VARCHAR(254) NULL, + `password` VARCHAR(145) NOT NULL, + `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `modified` DATETIME NOT NULL, + `isAdmin` TINYINT(1) NOT NULL DEFAULT 0, + `status` ENUM('a', 'i') NOT NULL DEFAULT 'a', + `photoURL` VARCHAR(255) NULL, + `lastLogin` DATETIME NULL, + `recoverPass` VARCHAR(255) NULL, + `backgroundURL` VARCHAR(255) NULL, + `canStream` TINYINT(1) NULL, + `canUpload` TINYINT(1) NULL, + `canCreateMeet` TINYINT(1) NULL, + `canViewChart` TINYINT(1) NOT NULL DEFAULT 0, + `about` TEXT NULL, + `channelName` VARCHAR(45) NULL, + `emailVerified` TINYINT(1) NOT NULL DEFAULT 0, + `analyticsCode` VARCHAR(45) NULL DEFAULT NULL, + `externalOptions` TEXT NULL, + `first_name` VARCHAR(255) NULL DEFAULT NULL, + `last_name` VARCHAR(255) NULL DEFAULT NULL, + `address` VARCHAR(255) NULL DEFAULT NULL, + `zip_code` VARCHAR(45) NULL DEFAULT NULL, + `country` VARCHAR(100) NULL DEFAULT NULL, + `region` VARCHAR(100) NULL DEFAULT NULL, + `city` VARCHAR(100) NULL DEFAULT NULL, + `donationLink` VARCHAR(225) NULL DEFAULT NULL, + `extra_info` TEXT NULL DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `user_UNIQUE` (`user` ASC)) +ENGINE = InnoDB; + + +CREATE TABLE IF NOT EXISTS `users_blob` ( + `id` INT NOT NULL AUTO_INCREMENT, + `blob` LONGBLOB NULL, + `users_id` INT NOT NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + `type` VARCHAR(45) NULL, + PRIMARY KEY (`id`), + INDEX `fk_users_document_image_users1_idx` (`users_id` ASC), + CONSTRAINT `fk_users_document_image_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `categories` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `categories` ( + `id` INT NOT NULL AUTO_INCREMENT, + `name` VARCHAR(45) NOT NULL, + `clean_name` VARCHAR(45) NOT NULL, + `description` TEXT NULL, + `nextVideoOrder` INT(2) NOT NULL DEFAULT '0', + `parentId` INT NOT NULL DEFAULT '0', + `created` DATETIME NOT NULL, + `modified` DATETIME NOT NULL, + `iconClass` VARCHAR(45) NOT NULL DEFAULT 'fa fa-folder', + `users_id` INT(11) NOT NULL DEFAULT 1, + `private` TINYINT(1) NULL DEFAULT 0, + `allow_download` TINYINT(1) NULL DEFAULT 1, + `order` INT(11) NULL DEFAULT NULL, + `suggested` TINYINT(1) NULL DEFAULT NULL, + PRIMARY KEY (`id`), + INDEX `fk_categories_users1_idx` (`users_id` ASC), + INDEX `clean_name_INDEX2` (`clean_name` ASC), + INDEX `sortcategoryOrderIndex` (`order` ASC), + INDEX `category_name_idx` (`name` ASC), + INDEX `categoriesindex9suggested` (`suggested` ASC), + FULLTEXT INDEX `index7cname` (`name`), + FULLTEXT INDEX `index8cdescr` (`description`), + UNIQUE INDEX `clean_name_UNIQUE` (`clean_name` ASC), + CONSTRAINT `fk_categories_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS `sites` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(255) NULL DEFAULT NULL, + `url` VARCHAR(255) NOT NULL, + `created` DATETIME NULL DEFAULT NULL, + `modified` DATETIME NULL DEFAULT NULL, + `status` CHAR(1) NULL DEFAULT NULL, + `secret` VARCHAR(255) NOT NULL, + PRIMARY KEY (`id`)) +ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `videos` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `videos` ( + `id` INT NOT NULL AUTO_INCREMENT, + `title` VARCHAR(190) NOT NULL, + `clean_title` VARCHAR(190) NOT NULL, + `description` TEXT NULL, + `views_count` INT NOT NULL DEFAULT 0, + `views_count_25` INT(11) NULL DEFAULT 0, + `views_count_50` INT(11) NULL DEFAULT 0, + `views_count_75` INT(11) NULL DEFAULT 0, + `views_count_100` INT(11) NULL DEFAULT 0, + `status` VARCHAR(16) NOT NULL DEFAULT 'e' , + `created` DATETIME NOT NULL, + `modified` DATETIME NOT NULL, + `users_id` INT NOT NULL, + `categories_id` INT NOT NULL, + `filename` VARCHAR(255) NOT NULL, + `duration` VARCHAR(15) NOT NULL, + `type` ENUM('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'zip') NOT NULL DEFAULT 'video', + `videoDownloadedLink` VARCHAR(255) NULL, + `order` INT UNSIGNED NOT NULL DEFAULT 1, + `rotation` SMALLINT NULL DEFAULT 0, + `zoom` FLOAT NULL DEFAULT 1, + `youtubeId` VARCHAR(45) NULL, + `videoLink` VARCHAR(255) NULL, + `next_videos_id` INT NULL, + `isSuggested` INT(1) NOT NULL DEFAULT 0, + `trailer1` VARCHAR(255) NULL DEFAULT NULL, + `trailer2` VARCHAR(255) NULL DEFAULT NULL, + `trailer3` VARCHAR(255) NULL DEFAULT NULL, + `rate` FLOAT(4,2) NULL DEFAULT NULL, + `can_download` TINYINT(1) NULL DEFAULT NULL, + `can_share` TINYINT(1) NULL DEFAULT NULL, + `rrating` VARCHAR(45) NULL DEFAULT NULL, + `externalOptions` TEXT NULL DEFAULT NULL, + `only_for_paid` TINYINT(1) NULL DEFAULT NULL, + `serie_playlists_id` INT(11) NULL DEFAULT NULL, + `sites_id` INT(11) NULL, + `video_password` VARCHAR(45) NULL DEFAULT NULL, + `encoderURL` VARCHAR(255) NULL DEFAULT NULL, + `filepath` VARCHAR(255) NULL DEFAULT NULL, + `filesize` BIGINT(19) UNSIGNED NULL DEFAULT 0, + `live_transmitions_history_id` INT(11) NULL DEFAULT NULL, + `total_seconds_watching` INT(11) NULL DEFAULT 0, + `duration_in_seconds` INT NULL DEFAULT NULL, + `likes` INT(11) NULL DEFAULT NULL, + `dislikes` INT(11) NULL DEFAULT NULL, + PRIMARY KEY (`id`), + INDEX `fk_videos_users_idx` (`users_id` ASC), + INDEX `fk_videos_categories1_idx` (`categories_id` ASC), + UNIQUE INDEX `clean_title_UNIQUE` (`clean_title` ASC), + INDEX `index5` (`order` ASC), + INDEX `fk_videos_videos1_idx` (`next_videos_id` ASC), + INDEX `fk_videos_sites1_idx` (`sites_id` ASC), + INDEX `clean_title_INDEX` (`clean_title` ASC), + INDEX `video_filename_INDEX` (`filename` ASC), + INDEX `video_status_idx` (`status` ASC), + INDEX `video_type_idx` (`type` ASC) , + INDEX `videos_likes_index` (`likes` ASC), + INDEX `videos_dislikes_index` (`dislikes` ASC), + INDEX `fk_videos_live_transmitions_history1_idx` (`live_transmitions_history_id` ASC), + INDEX `total_sec_watchinindex` (`total_seconds_watching` ASC), + FULLTEXT INDEX `index17vname` (`title`), + FULLTEXT INDEX `index18vdesc` (`description`), + CONSTRAINT `fk_videos_sites1` + FOREIGN KEY (`sites_id`) + REFERENCES `sites` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT `fk_videos_users` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT `fk_videos_categories1` + FOREIGN KEY (`categories_id`) + REFERENCES `categories` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT `fk_videos_videos1` + FOREIGN KEY (`next_videos_id`) + REFERENCES `videos` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION, +CONSTRAINT `fk_videos_playlists1` + FOREIGN KEY (`serie_playlists_id`) + REFERENCES `playlists` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS `videos_metadata` ( + `id` INT NOT NULL AUTO_INCREMENT, + `videos_id` INT NOT NULL, + `resolution` VARCHAR(12) NOT NULL, + `format` VARCHAR(12) NOT NULL, + `stream_id` INT NOT NULL, + `name` VARCHAR(128) NOT NULL, + `value` VARCHAR(255) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE (`videos_id`, `resolution`, `format`, `stream_id`, `name`), + INDEX `fk_videos_metadata_videos1_idx` (`videos_id` ASC), + CONSTRAINT `fk_videos_metadata_videos1` + FOREIGN KEY (`videos_id`) + REFERENCES `videos` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE +) ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `comments` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `comments` ( + `id` INT NOT NULL AUTO_INCREMENT, + `comment` TEXT NOT NULL, + `videos_id` INT NOT NULL, + `users_id` INT NOT NULL, + `created` DATETIME NOT NULL, + `modified` DATETIME NOT NULL, + `comments_id_pai` INT NULL, + `pin` INT(1) NOT NULL DEFAULT 0 COMMENT 'If = 1 will be on the top', + PRIMARY KEY (`id`), + INDEX `fk_comments_videos1_idx` (`videos_id` ASC), + INDEX `fk_comments_users1_idx` (`users_id` ASC), + INDEX `fk_comments_comments1_idx` (`comments_id_pai` ASC), + CONSTRAINT `fk_comments_videos1` + FOREIGN KEY (`videos_id`) + REFERENCES `videos` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_comments_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_comments_comments1` + FOREIGN KEY (`comments_id_pai`) + REFERENCES `comments` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `configurations` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `configurations` ( + `id` INT NOT NULL, + `video_resolution` VARCHAR(12) NOT NULL, + `users_id` INT NOT NULL, + `version` VARCHAR(10) NOT NULL, + `webSiteTitle` VARCHAR(45) NOT NULL DEFAULT 'AVideo', + `language` VARCHAR(6) NOT NULL DEFAULT 'en', + `contactEmail` VARCHAR(254) NOT NULL, + `modified` DATETIME NOT NULL, + `created` DATETIME NOT NULL, + `authGoogle_id` VARCHAR(255) NULL, + `authGoogle_key` VARCHAR(255) NULL, + `authGoogle_enabled` TINYINT(1) NOT NULL DEFAULT 0, + `authFacebook_id` VARCHAR(255) NULL, + `authFacebook_key` VARCHAR(255) NULL, + `authFacebook_enabled` TINYINT(1) NOT NULL DEFAULT 0, + `authCanUploadVideos` TINYINT(1) NOT NULL DEFAULT 0, + `authCanViewChart` TINYINT(2) NOT NULL DEFAULT 0, + `authCanComment` TINYINT(1) NOT NULL DEFAULT 1, + `head` TEXT NULL, + `logo` VARCHAR(255) NULL, + `logo_small` VARCHAR(255) NULL, + `adsense` TEXT NULL, + `mode` ENUM('Youtube', 'Gallery') NULL DEFAULT 'Youtube', + `disable_analytics` TINYINT(1) NULL DEFAULT 0, + `disable_youtubeupload` TINYINT(1) NULL DEFAULT 0, + `allow_download` TINYINT(1) NULL DEFAULT 0, + `session_timeout` INT NULL DEFAULT 3600, + `autoplay` TINYINT(1) NULL, + `theme` VARCHAR(45) NULL DEFAULT 'default', + `smtp` TINYINT(1) NULL, + `smtpAuth` TINYINT(1) NULL, + `smtpSecure` VARCHAR(255) NULL COMMENT '\'ssl\'; // secure transfer enabled REQUIRED for Gmail', + `smtpHost` VARCHAR(255) NULL COMMENT '\"smtp.gmail.com\"', + `smtpUsername` VARCHAR(255) NULL COMMENT '\"email@gmail.com\"', + `smtpPassword` VARCHAR(255) NULL, + `smtpPort` INT NULL, + `encoderURL` VARCHAR(255) NULL, + PRIMARY KEY (`id`), + INDEX `fk_configurations_users1_idx` (`users_id` ASC), + CONSTRAINT `fk_configurations_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE NO ACTION + ON UPDATE NO ACTION) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `videos_statistics` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `videos_statistics` ( + `id` INT NOT NULL AUTO_INCREMENT, + `when` DATETIME NOT NULL, + `ip` VARCHAR(45) NULL, + `users_id` INT NULL, + `videos_id` INT NOT NULL, + `created` DATETIME NULL DEFAULT NULL, + `modified` DATETIME NULL DEFAULT NULL, + `lastVideoTime` INT(11) NULL DEFAULT NULL, + `session_id` VARCHAR(45) NOT NULL, + `seconds_watching_video` INT(11) NULL DEFAULT NULL, + `json` TEXT NULL DEFAULT NULL, + PRIMARY KEY (`id`), + INDEX `fk_videos_statistics_users1_idx` (`users_id` ASC), + INDEX `fk_videos_statistics_videos1_idx` (`videos_id` ASC), + INDEX `when_statisci` (`when` ASC), + INDEX `session_id_statistics` (`session_id` ASC), + INDEX `sec_watchin_videos` (`seconds_watching_video` ASC), + CONSTRAINT `fk_videos_statistics_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_videos_statistics_videos1` + FOREIGN KEY (`videos_id`) + REFERENCES `videos` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `likes` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `likes` ( + `id` INT NOT NULL AUTO_INCREMENT, + `like` INT(1) NOT NULL DEFAULT 0 COMMENT '1 = Like\n0 = Does not metter\n-1 = Dislike', + `created` DATETIME NULL, + `modified` DATETIME NULL, + `videos_id` INT NOT NULL, + `users_id` INT NOT NULL, + PRIMARY KEY (`id`), + INDEX `fk_likes_videos1_idx` (`videos_id` ASC), + INDEX `fk_likes_users1_idx` (`users_id` ASC), + INDEX `likes_likes_idx` (`like` ASC), + CONSTRAINT `fk_likes_videos1` + FOREIGN KEY (`videos_id`) + REFERENCES `videos` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_likes_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `users_groups` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `users_groups` ( + `id` INT NOT NULL AUTO_INCREMENT, + `group_name` VARCHAR(255) NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + PRIMARY KEY (`id`)) +ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `users_has_users_groups` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `users_has_users_groups` ( + `users_id` INT NOT NULL, + `users_groups_id` INT NOT NULL, + PRIMARY KEY (`users_id`, `users_groups_id`), + INDEX `fk_users_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), + INDEX `fk_users_has_users_groups_users1_idx` (`users_id` ASC), + UNIQUE INDEX `index_user_groups_unique` (`users_groups_id` ASC, `users_id` ASC), + CONSTRAINT `fk_users_has_users_groups_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_users_has_users_groups_users_groups1` + FOREIGN KEY (`users_groups_id`) + REFERENCES `users_groups` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `videos_group_view` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `videos_group_view` ( + `id` INT NOT NULL AUTO_INCREMENT, + `users_groups_id` INT NOT NULL, + `videos_id` INT NOT NULL, + INDEX `fk_videos_group_view_users_groups1_idx` (`users_groups_id` ASC), + INDEX `fk_videos_group_view_videos1_idx` (`videos_id` ASC), + PRIMARY KEY (`id`), + CONSTRAINT `fk_videos_group_view_users_groups1` + FOREIGN KEY (`users_groups_id`) + REFERENCES `users_groups` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_videos_group_view_videos1` + FOREIGN KEY (`videos_id`) + REFERENCES `videos` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `subscribes` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `subscribes` ( + `id` INT NOT NULL AUTO_INCREMENT, + `email` VARCHAR(100) NOT NULL, + `status` ENUM('a', 'i') NOT NULL DEFAULT 'a', + `created` DATETIME NULL, + `modified` DATETIME NULL, + `ip` VARCHAR(45) NULL, + `users_id` INT NOT NULL DEFAULT 1 COMMENT 'subscribes to user channel', + `notify` TINYINT(1) NOT NULL DEFAULT 1, + `subscriber_users_id` INT(11) NOT NULL, + PRIMARY KEY (`id`), + INDEX `fk_subscribes_users1_idx` (`users_id` ASC), + INDEX `fk_subscribes_users2_idx` (`subscriber_users_id` ASC), + CONSTRAINT `fk_subscribes_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_subscribes_users2` + FOREIGN KEY (`subscriber_users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `playlists` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `playlists` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `name` VARCHAR(45) NOT NULL, + `created` DATETIME NULL DEFAULT NULL, + `modified` DATETIME NULL DEFAULT NULL, + `users_id` INT(11) NOT NULL, + `status` ENUM('public', 'private', 'unlisted', 'favorite', 'watch_later') NOT NULL DEFAULT 'public', + `showOnTV` TINYINT NULL, + PRIMARY KEY (`id`), + INDEX `fk_playlists_users1_idx` (`users_id` ASC), + INDEX `showOnTVindex3` (`showOnTV` ASC), + CONSTRAINT `fk_playlists_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `playlists_has_videos` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `playlists_has_videos` ( + `playlists_id` INT NOT NULL, + `videos_id` INT NOT NULL, + `order` INT NULL, + PRIMARY KEY (`playlists_id`, `videos_id`), + INDEX `fk_playlists_has_videos_videos1_idx` (`videos_id` ASC), + INDEX `fk_playlists_has_videos_playlists1_idx` (`playlists_id` ASC), + CONSTRAINT `fk_playlists_has_videos_playlists1` + FOREIGN KEY (`playlists_id`) + REFERENCES `playlists` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_playlists_has_videos_videos1` + FOREIGN KEY (`videos_id`) + REFERENCES `videos` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `plugins` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `plugins` ( + `id` INT NOT NULL AUTO_INCREMENT, + `uuid` VARCHAR(45) NOT NULL, + `status` ENUM('active', 'inactive') NOT NULL DEFAULT 'active', + `created` DATETIME NULL, + `modified` DATETIME NULL, + `object_data` TEXT NULL, + `name` VARCHAR(255) NOT NULL, + `dirName` VARCHAR(255) NOT NULL, + `pluginversion` VARCHAR(6) NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC)) +ENGINE = InnoDB; + + +-- ----------------------------------------------------- +-- Table `comments_likes` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `comments_likes` ( + `id` INT NOT NULL AUTO_INCREMENT, + `like` INT(1) NOT NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + `users_id` INT NOT NULL, + `comments_id` INT NOT NULL, + PRIMARY KEY (`id`), + INDEX `fk_comments_likes_users1_idx` (`users_id` ASC), + INDEX `fk_comments_likes_comments1_idx` (`comments_id` ASC), + CONSTRAINT `fk_comments_likes_users1` + FOREIGN KEY (`users_id`) + REFERENCES `users` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_comments_likes_comments1` + FOREIGN KEY (`comments_id`) + REFERENCES `comments` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +-- ----------------------------------------------------- +-- Table `category_type_cache` +-- ----------------------------------------------------- +CREATE TABLE `category_type_cache` ( + `categoryId` int(11) NOT NULL, + `type` int(2) NOT NULL COMMENT '0=both, 1=audio, 2=video' DEFAULT 0, + `manualSet` int(1) NOT NULL COMMENT '0=auto, 1=manual' DEFAULT 0 + +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS `categories_has_users_groups` ( + `id` INT NOT NULL AUTO_INCREMENT, + `categories_id` INT(11) NOT NULL, + `users_groups_id` INT(11) NOT NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + `status` CHAR(1) NOT NULL DEFAULT 'a', + PRIMARY KEY (`id`), + INDEX `fk_categories_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), + INDEX `fk_categories_has_users_groups_categories1_idx` (`categories_id` ASC), + CONSTRAINT `fk_categories_has_users_groups_categories1` + FOREIGN KEY (`categories_id`) + REFERENCES `categories` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_categories_has_users_groups_users_groups1` + FOREIGN KEY (`users_groups_id`) + REFERENCES `users_groups` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; + +CREATE TABLE IF NOT EXISTS `users_extra_info` ( + `id` INT NOT NULL AUTO_INCREMENT, + `field_name` VARCHAR(45) NOT NULL, + `field_type` VARCHAR(45) NOT NULL, + `field_options` TEXT NULL, + `field_default_value` VARCHAR(45) NULL, + `parameters` TEXT NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + `status` CHAR(1) NOT NULL DEFAULT 'a', + `order` INT NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + INDEX `ordersortusers_extra_info` USING BTREE (`order`)) +ENGINE = InnoDB; + +ALTER TABLE `category_type_cache` + ADD UNIQUE KEY `categoryId` (`categoryId`); + +ALTER TABLE `plugins` +ADD INDEX `plugin_status` (`status` ASC); + +ALTER TABLE `videos` +ADD INDEX `videos_status_index` (`status` ASC), +ADD INDEX `is_suggested_index` (`isSuggested` ASC), +ADD INDEX `views_count_index` (`views_count` ASC), +ADD INDEX `filename_index` (`filename` ASC); + +COMMIT; + +SET SQL_MODE=@OLD_SQL_MODE; +SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; +SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; diff --git a/install/deleteOrphanFiles.php b/install/deleteOrphanFiles.php index 288c6a19f8..10d71ff45f 100644 --- a/install/deleteOrphanFiles.php +++ b/install/deleteOrphanFiles.php @@ -1,85 +1,83 @@ - $value) { - $dir = "{$path}{$value}"; - if (!is_dir($dir)) { - $bname = basename($dir); - if (in_array($bname, $doNotDeleteFilesList) || preg_match('/configuration\./i', $bname)) { - unset($files[$key]); - } else { - $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; - } - } - 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; -} - -$totalSize = 0; -foreach ($files as $key => $value) { - $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"; - } - } -} + $value) { + $dir = "{$path}{$value}"; + if (!is_dir($dir)) { + $bname = basename($dir); + if (in_array($bname, $doNotDeleteFilesList) || preg_match('/configuration\./i', $bname)) { + unset($files[$key]); + } else { + $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] = [$value, $dir]; + //echo "*** Video NOT found for filename {$filename} ".PHP_EOL; + } + } + 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] = [$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; +} + +$totalSize = 0; +foreach ($files as $key => $value) { + $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"; + } + } elseif (unlink($value[1])) { + echo "$value[1] Deleted \n"; + } else { + echo "$value[1] Could Not be Deleted \n"; + } + } +} diff --git a/install/deleteStorageFiles.php b/install/deleteStorageFiles.php index 2e9cb8d8f3..e916f5d141 100644 --- a/install/deleteStorageFiles.php +++ b/install/deleteStorageFiles.php @@ -1,112 +1,110 @@ - $value) { - if (!empty($checkedFiles[$value[0]])) { - continue; - } - $checkedFiles[$value[0]] = array(true); - $getUsageFromFilename = YPTStorage::getUsageFromFilename($value[0]); - $checkedFiles[$value[0]][] = $getUsageFromFilename; - - if ($getUsageFromFilename < 200000) { - //echo "Local file is too small, probably transfered already or is a directory (HLS) \n"; - continue; - } - $video = Video::getVideoFromFileName($value[0], true); - if (!empty($video)) { - $sites_id = $video['sites_id']; - if ($sites_id > 0) { - $count++; - if ($count > $max) { - exit; - } - echo "{$count}: Local file videos_id = {$video['id']} {$video['title']}=> $getUsageFromFilename " . humanFileSize($getUsageFromFilename) . "\n"; - $source_size = YPTStorage::getFileSize($video['id'], -1); - $destination_size = YPTStorage::getFileSize($video['id'], $sites_id); - if (!empty($destination_size) && $destination_size > 5000000 && $source_size <= $destination_size) { - $countExecuted++; - if ($countExecuted > $max) { - exit; - } - YPTStorage::createDummy($video['id']); - $tgzFile = $global['systemRootPath'] . "videos/{$video['filename']}.tgz"; - if(file_exists($tgzFile)){ - unlink($tgzFile); - } - echo "****** File size is the same videos_id = {$video['id']} {$sites_id} [$source_size!==$destination_size][" . humanFileSize($source_size) . "!==" . humanFileSize($destination_size) . "]\n"; - //exit; - } else if($source_sizee > 5000000){ - echo "----- ERROR File size is NOT the same videos_id and it's supposed to be on the storage = {$video['id']} {$sites_id} [$source_size!==$destination_size][" . humanFileSize($source_size) . "!==" . humanFileSize($destination_size) . "]\n"; - } else if($source_sizee > 5000000){ - echo "+++++ All seems fine with video {$video['id']} {$sites_id} [$source_size!==$destination_size][" . humanFileSize($source_size) . "!==" . humanFileSize($destination_size) . "]\n"; - } - } else { - //echo "The video_id {$video['id']} ({$video['title']}) is not hosted on the storage\n"; - } - } -} \ No newline at end of file + $value) { + if (!empty($checkedFiles[$value[0]])) { + continue; + } + $checkedFiles[$value[0]] = [true]; + $getUsageFromFilename = YPTStorage::getUsageFromFilename($value[0]); + $checkedFiles[$value[0]][] = $getUsageFromFilename; + + if ($getUsageFromFilename < 200000) { + //echo "Local file is too small, probably transfered already or is a directory (HLS) \n"; + continue; + } + $video = Video::getVideoFromFileName($value[0], true); + if (!empty($video)) { + $sites_id = $video['sites_id']; + if ($sites_id > 0) { + $count++; + if ($count > $max) { + exit; + } + echo "{$count}: Local file videos_id = {$video['id']} {$video['title']}=> $getUsageFromFilename " . humanFileSize($getUsageFromFilename) . "\n"; + $source_size = YPTStorage::getFileSize($video['id'], -1); + $destination_size = YPTStorage::getFileSize($video['id'], $sites_id); + if (!empty($destination_size) && $destination_size > 5000000 && $source_size <= $destination_size) { + $countExecuted++; + if ($countExecuted > $max) { + exit; + } + YPTStorage::createDummy($video['id']); + $tgzFile = $global['systemRootPath'] . "videos/{$video['filename']}.tgz"; + if (file_exists($tgzFile)) { + unlink($tgzFile); + } + echo "****** File size is the same videos_id = {$video['id']} {$sites_id} [$source_size!==$destination_size][" . humanFileSize($source_size) . "!==" . humanFileSize($destination_size) . "]\n"; + //exit; + } elseif ($source_sizee > 5000000) { + echo "----- ERROR File size is NOT the same videos_id and it's supposed to be on the storage = {$video['id']} {$sites_id} [$source_size!==$destination_size][" . humanFileSize($source_size) . "!==" . humanFileSize($destination_size) . "]\n"; + } elseif ($source_sizee > 5000000) { + echo "+++++ All seems fine with video {$video['id']} {$sites_id} [$source_size!==$destination_size][" . humanFileSize($source_size) . "!==" . humanFileSize($destination_size) . "]\n"; + } + } else { + //echo "The video_id {$video['id']} ({$video['title']}) is not hosted on the storage\n"; + } + } +} diff --git a/install/deleteTGZFiles.php b/install/deleteTGZFiles.php index 4961d4bab4..44967c4da1 100644 --- a/install/deleteTGZFiles.php +++ b/install/deleteTGZFiles.php @@ -1,26 +1,25 @@ - $row) { - $count++; - $filename = $row['filename']; - $totalDeleted = Video::deleteThumbs($filename, true, $checkIfIsCorrupted); - if($totalDeleted){ - echo "{$total}/{$count} Thumbs deleted ($totalDeleted) from {$row['title']}".PHP_EOL; - }else{ - echo "{$total}/{$count} Thumbs NOT deleted from {$row['title']}".PHP_EOL; - } - } -} else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); -} \ No newline at end of file + $row) { + $count++; + $filename = $row['filename']; + $totalDeleted = Video::deleteThumbs($filename, true, $checkIfIsCorrupted); + if ($totalDeleted) { + echo "{$total}/{$count} Thumbs deleted ($totalDeleted) from {$row['title']}".PHP_EOL; + } else { + echo "{$total}/{$count} Thumbs NOT deleted from {$row['title']}".PHP_EOL; + } + } +} else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); +} diff --git a/install/fixDynamicUsergroups.php b/install/fixDynamicUsergroups.php index 029fc68254..b5d0b0a563 100644 --- a/install/fixDynamicUsergroups.php +++ b/install/fixDynamicUsergroups.php @@ -1,43 +1,42 @@ -0, 'NoDynamic'=>0, 'Deleted'=>0); -if ($res != false) { - foreach ($fullData as $key => $row) { - $rowsUser = UserGroups::getUserGroups($row['id']); - if(empty($rowsUser)){ - //echo "This user has no permanent usergroups".PHP_EOL; - $count['NoPermanent']++; - }else{ - $user = new User($row['id'], $row['user'], $row['password']); - $user->login(true, false, true); - $user_groups_id = AVideoPlugin::getDynamicUserGroupsId($row['id']); - if(empty($user_groups_id)){ - //echo "This user has no dynamic usergroups".PHP_EOL; - $count['NoDynamic']++; - }else{ - echo "found dynamic usergroups from users_id={$row['id']} user={$row['user']} usergroups=". implode(',', $user_groups_id).PHP_EOL; - $sqlUG = "DELETE FROM users_has_users_groups WHERE users_id = ? AND users_groups_id IN (". implode(',', $user_groups_id).")"; - sqlDAL::writeSql($sqlUG, "i", array($row['id'])); - $count['Deleted']++; - } - } - } -} else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); -} -echo "Finish, ". json_encode($count); \ No newline at end of file +0, 'NoDynamic'=>0, 'Deleted'=>0]; +if ($res != false) { + foreach ($fullData as $key => $row) { + $rowsUser = UserGroups::getUserGroups($row['id']); + if (empty($rowsUser)) { + //echo "This user has no permanent usergroups".PHP_EOL; + $count['NoPermanent']++; + } else { + $user = new User($row['id'], $row['user'], $row['password']); + $user->login(true, false, true); + $user_groups_id = AVideoPlugin::getDynamicUserGroupsId($row['id']); + if (empty($user_groups_id)) { + //echo "This user has no dynamic usergroups".PHP_EOL; + $count['NoDynamic']++; + } else { + echo "found dynamic usergroups from users_id={$row['id']} user={$row['user']} usergroups=". implode(',', $user_groups_id).PHP_EOL; + $sqlUG = "DELETE FROM users_has_users_groups WHERE users_id = ? AND users_groups_id IN (". implode(',', $user_groups_id).")"; + sqlDAL::writeSql($sqlUG, "i", [$row['id']]); + $count['Deleted']++; + } + } + } +} else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); +} +echo "Finish, ". json_encode($count); diff --git a/install/getAllWebp.php b/install/getAllWebp.php index ec6ab2c12b..93696498ba 100644 --- a/install/getAllWebp.php +++ b/install/getAllWebp.php @@ -1,97 +1,98 @@ - [ - 'verify_peer' => false, - 'verify_peer_name' => false, - ], - ]); - - $file_headers = @get_headers($url, 0, $context); - if (!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') { - echo "\nGet webp not found {$url}"; - ob_flush(); - continue; - } else { - $url = $config->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'] . " {$destination}"; - 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; -} + [ + 'verify_peer' => false, + 'verify_peer_name' => false, + ], + ]); + + $file_headers = @get_headers($url, 0, $context); + if (!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') { + echo "\nGet webp not found {$url}"; + ob_flush(); + continue; + } else { + $url = $config->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'] . " {$destination}"; + ob_flush(); + } + + echo "\nFinish: " . $value['title']; + echo "\n******\n"; + ob_flush(); +} + +function getFirstVideoURL($videoFileName) +{ + $types = ['', '_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"]; + } elseif (!empty($videosList['webm' . $value]["url"])) { + return $videosList['webm' . $value]["url"]; + } + } + return false; +} + +function getFirstVideoPath($videoFileName) +{ + $types = ['', '_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"]; + } elseif (!empty($videosList['webm' . $value]["path"])) { + return $videosList['webm' . $value]["path"]; + } + } + return false; +} diff --git a/install/index.php b/install/index.php index 5ca44029b6..efb6904f83 100644 --- a/install/index.php +++ b/install/index.php @@ -1,363 +1,350 @@ - - - - - Install AVideo - - - - - - - - - - - - -
-

- - Your system is installed, remove the install directory to continue -
- Go to the main page -

-
- -
- Logo -
-
-
-
Check list
-
- -
- - is Present -
- -
- - Your server is , you must install Apache -
- - -
- - PHP is present. -
- -
- - Your PHP version is . PHP 7.3 or newer is required. -
- - - -
- - Your videos directory is writable -
- -
- - Your videos directory must be writable -
- - The video directory does not exists, AVideo had no permition to create it, you must create it manualy! -
-
sudo mkdir 
- -
- Then you can set the permissions (www-data means apache user). -
-
sudo chown www-data:www-data  && sudo chmod 755  
-
-
- - - -
- - Your post_max_size is -
- -
- - Your post_max_size is , it must be at least 100M - -
- Edit the php.ini file -
-
sudo nano 
-
-
- - - -
- - Your upload_max_filesize is -
- -
- - Your upload_max_filesize is , it must be at least 100M - -
- Edit the php.ini file -
-
sudo nano 
-
-
- -
-
-
- -
-
-
-
Site Configuration
-
-
- - -
-
- - -
-
-
- - -
-
-
- -
-
-
- - -
-
- - -
-
- - -
-
-
-
-
-
-
Database
-
- -
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- -
-
-
-
-
- -
-
-
- -
- - - - - - - - - - - - - + + + + + Install AVideo + + + + + + + + + + + + +
+

+ + Your system is installed, remove the install directory to continue +
+ Go to the main page +

+
+ +
+ Logo +
+
+
+
Check list
+
+ +
+ + is Present +
+ +
+ + Your server is , you must install Apache +
+ + +
+ + PHP is present. +
+ +
+ + Your PHP version is . PHP 7.3 or newer is required. +
+ + + +
+ + Your videos directory is writable +
+ +
+ + Your videos directory must be writable +
+ + The video directory does not exists, AVideo had no permition to create it, you must create it manualy! +
+
sudo mkdir 
+ +
+ Then you can set the permissions (www-data means apache user). +
+
sudo chown www-data:www-data  && sudo chmod 755  
+
+
+ + + +
+ + Your post_max_size is +
+ +
+ + Your post_max_size is , it must be at least 100M + +
+ Edit the php.ini file +
+
sudo nano 
+
+
+ + + +
+ + Your upload_max_filesize is +
+ +
+ + Your upload_max_filesize is , it must be at least 100M + +
+ Edit the php.ini file +
+
sudo nano 
+
+
+ +
+
+
+ +
+
+
+
Site Configuration
+
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ +
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
Database
+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ +
+
+
+
+
+ +
+
+
+ +
+ + + + + + + + + + + + + diff --git a/install/install.php b/install/install.php index a13c409678..fb08048dff 100644 --- a/install/install.php +++ b/install/install.php @@ -1,59 +1,58 @@ - $value) { - $file[$key] = "{$folder}{$dir}/{$value}"; - } - $fileList = array_merge($fileList, $file); - } - usort($fileList, - function($a, $b) { - return preg_match('/SendRecordedToEncoder/', $a) ? 1 : 0; - } - ); - return $fileList; -} - -$option = intval(@$argv[1]); - -if (empty($option)) { - echo "1 - Install tables and enable plugins\n"; - echo "2 - Install tables only\n"; - echo "3 - Enable plugins only\n"; - echo "4 - Update plugins only\n"; - echo "Choose an option: "; - ob_flush(); - $option = trim(readline("")); -} -if ($option == 1 || $option == 2) { - $files = _rsearch("{$global['systemRootPath']}plugin/", "/install\/install.sql$/i"); - $templine = ''; - $global['mysqli']->begin_transaction(); - $totalFiles = count($files); - $countFiles = 0; - foreach ($files as $value) { - $countFiles++; - $lines = file($value); - $totalLines = count($lines); - $countLines = 0; - foreach ($lines as $line) { - $countLines++; - if (substr($line, 0, 2) == '--' || $line == '') - continue; - $templine .= $line; - if (substr(trim($line), -1, 1) == ';') { - if (!$global['mysqli']->query($templine)) { - echo ($value . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

'); - die(json_encode($obj)); - } else { - echo "[{$countFiles}/{$totalFiles}][{$countLines}/{$totalLines}] Success performing query from $value\n"; - } - $templine = ''; - } - } - } - $global['mysqli']->commit(); -} -if ($option == 1 || $option == 3) { - $EnablePlugins = array( - array('1apicbec-91db-4357-bb10-ee08b0913778', 'API', 'API'), - array('6daca392-7b14-44fb-aa33-51cba620d92e', 'CookieAlert', 'CookieAlert'), - array('55a4fa56-8a30-48d4-a0fb-8aa6b3f69033', 'CustomizeAdvanced', 'CustomizeAdvanced'), - array('55a4fa56-8a30-48d4-a0fb-8aa6b3fuser3', 'CustomizeUser', 'CustomizeUser'), - array('a06505bf-3570-4b1f-977a-fd0e5cab205d', 'Gallery', 'Gallery'), - array('e06b161c-cbd0-4c1d-a484-71018efa2f35', 'Live', 'Live'), - array('5310b394-b54f-48ab-9049-995df4d95239', 'NextButton', 'NextButton'), - array('plist12345-370-4b1f-977a-fd0e5cabtube', 'Programs', 'PlayLists'), - array('b5e223db-785b-4436-8f7b-f297860c9be0', 'ReportVideo', 'ReportVideo'), - array('f7596843-51b1-47a0-8bb1-b4ad91f87d6b', 'TheaterButton', 'TheaterButton'), - array('45432a78-d0c6-47f3-8ac4-8fd05f507386', 'User_Location', 'User_Location'), - array('4c1f4f76-b336-4ddc-a4de-184efe715c09', 'MobileManager', 'MobileManager'), - array('52chata2-3f14-49db-958e-15ccb1a07f0e', 'Chat2', 'Chat2'), - array('cf145581-7d5e-4bb6-8c12-48fc37c0630d', 'LiveUsers', 'LiveUsers'), - array('996c9afb-b90e-40ca-90cb-934856180bb9', 'MP4ThumbsAndGif', 'MP4ThumbsAndGif'), - array('eb6e2808-d876-4488-94cb-2448a6b14e0b', 'SendRecordedToEncoder', 'SendRecordedToEncoder'), - array('f2hls8c6-9359-4cc1-809f-fac32c8a4333', 'VideoHLS', 'VideoHLS'), - array('4b9142c0-f0c3-42be-8fe5-a4775111239c', 'VideoResolutionSwitcher', 'VideoResolutionSwitcher'), - array('28e74f9a-a2ef-4644-86f0-40234ae7c1b5', 'VideoThumbnails', 'VideoThumbnails'), - array('meet225-3807-4167-ba81-0509dd280e06', 'Meet', 'Meet'), - array('YPTSocket-5ee8405eaaa16', 'YPTSocket', 'YPTSocket'), - array('Scheduler-5ee8405eaaa16', 'Scheduler', 'Scheduler') - ); - foreach ($EnablePlugins as $value) { - if ($plugin = Plugin::getOrCreatePluginByName($value[2], 'active')) { - echo "Success enable plugin ($value[2]) " . $plugin['name'] . "\n"; - } else { - echo "ERROR enable plugin ($value[2]) \n"; - } - } -} -if ($option == 4) { - echo "Searching for {$global['systemRootPath']}plugin/[plugin]/install/install.sql" . PHP_EOL; - $files = _rsearch("{$global['systemRootPath']}plugin/", "/install\/install.sql$/i"); - $templine = ''; - foreach ($files as $value) { - if (preg_match("/User_Location/", $value)) { - continue; - } - if (preg_match("/Customize/", $value)) { - continue; - } - - echo "Checking tables from {$value}" . PHP_EOL; - $lines = file($value); - foreach ($lines as $line) { - if (substr($line, 0, 2) == '--' || $line == '') - continue; - $templine .= $line; - if (substr(trim($line), -1, 1) == ';') { - if (!$global['mysqli']->query($templine)) { - echo ($value . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

'); - //die(json_encode($obj)); - } else { - echo "Success performing query from $value\n"; - } - $templine = ''; - } - } - } - $plugins = Plugin::getAvailablePlugins(); - foreach ($plugins as $value) { - $p = AVideoPlugin::loadPlugin($value->dir); - if (empty($p)) { - continue; - } - $currentVersion = $p->getPluginVersion(); - if (AVideoPlugin::updatePlugin($value->dir)) { - $p = AVideoPlugin::loadPlugin($value->dir, true); - $newVersion = $p->getPluginVersion(); - echo "{$value->dir} updated FROM {$currentVersion} TO {$newVersion}" . PHP_EOL; - } - } -} -echo "Option {$option} finished \n"; + $value) { + $file[$key] = "{$folder}{$dir}/{$value}"; + } + $fileList = array_merge($fileList, $file); + } + usort( + $fileList, + function ($a, $b) { + return preg_match('/SendRecordedToEncoder/', $a) ? 1 : 0; + } + ); + return $fileList; +} + +$option = intval(@$argv[1]); + +if (empty($option)) { + echo "1 - Install tables and enable plugins\n"; + echo "2 - Install tables only\n"; + echo "3 - Enable plugins only\n"; + echo "4 - Update plugins only\n"; + echo "Choose an option: "; + ob_flush(); + $option = trim(readline("")); +} +if ($option == 1 || $option == 2) { + $files = _rsearch("{$global['systemRootPath']}plugin/", "/install\/install.sql$/i"); + $templine = ''; + $global['mysqli']->begin_transaction(); + $totalFiles = count($files); + $countFiles = 0; + foreach ($files as $value) { + $countFiles++; + $lines = file($value); + $totalLines = count($lines); + $countLines = 0; + foreach ($lines as $line) { + $countLines++; + if (substr($line, 0, 2) == '--' || $line == '') { + continue; + } + $templine .= $line; + if (substr(trim($line), -1, 1) == ';') { + if (!$global['mysqli']->query($templine)) { + echo($value . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

'); + die(json_encode($obj)); + } else { + echo "[{$countFiles}/{$totalFiles}][{$countLines}/{$totalLines}] Success performing query from $value\n"; + } + $templine = ''; + } + } + } + $global['mysqli']->commit(); +} +if ($option == 1 || $option == 3) { + $EnablePlugins = [ + ['1apicbec-91db-4357-bb10-ee08b0913778', 'API', 'API'], + ['6daca392-7b14-44fb-aa33-51cba620d92e', 'CookieAlert', 'CookieAlert'], + ['55a4fa56-8a30-48d4-a0fb-8aa6b3f69033', 'CustomizeAdvanced', 'CustomizeAdvanced'], + ['55a4fa56-8a30-48d4-a0fb-8aa6b3fuser3', 'CustomizeUser', 'CustomizeUser'], + ['a06505bf-3570-4b1f-977a-fd0e5cab205d', 'Gallery', 'Gallery'], + ['e06b161c-cbd0-4c1d-a484-71018efa2f35', 'Live', 'Live'], + ['5310b394-b54f-48ab-9049-995df4d95239', 'NextButton', 'NextButton'], + ['plist12345-370-4b1f-977a-fd0e5cabtube', 'Programs', 'PlayLists'], + ['b5e223db-785b-4436-8f7b-f297860c9be0', 'ReportVideo', 'ReportVideo'], + ['f7596843-51b1-47a0-8bb1-b4ad91f87d6b', 'TheaterButton', 'TheaterButton'], + ['45432a78-d0c6-47f3-8ac4-8fd05f507386', 'User_Location', 'User_Location'], + ['4c1f4f76-b336-4ddc-a4de-184efe715c09', 'MobileManager', 'MobileManager'], + ['52chata2-3f14-49db-958e-15ccb1a07f0e', 'Chat2', 'Chat2'], + ['cf145581-7d5e-4bb6-8c12-48fc37c0630d', 'LiveUsers', 'LiveUsers'], + ['996c9afb-b90e-40ca-90cb-934856180bb9', 'MP4ThumbsAndGif', 'MP4ThumbsAndGif'], + ['eb6e2808-d876-4488-94cb-2448a6b14e0b', 'SendRecordedToEncoder', 'SendRecordedToEncoder'], + ['f2hls8c6-9359-4cc1-809f-fac32c8a4333', 'VideoHLS', 'VideoHLS'], + ['4b9142c0-f0c3-42be-8fe5-a4775111239c', 'VideoResolutionSwitcher', 'VideoResolutionSwitcher'], + ['28e74f9a-a2ef-4644-86f0-40234ae7c1b5', 'VideoThumbnails', 'VideoThumbnails'], + ['meet225-3807-4167-ba81-0509dd280e06', 'Meet', 'Meet'], + ['YPTSocket-5ee8405eaaa16', 'YPTSocket', 'YPTSocket'], + ['Scheduler-5ee8405eaaa16', 'Scheduler', 'Scheduler'], + ]; + foreach ($EnablePlugins as $value) { + if ($plugin = Plugin::getOrCreatePluginByName($value[2], 'active')) { + echo "Success enable plugin ($value[2]) " . $plugin['name'] . "\n"; + } else { + echo "ERROR enable plugin ($value[2]) \n"; + } + } +} +if ($option == 4) { + echo "Searching for {$global['systemRootPath']}plugin/[plugin]/install/install.sql" . PHP_EOL; + $files = _rsearch("{$global['systemRootPath']}plugin/", "/install\/install.sql$/i"); + $templine = ''; + foreach ($files as $value) { + if (preg_match("/User_Location/", $value)) { + continue; + } + if (preg_match("/Customize/", $value)) { + continue; + } + + echo "Checking tables from {$value}" . PHP_EOL; + $lines = file($value); + foreach ($lines as $line) { + if (substr($line, 0, 2) == '--' || $line == '') { + continue; + } + $templine .= $line; + if (substr(trim($line), -1, 1) == ';') { + if (!$global['mysqli']->query($templine)) { + echo($value . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

'); + //die(json_encode($obj)); + } else { + echo "Success performing query from $value\n"; + } + $templine = ''; + } + } + } + $plugins = Plugin::getAvailablePlugins(); + foreach ($plugins as $value) { + $p = AVideoPlugin::loadPlugin($value->dir); + if (empty($p)) { + continue; + } + $currentVersion = $p->getPluginVersion(); + if (AVideoPlugin::updatePlugin($value->dir)) { + $p = AVideoPlugin::loadPlugin($value->dir, true); + $newVersion = $p->getPluginVersion(); + echo "{$value->dir} updated FROM {$currentVersion} TO {$newVersion}" . PHP_EOL; + } + } +} +echo "Option {$option} finished \n"; diff --git a/install/liveLinks.php b/install/liveLinks.php index 5464c02a5e..b46195f6bd 100644 --- a/install/liveLinks.php +++ b/install/liveLinks.php @@ -1,34 +1,29 @@ -real_escape_string($channelName); -$sql = "SELECT lt.*, u.* FROM users u LEFT JOIN live_transmitions lt ON users_id = u.id " - . " WHERE canStream = 1 AND status = 'a' ORDER BY public DESC LIMIT 20"; -$res = sqlDAL::readSql($sql); -$users = sqlDAL::fetchAllAssoc($res); -sqlDAL::close($res); -if ($res != false) { - foreach ($users as $row) { - echo "-----------------------------------".PHP_EOL; - if(!empty($row['public'])){ - echo "PUBLIC "; - } - echo "{$row['id']} - {$row['user']} ".PHP_EOL; - echo Live::getServer() . "?p=" . $row['password'] . "/" . $row['key'].PHP_EOL; - echo Live::getLinkToLiveFromUsers_id($row['id']).PHP_EOL; - echo "-----------------------------------".PHP_EOL; - } -} -die(); - - - - +real_escape_string($channelName); +$sql = "SELECT lt.*, u.* FROM users u LEFT JOIN live_transmitions lt ON users_id = u.id " + . " WHERE canStream = 1 AND status = 'a' ORDER BY public DESC LIMIT 20"; +$res = sqlDAL::readSql($sql); +$users = sqlDAL::fetchAllAssoc($res); +sqlDAL::close($res); +if ($res != false) { + foreach ($users as $row) { + echo "-----------------------------------".PHP_EOL; + if (!empty($row['public'])) { + echo "PUBLIC "; + } + echo "{$row['id']} - {$row['user']} ".PHP_EOL; + echo Live::getServer() . "?p=" . $row['password'] . "/" . $row['key'].PHP_EOL; + echo Live::getLinkToLiveFromUsers_id($row['id']).PHP_EOL; + echo "-----------------------------------".PHP_EOL; + } +} +die(); diff --git a/install/makeAdmin.php b/install/makeAdmin.php index 6764a4374c..92b6dc4c7c 100644 --- a/install/makeAdmin.php +++ b/install/makeAdmin.php @@ -1,36 +1,32 @@ -getBdId())){ - $sql = "UPDATE users SET isAdmin = 1, status = 'a' where id = ".$user->getBdId(); - - $insert_row = sqlDAL::writeSql($sql); - if($insert_row){ - echo "Your user {$userName} is admin now"; - echo "\n"; - die(); - } - }else{ - echo "User ({$userName}) Not found"; - echo "\n"; - die(); - } -} -echo "Bye"; -echo "\n"; -die(); - - - - +getBdId())) { + $sql = "UPDATE users SET isAdmin = 1, status = 'a' where id = ".$user->getBdId(); + + $insert_row = sqlDAL::writeSql($sql); + if ($insert_row) { + echo "Your user {$userName} is admin now"; + echo "\n"; + die(); + } + } else { + echo "User ({$userName}) Not found"; + echo "\n"; + die(); + } +} +echo "Bye"; +echo "\n"; +die(); diff --git a/install/markAllLivesAsFinished.php b/install/markAllLivesAsFinished.php index b6cabd80f6..4296df75cb 100644 --- a/install/markAllLivesAsFinished.php +++ b/install/markAllLivesAsFinished.php @@ -1,14 +1,13 @@ -".PHP_EOL." {$count}/{$total} move directory {$move['oldDir']} to {$move['newDir']} ".PHP_EOL."<--" . PHP_EOL . PHP_EOL; - }else{ - echo " We will not rename directory {$file} ".PHP_EOL; - } - continue; - } - $filename = basename($file); - $newname = Video::getPathToFile($filename); - $renamed = rename($file, $newname); - if($renamed){ - echo "{$count}/{$total} moved $filename to $newname" . PHP_EOL; - }else{ - echo "{$count}/{$total} fail to move $filename to $newname" . PHP_EOL; - } - } - ob_flush(); -} -echo PHP_EOL." Deleting cache ... "; -ObjectYPT::deleteALLCache(); -$videosDir = Video::getStoragePath(); -exec("chown -R www-data:www-data {$videosDir}"); -exec("chmod -R 755 {$videosDir}"); -echo PHP_EOL." Done! ".PHP_EOL; -die(); - +".PHP_EOL." {$count}/{$total} move directory {$move['oldDir']} to {$move['newDir']} ".PHP_EOL."<--" . PHP_EOL . PHP_EOL; + } else { + echo " We will not rename directory {$file} ".PHP_EOL; + } + continue; + } + $filename = basename($file); + $newname = Video::getPathToFile($filename); + $renamed = rename($file, $newname); + if ($renamed) { + echo "{$count}/{$total} moved $filename to $newname" . PHP_EOL; + } else { + echo "{$count}/{$total} fail to move $filename to $newname" . PHP_EOL; + } + } + ob_flush(); +} +echo PHP_EOL." Deleting cache ... "; +ObjectYPT::deleteALLCache(); +$videosDir = Video::getStoragePath(); +exec("chown -R www-data:www-data {$videosDir}"); +exec("chmod -R 755 {$videosDir}"); +echo PHP_EOL." Done! ".PHP_EOL; +die(); diff --git a/install/moveFilesToFolder2.php b/install/moveFilesToFolder2.php index 7f198b5649..134df3fac7 100644 --- a/install/moveFilesToFolder2.php +++ b/install/moveFilesToFolder2.php @@ -1,58 +1,56 @@ - $value) { - $video = Video::getVideoFromFileName($value[0], true); - if (!empty($video)) { - unset($files[$key]); - } -} -echo "*** Total filenames " . $total . " Will be created\n"; -echo "*** Confirm Create Them? y/n: "; -ob_flush(); -$confirm = trim(readline("")); -if (!empty($confirm) && strtolower($confirm) === 'y') { - $count = 0; - foreach ($files as $key => $value) { - $count++; - $title = "Video recovered: ".date("Y-m-d H:i:s", filectime($value[1])); - $video = new Video($title, $value[0]); - $video->setStatus(Video::$statusActive); - $video->setUsers_id(1); - if($video->save(false, true)){ - echo "{$count}/{$total} {$title} created\n"; - }else{ - echo "{$count}/{$total} ERROR on create video {$title}\n"; - } - } -} \ No newline at end of file + $value) { + $video = Video::getVideoFromFileName($value[0], true); + if (!empty($video)) { + unset($files[$key]); + } +} +echo "*** Total filenames " . $total . " Will be created\n"; +echo "*** Confirm Create Them? y/n: "; +ob_flush(); +$confirm = trim(readline("")); +if (!empty($confirm) && strtolower($confirm) === 'y') { + $count = 0; + foreach ($files as $key => $value) { + $count++; + $title = "Video recovered: ".date("Y-m-d H:i:s", filectime($value[1])); + $video = new Video($title, $value[0]); + $video->setStatus(Video::$statusActive); + $video->setUsers_id(1); + if ($video->save(false, true)) { + echo "{$count}/{$total} {$title} created\n"; + } else { + echo "{$count}/{$total} ERROR on create video {$title}\n"; + } + } +} diff --git a/install/recoverPassword.php b/install/recoverPassword.php index 175db29b68..18f3c32e80 100644 --- a/install/recoverPassword.php +++ b/install/recoverPassword.php @@ -1,65 +1,60 @@ -getBdId())) { - echo "Enter a new password for the user {$userName} or press enter to skip:"; - echo "\n"; - ob_flush(); - $password = trim(readline("")); - if (!empty($password)) { - echo "Confirm the new password for the user {$userName}:"; - echo "\n"; - ob_flush(); - $password2 = trim(readline("")); - if ($password === $password2) { - $user->setPassword($password); - if ($user->save()) { - echo "Your new password was saved"; - echo "\n"; - die(); - } - } else { - echo "The passwords do not match"; - echo "\n"; - die(); - } - } - } else { - echo "User ({$userName}) Not found"; - echo "\n"; - die(); - } - } -} else { - $user = new User(0, $userName, false); - $user->setPassword($password); - if ($user->save()) { - echo "Your new password was saved"; - echo "\n"; - die(); - } -} -echo "Bye"; -echo "\n"; -die(); - - - - +getBdId())) { + echo "Enter a new password for the user {$userName} or press enter to skip:"; + echo "\n"; + ob_flush(); + $password = trim(readline("")); + if (!empty($password)) { + echo "Confirm the new password for the user {$userName}:"; + echo "\n"; + ob_flush(); + $password2 = trim(readline("")); + if ($password === $password2) { + $user->setPassword($password); + if ($user->save()) { + echo "Your new password was saved"; + echo "\n"; + die(); + } + } else { + echo "The passwords do not match"; + echo "\n"; + die(); + } + } + } else { + echo "User ({$userName}) Not found"; + echo "\n"; + die(); + } + } +} else { + $user = new User(0, $userName, false); + $user->setPassword($password); + if ($user->save()) { + echo "Your new password was saved"; + echo "\n"; + die(); + } +} +echo "Bye"; +echo "\n"; +die(); diff --git a/install/removeAllViewsStatistics.php b/install/removeAllViewsStatistics.php index e17df6f06e..124d1227d2 100644 --- a/install/removeAllViewsStatistics.php +++ b/install/removeAllViewsStatistics.php @@ -1,16 +1,15 @@ - 0"; -sqlDAL::writeSql($sql); - -echo "Finish delete statistics" . PHP_EOL; + 0"; +sqlDAL::writeSql($sql); + +echo "Finish delete statistics" . PHP_EOL; diff --git a/install/removeRepeatedPlaylists.php b/install/removeRepeatedPlaylists.php index bd8aedd72d..a0020b40a2 100644 --- a/install/removeRepeatedPlaylists.php +++ b/install/removeRepeatedPlaylists.php @@ -1,78 +1,76 @@ - $row) { - $users_ids[] = $row['users_id']; - } -} else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); -} - - -foreach ($users_ids as $user_id) { - echo "Process user_id = {$user_id} favorite\n"; - ob_flush(); - $sql = "SELECT * FROM playlists WHERE users_id = {$user_id} AND status = 'favorite' ORDER BY created "; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $key => $row) { - if ($key === 0) { - continue; - } - - if(!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))){ - continue; - } - - $sql = "DELETE FROM playlists "; - $sql .= " WHERE id = ?"; - - echo $sql." = {$row['id']}\n"; - ob_flush(); - sqlDAL::writeSql($sql, "i", array($row['id'])); - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - - - echo "Process user_id = {$user_id} watch_later\n"; - ob_flush(); - $sql = "SELECT * FROM playlists WHERE users_id = {$user_id} AND status = 'watch_later' ORDER BY created "; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $key => $row) { - if ($key === 0) { - continue; - } - $sql = "DELETE FROM playlists "; - $sql .= " WHERE id = ?"; - echo $sql." = {$row['id']}\n"; - ob_flush(); - sqlDAL::writeSql($sql, "i", array($row['id'])); - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - -} + $row) { + $users_ids[] = $row['users_id']; + } +} else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); +} + + +foreach ($users_ids as $user_id) { + echo "Process user_id = {$user_id} favorite\n"; + ob_flush(); + $sql = "SELECT * FROM playlists WHERE users_id = {$user_id} AND status = 'favorite' ORDER BY created "; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $key => $row) { + if ($key === 0) { + continue; + } + + if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { + continue; + } + + $sql = "DELETE FROM playlists "; + $sql .= " WHERE id = ?"; + + echo $sql." = {$row['id']}\n"; + ob_flush(); + sqlDAL::writeSql($sql, "i", [$row['id']]); + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + + + echo "Process user_id = {$user_id} watch_later\n"; + ob_flush(); + $sql = "SELECT * FROM playlists WHERE users_id = {$user_id} AND status = 'watch_later' ORDER BY created "; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $key => $row) { + if ($key === 0) { + continue; + } + $sql = "DELETE FROM playlists "; + $sql .= " WHERE id = ?"; + echo $sql." = {$row['id']}\n"; + ob_flush(); + sqlDAL::writeSql($sql, "i", [$row['id']]); + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } +} diff --git a/install/removeViewsStatisticsErrors.php b/install/removeViewsStatisticsErrors.php index 963ae14073..8e0fdd8e09 100644 --- a/install/removeViewsStatisticsErrors.php +++ b/install/removeViewsStatisticsErrors.php @@ -1,62 +1,61 @@ - $row) { - $session_id[] = $row['session_id']; - } -} else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); -} - - -foreach ($session_id as $id) { - echo "Process session_id = {$id}\n"; - ob_flush(); - $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE session_id = '{$id}'"; - echo $sql . PHP_EOL; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $sql2 = "SELECT id FROM videos_statistics WHERE videos_id = {$row['videos_id']} AND session_id = '{$id}' ORDER BY `when` DESC LIMIT 1"; - echo $sql . PHP_EOL; - $res2 = sqlDAL::readSql($sql2); - $fullData2 = sqlDAL::fetchAllAssoc($res2); - sqlDAL::close($res2); - if ($res != false) { - foreach ($fullData2 as $key2 => $row2) { - $sql = "DELETE FROM videos_statistics "; - $sql .= " WHERE videos_id = {$row['videos_id']} AND session_id = '{$id}' AND id != {$row2['id']} "; - - echo $sql . PHP_EOL; - ob_flush(); - sqlDAL::writeSql($sql); - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } -} - -echo "Finish fixing statistics" . PHP_EOL; + $row) { + $session_id[] = $row['session_id']; + } +} else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); +} + + +foreach ($session_id as $id) { + echo "Process session_id = {$id}\n"; + ob_flush(); + $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE session_id = '{$id}'"; + echo $sql . PHP_EOL; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $sql2 = "SELECT id FROM videos_statistics WHERE videos_id = {$row['videos_id']} AND session_id = '{$id}' ORDER BY `when` DESC LIMIT 1"; + echo $sql . PHP_EOL; + $res2 = sqlDAL::readSql($sql2); + $fullData2 = sqlDAL::fetchAllAssoc($res2); + sqlDAL::close($res2); + if ($res != false) { + foreach ($fullData2 as $key2 => $row2) { + $sql = "DELETE FROM videos_statistics "; + $sql .= " WHERE videos_id = {$row['videos_id']} AND session_id = '{$id}' AND id != {$row2['id']} "; + + echo $sql . PHP_EOL; + ob_flush(); + sqlDAL::writeSql($sql); + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } +} + +echo "Finish fixing statistics" . PHP_EOL; diff --git a/install/resetPlugins.php b/install/resetPlugins.php index 17b6870ab6..5340d26edf 100644 --- a/install/resetPlugins.php +++ b/install/resetPlugins.php @@ -1,39 +1,38 @@ - 0"; - sqlDAL::writeSql($sql); - echo "* Reset all plugins Parameters DONE\n"; - ob_flush(); -} else if ($option == 2) { - $sql = "UPDATE plugins "; - $sql .= " SET object_data = '' WHERE name = 'CustomizeUser'"; - sqlDAL::writeSql($sql); - echo "* Reset CustomizeUser Plugin Parameters only DONE\n"; - ob_flush(); -} else if ($option == 3) { - $sql = "DELETE FROM plugins "; - $sql .= " WHERE id > 0"; - sqlDAL::writeSql($sql); - echo "* Reset all plugins (All plugins inactivated) DONE\n"; - ob_flush(); -}else{ - echo "Bye\n"; -} \ No newline at end of file + 0"; + sqlDAL::writeSql($sql); + echo "* Reset all plugins Parameters DONE\n"; + ob_flush(); +} elseif ($option == 2) { + $sql = "UPDATE plugins "; + $sql .= " SET object_data = '' WHERE name = 'CustomizeUser'"; + sqlDAL::writeSql($sql); + echo "* Reset CustomizeUser Plugin Parameters only DONE\n"; + ob_flush(); +} elseif ($option == 3) { + $sql = "DELETE FROM plugins "; + $sql .= " WHERE id > 0"; + sqlDAL::writeSql($sql); + echo "* Reset all plugins (All plugins inactivated) DONE\n"; + ob_flush(); +} else { + echo "Bye\n"; +} diff --git a/install/reviewBrokenVideos.php b/install/reviewBrokenVideos.php index 98ba5afd33..80a84fd6c9 100644 --- a/install/reviewBrokenVideos.php +++ b/install/reviewBrokenVideos.php @@ -1,50 +1,49 @@ - $value) { - if(!empty($index) && $key<$index){ - continue; - } - $video = new Video('', '', $value); - $filename = $video->getFilename(); - - echo "{$key}/{$total} Start check {$filename} " . PHP_EOL; - if(Video::isMediaFileMissing($filename)){ - $sources = getVideosURL_V2($filename); - echo "{$key}/{$total} is missing ". json_encode($sources) . PHP_EOL; - }else{ - $video->setStatus(Video::$statusActive); - echo "{$key}/{$total} is set to active " . PHP_EOL; - } -} - -echo PHP_EOL . " Done! " . PHP_EOL; -die(); + $value) { + if (!empty($index) && $key<$index) { + continue; + } + $video = new Video('', '', $value); + $filename = $video->getFilename(); + + echo "{$key}/{$total} Start check {$filename} " . PHP_EOL; + if (Video::isMediaFileMissing($filename)) { + $sources = getVideosURL_V2($filename); + echo "{$key}/{$total} is missing ". json_encode($sources) . PHP_EOL; + } else { + $video->setStatus(Video::$statusActive); + echo "{$key}/{$total} is set to active " . PHP_EOL; + } +} + +echo PHP_EOL . " Done! " . PHP_EOL; +die(); diff --git a/install/test.php b/install/test.php index 02ac343238..50b8897f58 100644 --- a/install/test.php +++ b/install/test.php @@ -1,13 +1,12 @@ -query($sql); - echo "Encoder Update streamers set siteURL\n"; - $sql = "update streamers set siteURL = '{$streamerURL}';"; - $global['mysqli']->query($sql); - // change the encoder config file -}else{ - echo "Encoder not found in {$encoderConfigFile}\n"; -} - - - +query($sql); + echo "Encoder Update streamers set siteURL\n"; + $sql = "update streamers set siteURL = '{$streamerURL}';"; + $global['mysqli']->query($sql); +// change the encoder config file +} else { + echo "Encoder not found in {$encoderConfigFile}\n"; +} diff --git a/install/updatedb.php b/install/updatedb.php index 04491ebcec..28eb77e62f 100644 --- a/install/updatedb.php +++ b/install/updatedb.php @@ -1,62 +1,62 @@ - 0; -} - -$updateDir = $global['systemRootPath'] . "updatedb/"; -$currentVersion = $config->getVersion(); - -echo "Searching on ({$updateDir}) for updates greater then {$currentVersion}" . PHP_EOL; -global $global; -$files1 = scandir($updateDir); -$updateFiles = array(); -foreach ($files1 as $value) { - preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); - if (!empty($match)) { - if (currentVersionLowerThen($match[1], $currentVersion)) { - $updateFiles[] = array('filename' => $match[0], 'version' => $match[1]); - } - } -} - -if (empty($updateFiles)) { - echo "No new update files found on ({$updateDir})" . PHP_EOL; -}else{ - echo "Found ".count($updateDir)." updats" . PHP_EOL; -} - -foreach ($updateFiles as $value) { - echo "Updating version " . $value['version'] . PHP_EOL; - - $lines = file("{$updateDir}{$value['filename']}"); - foreach ($lines as $line) { - if (substr($line, 0, 2) == '--' || $line == '') - continue; - $templine .= $line; - if (substr(trim($line), -1, 1) == ';') { - if (!$global['mysqli']->query($templine)) { - echo ('Error performing query ' . $templine . ': ' . $global['mysqli']->error . PHP_EOL); - //exit; - } - $templine = ''; - } - } -} - -echo PHP_EOL . " Done! " . PHP_EOL; -die(); - + 0; +} + +$updateDir = $global['systemRootPath'] . "updatedb/"; +$currentVersion = $config->getVersion(); + +echo "Searching on ({$updateDir}) for updates greater then {$currentVersion}" . PHP_EOL; +global $global; +$files1 = scandir($updateDir); +$updateFiles = []; +foreach ($files1 as $value) { + preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); + if (!empty($match)) { + if (currentVersionLowerThen($match[1], $currentVersion)) { + $updateFiles[] = ['filename' => $match[0], 'version' => $match[1]]; + } + } +} + +if (empty($updateFiles)) { + echo "No new update files found on ({$updateDir})" . PHP_EOL; +} else { + echo "Found ".count($updateDir)." updats" . PHP_EOL; +} + +foreach ($updateFiles as $value) { + echo "Updating version " . $value['version'] . PHP_EOL; + + $lines = file("{$updateDir}{$value['filename']}"); + foreach ($lines as $line) { + if (substr($line, 0, 2) == '--' || $line == '') { + continue; + } + $templine .= $line; + if (substr(trim($line), -1, 1) == ';') { + if (!$global['mysqli']->query($templine)) { + echo('Error performing query ' . $templine . ': ' . $global['mysqli']->error . PHP_EOL); + //exit; + } + $templine = ''; + } + } +} + +echo PHP_EOL . " Done! " . PHP_EOL; +die(); diff --git a/objects/Channel.php b/objects/Channel.php index 9f8c27d84a..85c9e364b7 100644 --- a/objects/Channel.php +++ b/objects/Channel.php @@ -1,55 +1,55 @@ - 0 "; - if ($activeOnly) { - $sql .= " AND u.status = 'a' "; - } - $sql .= BootGrid::getSqlFromPost(array('user', 'about', 'channelName', 'u.name', 'u.email'), "", "", false, $FIND_IN_SET); - - $res = sqlDAL::readSql($sql); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $subscribe = array(); - if ($res != false) { - foreach ($fullResult as $row) { - $row = cleanUpRowFromDatabase($row); - $subscribe[] = $row; - } - } else { - $subscribe = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $subscribe; - } - - - public static function getTotalChannels($activeOnly=true) - { - global $global; - $sql = "SELECT count(*) as total " - . " FROM users u " - . " WHERE (SELECT count(v.id) FROM videos v where v.users_id = u.id) > 0 "; - if ($activeOnly) { - $sql .= " AND u.status = 'a' "; - } - $sql .= BootGrid::getSqlFromPost(array('user', 'about')); - $res = sqlDAL::readSql($sql); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return $res ? intval($data['total']) : 0; - } -} + 0 "; + if ($activeOnly) { + $sql .= " AND u.status = 'a' "; + } + $sql .= BootGrid::getSqlFromPost(['user', 'about', 'channelName', 'u.name', 'u.email'], "", "", false, $FIND_IN_SET); + + $res = sqlDAL::readSql($sql); + $fullResult = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $subscribe = []; + if ($res != false) { + foreach ($fullResult as $row) { + $row = cleanUpRowFromDatabase($row); + $subscribe[] = $row; + } + } else { + $subscribe = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $subscribe; + } + + + public static function getTotalChannels($activeOnly=true) + { + global $global; + $sql = "SELECT count(*) as total " + . " FROM users u " + . " WHERE (SELECT count(v.id) FROM videos v where v.users_id = u.id) > 0 "; + if ($activeOnly) { + $sql .= " AND u.status = 'a' "; + } + $sql .= BootGrid::getSqlFromPost(['user', 'about']); + $res = sqlDAL::readSql($sql); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return $res ? intval($data['total']) : 0; + } +} diff --git a/objects/Mobile_Detect.php b/objects/Mobile_Detect.php index 2d9029bfcd..14a3b8bcca 100644 --- a/objects/Mobile_Detect.php +++ b/objects/Mobile_Detect.php @@ -1,1683 +1,1677 @@ - - * @author Nick Ilyin - * Original author: Victor Stanciu - * - * @version 2.8.37 - * - * Auto-generated isXXXX() magic methods. - * php -a examples/dump_magic_methods.php - * - * @method bool isiPhone() - * @method bool isBlackBerry() - * @method bool isPixel() - * @method bool isHTC() - * @method bool isNexus() - * @method bool isDell() - * @method bool isMotorola() - * @method bool isSamsung() - * @method bool isLG() - * @method bool isSony() - * @method bool isAsus() - * @method bool isXiaomi() - * @method bool isNokiaLumia() - * @method bool isMicromax() - * @method bool isPalm() - * @method bool isVertu() - * @method bool isPantech() - * @method bool isFly() - * @method bool isWiko() - * @method bool isiMobile() - * @method bool isSimValley() - * @method bool isWolfgang() - * @method bool isAlcatel() - * @method bool isNintendo() - * @method bool isAmoi() - * @method bool isINQ() - * @method bool isOnePlus() - * @method bool isGenericPhone() - * @method bool isiPad() - * @method bool isNexusTablet() - * @method bool isGoogleTablet() - * @method bool isSamsungTablet() - * @method bool isKindle() - * @method bool isSurfaceTablet() - * @method bool isHPTablet() - * @method bool isAsusTablet() - * @method bool isBlackBerryTablet() - * @method bool isHTCtablet() - * @method bool isMotorolaTablet() - * @method bool isNookTablet() - * @method bool isAcerTablet() - * @method bool isToshibaTablet() - * @method bool isLGTablet() - * @method bool isFujitsuTablet() - * @method bool isPrestigioTablet() - * @method bool isLenovoTablet() - * @method bool isDellTablet() - * @method bool isYarvikTablet() - * @method bool isMedionTablet() - * @method bool isArnovaTablet() - * @method bool isIntensoTablet() - * @method bool isIRUTablet() - * @method bool isMegafonTablet() - * @method bool isEbodaTablet() - * @method bool isAllViewTablet() - * @method bool isArchosTablet() - * @method bool isAinolTablet() - * @method bool isNokiaLumiaTablet() - * @method bool isSonyTablet() - * @method bool isPhilipsTablet() - * @method bool isCubeTablet() - * @method bool isCobyTablet() - * @method bool isMIDTablet() - * @method bool isMSITablet() - * @method bool isSMiTTablet() - * @method bool isRockChipTablet() - * @method bool isFlyTablet() - * @method bool isbqTablet() - * @method bool isHuaweiTablet() - * @method bool isNecTablet() - * @method bool isPantechTablet() - * @method bool isBronchoTablet() - * @method bool isVersusTablet() - * @method bool isZyncTablet() - * @method bool isPositivoTablet() - * @method bool isNabiTablet() - * @method bool isKoboTablet() - * @method bool isDanewTablet() - * @method bool isTexetTablet() - * @method bool isPlaystationTablet() - * @method bool isTrekstorTablet() - * @method bool isPyleAudioTablet() - * @method bool isAdvanTablet() - * @method bool isDanyTechTablet() - * @method bool isGalapadTablet() - * @method bool isMicromaxTablet() - * @method bool isKarbonnTablet() - * @method bool isAllFineTablet() - * @method bool isPROSCANTablet() - * @method bool isYONESTablet() - * @method bool isChangJiaTablet() - * @method bool isGUTablet() - * @method bool isPointOfViewTablet() - * @method bool isOvermaxTablet() - * @method bool isHCLTablet() - * @method bool isDPSTablet() - * @method bool isVistureTablet() - * @method bool isCrestaTablet() - * @method bool isMediatekTablet() - * @method bool isConcordeTablet() - * @method bool isGoCleverTablet() - * @method bool isModecomTablet() - * @method bool isVoninoTablet() - * @method bool isECSTablet() - * @method bool isStorexTablet() - * @method bool isVodafoneTablet() - * @method bool isEssentielBTablet() - * @method bool isRossMoorTablet() - * @method bool isiMobileTablet() - * @method bool isTolinoTablet() - * @method bool isAudioSonicTablet() - * @method bool isAMPETablet() - * @method bool isSkkTablet() - * @method bool isTecnoTablet() - * @method bool isJXDTablet() - * @method bool isiJoyTablet() - * @method bool isFX2Tablet() - * @method bool isXoroTablet() - * @method bool isViewsonicTablet() - * @method bool isVerizonTablet() - * @method bool isOdysTablet() - * @method bool isCaptivaTablet() - * @method bool isIconbitTablet() - * @method bool isTeclastTablet() - * @method bool isOndaTablet() - * @method bool isJaytechTablet() - * @method bool isBlaupunktTablet() - * @method bool isDigmaTablet() - * @method bool isEvolioTablet() - * @method bool isLavaTablet() - * @method bool isAocTablet() - * @method bool isMpmanTablet() - * @method bool isCelkonTablet() - * @method bool isWolderTablet() - * @method bool isMediacomTablet() - * @method bool isMiTablet() - * @method bool isNibiruTablet() - * @method bool isNexoTablet() - * @method bool isLeaderTablet() - * @method bool isUbislateTablet() - * @method bool isPocketBookTablet() - * @method bool isKocasoTablet() - * @method bool isHisenseTablet() - * @method bool isHudl() - * @method bool isTelstraTablet() - * @method bool isGenericTablet() - * @method bool isAndroidOS() - * @method bool isBlackBerryOS() - * @method bool isPalmOS() - * @method bool isSymbianOS() - * @method bool isWindowsMobileOS() - * @method bool isWindowsPhoneOS() - * @method bool isiOS() - * @method bool isiPadOS() - * @method bool isSailfishOS() - * @method bool isMeeGoOS() - * @method bool isMaemoOS() - * @method bool isJavaOS() - * @method bool iswebOS() - * @method bool isbadaOS() - * @method bool isBREWOS() - * @method bool isChrome() - * @method bool isDolfin() - * @method bool isOpera() - * @method bool isSkyfire() - * @method bool isEdge() - * @method bool isIE() - * @method bool isFirefox() - * @method bool isBolt() - * @method bool isTeaShark() - * @method bool isBlazer() - * @method bool isSafari() - * @method bool isWeChat() - * @method bool isUCBrowser() - * @method bool isbaiduboxapp() - * @method bool isbaidubrowser() - * @method bool isDiigoBrowser() - * @method bool isMercury() - * @method bool isObigoBrowser() - * @method bool isNetFront() - * @method bool isGenericBrowser() - * @method bool isPaleMoon() - * @method bool isBot() - * @method bool isMobileBot() - * @method bool isDesktopMode() - * @method bool isTV() - * @method bool isWebKit() - * @method bool isConsole() - * @method bool isWatch() - - */ -class Mobile_Detect -{ - /** - * Mobile detection type. - * - * @deprecated since version 2.6.9 - */ - const DETECTION_TYPE_MOBILE = 'mobile'; - - /** - * Extended detection type. - * - * @deprecated since version 2.6.9 - */ - const DETECTION_TYPE_EXTENDED = 'extended'; - - /** - * A frequently used regular expression to extract version #s. - * - * @deprecated since version 2.6.9 - */ - const VER = '([\w._\+]+)'; - - /** - * Top-level device. - */ - const MOBILE_GRADE_A = 'A'; - - /** - * Mid-level device. - */ - const MOBILE_GRADE_B = 'B'; - - /** - * Low-level device. - */ - const MOBILE_GRADE_C = 'C'; - - /** - * Stores the version number of the current release. - */ - const VERSION = '2.8.37'; - - /** - * A type for the version() method indicating a string return value. - */ - const VERSION_TYPE_STRING = 'text'; - - /** - * A type for the version() method indicating a float return value. - */ - const VERSION_TYPE_FLOAT = 'float'; - - /** - * A cache for resolved matches - * @var array - */ - protected $cache = array(); - - /** - * The User-Agent HTTP header is stored in here. - * @var string - */ - protected $userAgent = null; - - /** - * HTTP headers in the PHP-flavor. So HTTP_USER_AGENT and SERVER_SOFTWARE. - * @var array - */ - protected $httpHeaders = array(); - - /** - * CloudFront headers. E.g. CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer & CloudFront-Is-Tablet-Viewer. - * @var array - */ - protected $cloudfrontHeaders = array(); - - /** - * The matching Regex. - * This is good for debug. - * @var string - */ - protected $matchingRegex = null; - - /** - * The matches extracted from the regex expression. - * This is good for debug. - * - * @var string - */ - protected $matchesArray = null; - - /** - * The detection type, using self::DETECTION_TYPE_MOBILE or self::DETECTION_TYPE_EXTENDED. - * - * @deprecated since version 2.6.9 - * - * @var string - */ - protected $detectionType = self::DETECTION_TYPE_MOBILE; - - /** - * HTTP headers that trigger the 'isMobile' detection - * to be true. - * - * @var array - */ - protected static $mobileHeaders = array( - - 'HTTP_ACCEPT' => array('matches' => array( - // Opera Mini; @reference: http://dev.opera.com/articles/view/opera-binary-markup-language/ - 'application/x-obml2d', - // BlackBerry devices. - 'application/vnd.rim.html', - 'text/vnd.wap.wml', - 'application/vnd.wap.xhtml+xml' - )), - 'HTTP_X_WAP_PROFILE' => null, - 'HTTP_X_WAP_CLIENTID' => null, - 'HTTP_WAP_CONNECTION' => null, - 'HTTP_PROFILE' => null, - // Reported by Opera on Nokia devices (eg. C3). - 'HTTP_X_OPERAMINI_PHONE_UA' => null, - 'HTTP_X_NOKIA_GATEWAY_ID' => null, - 'HTTP_X_ORANGE_ID' => null, - 'HTTP_X_VODAFONE_3GPDPCONTEXT' => null, - 'HTTP_X_HUAWEI_USERID' => null, - // Reported by Windows Smartphones. - 'HTTP_UA_OS' => null, - // Reported by Verizon, Vodafone proxy system. - 'HTTP_X_MOBILE_GATEWAY' => null, - // Seen this on HTC Sensation. SensationXE_Beats_Z715e. - 'HTTP_X_ATT_DEVICEID' => null, - // Seen this on a HTC. - 'HTTP_UA_CPU' => array('matches' => array('ARM')), - ); - - /** - * List of mobile devices (phones). - * - * @var array - */ - protected static $phoneDevices = array( - 'iPhone' => '\biPhone\b|\biPod\b', // |\biTunes - 'BlackBerry' => 'BlackBerry|\bBB10\b|rim[0-9]+|\b(BBA100|BBB100|BBD100|BBE100|BBF100|STH100)\b-[0-9]+', - 'Pixel' => '; \bPixel\b', - 'HTC' => 'HTC|HTC.*(Sensation|Evo|Vision|Explorer|6800|8100|8900|A7272|S510e|C110e|Legend|Desire|T8282)|APX515CKT|Qtek9090|APA9292KT|HD_mini|Sensation.*Z710e|PG86100|Z715e|Desire.*(A8181|HD)|ADR6200|ADR6400L|ADR6425|001HT|Inspire 4G|Android.*\bEVO\b|T-Mobile G1|Z520m|Android [0-9.]+; Pixel', - 'Nexus' => 'Nexus One|Nexus S|Galaxy.*Nexus|Android.*Nexus.*Mobile|Nexus 4|Nexus 5|Nexus 5X|Nexus 6', - // @todo: Is 'Dell Streak' a tablet or a phone? ;) - 'Dell' => 'Dell[;]? (Streak|Aero|Venue|Venue Pro|Flash|Smoke|Mini 3iX)|XCD28|XCD35|\b001DL\b|\b101DL\b|\bGS01\b', - 'Motorola' => 'Motorola|DROIDX|DROID BIONIC|\bDroid\b.*Build|Android.*Xoom|HRI39|MOT-|A1260|A1680|A555|A853|A855|A953|A955|A956|Motorola.*ELECTRIFY|Motorola.*i1|i867|i940|MB200|MB300|MB501|MB502|MB508|MB511|MB520|MB525|MB526|MB611|MB612|MB632|MB810|MB855|MB860|MB861|MB865|MB870|ME501|ME502|ME511|ME525|ME600|ME632|ME722|ME811|ME860|ME863|ME865|MT620|MT710|MT716|MT720|MT810|MT870|MT917|Motorola.*TITANIUM|WX435|WX445|XT300|XT301|XT311|XT316|XT317|XT319|XT320|XT390|XT502|XT530|XT531|XT532|XT535|XT603|XT610|XT611|XT615|XT681|XT701|XT702|XT711|XT720|XT800|XT806|XT860|XT862|XT875|XT882|XT883|XT894|XT901|XT907|XT909|XT910|XT912|XT928|XT926|XT915|XT919|XT925|XT1021|\bMoto E\b|XT1068|XT1092|XT1052', - 'Samsung' => '\bSamsung\b|SM-G950F|SM-G955F|SM-G9250|GT-19300|SGH-I337|BGT-S5230|GT-B2100|GT-B2700|GT-B2710|GT-B3210|GT-B3310|GT-B3410|GT-B3730|GT-B3740|GT-B5510|GT-B5512|GT-B5722|GT-B6520|GT-B7300|GT-B7320|GT-B7330|GT-B7350|GT-B7510|GT-B7722|GT-B7800|GT-C3010|GT-C3011|GT-C3060|GT-C3200|GT-C3212|GT-C3212I|GT-C3262|GT-C3222|GT-C3300|GT-C3300K|GT-C3303|GT-C3303K|GT-C3310|GT-C3322|GT-C3330|GT-C3350|GT-C3500|GT-C3510|GT-C3530|GT-C3630|GT-C3780|GT-C5010|GT-C5212|GT-C6620|GT-C6625|GT-C6712|GT-E1050|GT-E1070|GT-E1075|GT-E1080|GT-E1081|GT-E1085|GT-E1087|GT-E1100|GT-E1107|GT-E1110|GT-E1120|GT-E1125|GT-E1130|GT-E1160|GT-E1170|GT-E1175|GT-E1180|GT-E1182|GT-E1200|GT-E1210|GT-E1225|GT-E1230|GT-E1390|GT-E2100|GT-E2120|GT-E2121|GT-E2152|GT-E2220|GT-E2222|GT-E2230|GT-E2232|GT-E2250|GT-E2370|GT-E2550|GT-E2652|GT-E3210|GT-E3213|GT-I5500|GT-I5503|GT-I5700|GT-I5800|GT-I5801|GT-I6410|GT-I6420|GT-I7110|GT-I7410|GT-I7500|GT-I8000|GT-I8150|GT-I8160|GT-I8190|GT-I8320|GT-I8330|GT-I8350|GT-I8530|GT-I8700|GT-I8703|GT-I8910|GT-I9000|GT-I9001|GT-I9003|GT-I9010|GT-I9020|GT-I9023|GT-I9070|GT-I9082|GT-I9100|GT-I9103|GT-I9220|GT-I9250|GT-I9300|GT-I9305|GT-I9500|GT-I9505|GT-M3510|GT-M5650|GT-M7500|GT-M7600|GT-M7603|GT-M8800|GT-M8910|GT-N7000|GT-S3110|GT-S3310|GT-S3350|GT-S3353|GT-S3370|GT-S3650|GT-S3653|GT-S3770|GT-S3850|GT-S5210|GT-S5220|GT-S5229|GT-S5230|GT-S5233|GT-S5250|GT-S5253|GT-S5260|GT-S5263|GT-S5270|GT-S5300|GT-S5330|GT-S5350|GT-S5360|GT-S5363|GT-S5369|GT-S5380|GT-S5380D|GT-S5560|GT-S5570|GT-S5600|GT-S5603|GT-S5610|GT-S5620|GT-S5660|GT-S5670|GT-S5690|GT-S5750|GT-S5780|GT-S5830|GT-S5839|GT-S6102|GT-S6500|GT-S7070|GT-S7200|GT-S7220|GT-S7230|GT-S7233|GT-S7250|GT-S7500|GT-S7530|GT-S7550|GT-S7562|GT-S7710|GT-S8000|GT-S8003|GT-S8500|GT-S8530|GT-S8600|SCH-A310|SCH-A530|SCH-A570|SCH-A610|SCH-A630|SCH-A650|SCH-A790|SCH-A795|SCH-A850|SCH-A870|SCH-A890|SCH-A930|SCH-A950|SCH-A970|SCH-A990|SCH-I100|SCH-I110|SCH-I400|SCH-I405|SCH-I500|SCH-I510|SCH-I515|SCH-I600|SCH-I730|SCH-I760|SCH-I770|SCH-I830|SCH-I910|SCH-I920|SCH-I959|SCH-LC11|SCH-N150|SCH-N300|SCH-R100|SCH-R300|SCH-R351|SCH-R400|SCH-R410|SCH-T300|SCH-U310|SCH-U320|SCH-U350|SCH-U360|SCH-U365|SCH-U370|SCH-U380|SCH-U410|SCH-U430|SCH-U450|SCH-U460|SCH-U470|SCH-U490|SCH-U540|SCH-U550|SCH-U620|SCH-U640|SCH-U650|SCH-U660|SCH-U700|SCH-U740|SCH-U750|SCH-U810|SCH-U820|SCH-U900|SCH-U940|SCH-U960|SCS-26UC|SGH-A107|SGH-A117|SGH-A127|SGH-A137|SGH-A157|SGH-A167|SGH-A177|SGH-A187|SGH-A197|SGH-A227|SGH-A237|SGH-A257|SGH-A437|SGH-A517|SGH-A597|SGH-A637|SGH-A657|SGH-A667|SGH-A687|SGH-A697|SGH-A707|SGH-A717|SGH-A727|SGH-A737|SGH-A747|SGH-A767|SGH-A777|SGH-A797|SGH-A817|SGH-A827|SGH-A837|SGH-A847|SGH-A867|SGH-A877|SGH-A887|SGH-A897|SGH-A927|SGH-B100|SGH-B130|SGH-B200|SGH-B220|SGH-C100|SGH-C110|SGH-C120|SGH-C130|SGH-C140|SGH-C160|SGH-C170|SGH-C180|SGH-C200|SGH-C207|SGH-C210|SGH-C225|SGH-C230|SGH-C417|SGH-C450|SGH-D307|SGH-D347|SGH-D357|SGH-D407|SGH-D415|SGH-D780|SGH-D807|SGH-D980|SGH-E105|SGH-E200|SGH-E315|SGH-E316|SGH-E317|SGH-E335|SGH-E590|SGH-E635|SGH-E715|SGH-E890|SGH-F300|SGH-F480|SGH-I200|SGH-I300|SGH-I320|SGH-I550|SGH-I577|SGH-I600|SGH-I607|SGH-I617|SGH-I627|SGH-I637|SGH-I677|SGH-I700|SGH-I717|SGH-I727|SGH-i747M|SGH-I777|SGH-I780|SGH-I827|SGH-I847|SGH-I857|SGH-I896|SGH-I897|SGH-I900|SGH-I907|SGH-I917|SGH-I927|SGH-I937|SGH-I997|SGH-J150|SGH-J200|SGH-L170|SGH-L700|SGH-M110|SGH-M150|SGH-M200|SGH-N105|SGH-N500|SGH-N600|SGH-N620|SGH-N625|SGH-N700|SGH-N710|SGH-P107|SGH-P207|SGH-P300|SGH-P310|SGH-P520|SGH-P735|SGH-P777|SGH-Q105|SGH-R210|SGH-R220|SGH-R225|SGH-S105|SGH-S307|SGH-T109|SGH-T119|SGH-T139|SGH-T209|SGH-T219|SGH-T229|SGH-T239|SGH-T249|SGH-T259|SGH-T309|SGH-T319|SGH-T329|SGH-T339|SGH-T349|SGH-T359|SGH-T369|SGH-T379|SGH-T409|SGH-T429|SGH-T439|SGH-T459|SGH-T469|SGH-T479|SGH-T499|SGH-T509|SGH-T519|SGH-T539|SGH-T559|SGH-T589|SGH-T609|SGH-T619|SGH-T629|SGH-T639|SGH-T659|SGH-T669|SGH-T679|SGH-T709|SGH-T719|SGH-T729|SGH-T739|SGH-T746|SGH-T749|SGH-T759|SGH-T769|SGH-T809|SGH-T819|SGH-T839|SGH-T919|SGH-T929|SGH-T939|SGH-T959|SGH-T989|SGH-U100|SGH-U200|SGH-U800|SGH-V205|SGH-V206|SGH-X100|SGH-X105|SGH-X120|SGH-X140|SGH-X426|SGH-X427|SGH-X475|SGH-X495|SGH-X497|SGH-X507|SGH-X600|SGH-X610|SGH-X620|SGH-X630|SGH-X700|SGH-X820|SGH-X890|SGH-Z130|SGH-Z150|SGH-Z170|SGH-ZX10|SGH-ZX20|SHW-M110|SPH-A120|SPH-A400|SPH-A420|SPH-A460|SPH-A500|SPH-A560|SPH-A600|SPH-A620|SPH-A660|SPH-A700|SPH-A740|SPH-A760|SPH-A790|SPH-A800|SPH-A820|SPH-A840|SPH-A880|SPH-A900|SPH-A940|SPH-A960|SPH-D600|SPH-D700|SPH-D710|SPH-D720|SPH-I300|SPH-I325|SPH-I330|SPH-I350|SPH-I500|SPH-I600|SPH-I700|SPH-L700|SPH-M100|SPH-M220|SPH-M240|SPH-M300|SPH-M305|SPH-M320|SPH-M330|SPH-M350|SPH-M360|SPH-M370|SPH-M380|SPH-M510|SPH-M540|SPH-M550|SPH-M560|SPH-M570|SPH-M580|SPH-M610|SPH-M620|SPH-M630|SPH-M800|SPH-M810|SPH-M850|SPH-M900|SPH-M910|SPH-M920|SPH-M930|SPH-N100|SPH-N200|SPH-N240|SPH-N300|SPH-N400|SPH-Z400|SWC-E100|SCH-i909|GT-N7100|GT-N7105|SCH-I535|SM-N900A|SGH-I317|SGH-T999L|GT-S5360B|GT-I8262|GT-S6802|GT-S6312|GT-S6310|GT-S5312|GT-S5310|GT-I9105|GT-I8510|GT-S6790N|SM-G7105|SM-N9005|GT-S5301|GT-I9295|GT-I9195|SM-C101|GT-S7392|GT-S7560|GT-B7610|GT-I5510|GT-S7582|GT-S7530E|GT-I8750|SM-G9006V|SM-G9008V|SM-G9009D|SM-G900A|SM-G900D|SM-G900F|SM-G900H|SM-G900I|SM-G900J|SM-G900K|SM-G900L|SM-G900M|SM-G900P|SM-G900R4|SM-G900S|SM-G900T|SM-G900V|SM-G900W8|SHV-E160K|SCH-P709|SCH-P729|SM-T2558|GT-I9205|SM-G9350|SM-J120F|SM-G920F|SM-G920V|SM-G930F|SM-N910C|SM-A310F|GT-I9190|SM-J500FN|SM-G903F|SM-J330F|SM-G610F|SM-G981B|SM-G892A|SM-A530F', - 'LG' => '\bLG\b;|LG[- ]?(C800|C900|E400|E610|E900|E-900|F160|F180K|F180L|F180S|730|855|L160|LS740|LS840|LS970|LU6200|MS690|MS695|MS770|MS840|MS870|MS910|P500|P700|P705|VM696|AS680|AS695|AX840|C729|E970|GS505|272|C395|E739BK|E960|L55C|L75C|LS696|LS860|P769BK|P350|P500|P509|P870|UN272|US730|VS840|VS950|LN272|LN510|LS670|LS855|LW690|MN270|MN510|P509|P769|P930|UN200|UN270|UN510|UN610|US670|US740|US760|UX265|UX840|VN271|VN530|VS660|VS700|VS740|VS750|VS910|VS920|VS930|VX9200|VX11000|AX840A|LW770|P506|P925|P999|E612|D955|D802|MS323|M257)|LM-G710', - 'Sony' => 'SonyST|SonyLT|SonyEricsson|SonyEricssonLT15iv|LT18i|E10i|LT28h|LT26w|SonyEricssonMT27i|C5303|C6902|C6903|C6906|C6943|D2533|SOV34|601SO|F8332', - 'Asus' => 'Asus.*Galaxy|PadFone.*Mobile', - 'Xiaomi' => '^(?!.*\bx11\b).*xiaomi.*$|POCOPHONE F1|MI 8|Redmi Note 9S|Redmi Note 5A Prime|N2G47H|M2001J2G|M2001J2I|M1805E10A|M2004J11G|M1902F1G|M2002J9G|M2004J19G|M2003J6A1G', - 'NokiaLumia' => 'Lumia [0-9]{3,4}', - // http://www.micromaxinfo.com/mobiles/smartphones - // Added because the codes might conflict with Acer Tablets. - 'Micromax' => 'Micromax.*\b(A210|A92|A88|A72|A111|A110Q|A115|A116|A110|A90S|A26|A51|A35|A54|A25|A27|A89|A68|A65|A57|A90)\b', - // @todo Complete the regex. - 'Palm' => 'PalmSource|Palm', // avantgo|blazer|elaine|hiptop|plucker|xiino ; - 'Vertu' => 'Vertu|Vertu.*Ltd|Vertu.*Ascent|Vertu.*Ayxta|Vertu.*Constellation(F|Quest)?|Vertu.*Monika|Vertu.*Signature', // Just for fun ;) - // http://www.pantech.co.kr/en/prod/prodList.do?gbrand=VEGA (PANTECH) - // Most of the VEGA devices are legacy. PANTECH seem to be newer devices based on Android. - 'Pantech' => 'PANTECH|IM-A850S|IM-A840S|IM-A830L|IM-A830K|IM-A830S|IM-A820L|IM-A810K|IM-A810S|IM-A800S|IM-T100K|IM-A725L|IM-A780L|IM-A775C|IM-A770K|IM-A760S|IM-A750K|IM-A740S|IM-A730S|IM-A720L|IM-A710K|IM-A690L|IM-A690S|IM-A650S|IM-A630K|IM-A600S|VEGA PTL21|PT003|P8010|ADR910L|P6030|P6020|P9070|P4100|P9060|P5000|CDM8992|TXT8045|ADR8995|IS11PT|P2030|P6010|P8000|PT002|IS06|CDM8999|P9050|PT001|TXT8040|P2020|P9020|P2000|P7040|P7000|C790', - // http://www.fly-phone.com/devices/smartphones/ ; Included only smartphones. - 'Fly' => 'IQ230|IQ444|IQ450|IQ440|IQ442|IQ441|IQ245|IQ256|IQ236|IQ255|IQ235|IQ245|IQ275|IQ240|IQ285|IQ280|IQ270|IQ260|IQ250', - // http://fr.wikomobile.com - 'Wiko' => 'KITE 4G|HIGHWAY|GETAWAY|STAIRWAY|DARKSIDE|DARKFULL|DARKNIGHT|DARKMOON|SLIDE|WAX 4G|RAINBOW|BLOOM|SUNSET|GOA(?!nna)|LENNY|BARRY|IGGY|OZZY|CINK FIVE|CINK PEAX|CINK PEAX 2|CINK SLIM|CINK SLIM 2|CINK +|CINK KING|CINK PEAX|CINK SLIM|SUBLIM', - 'iMobile' => 'i-mobile (IQ|i-STYLE|idea|ZAA|Hitz)', - // Added simvalley mobile just for fun. They have some interesting devices. - // http://www.simvalley.fr/telephonie---gps-_22_telephonie-mobile_telephones_.html - 'SimValley' => '\b(SP-80|XT-930|SX-340|XT-930|SX-310|SP-360|SP60|SPT-800|SP-120|SPT-800|SP-140|SPX-5|SPX-8|SP-100|SPX-8|SPX-12)\b', - // Wolfgang - a brand that is sold by Aldi supermarkets. - // http://www.wolfgangmobile.com/ - 'Wolfgang' => 'AT-B24D|AT-AS50HD|AT-AS40W|AT-AS55HD|AT-AS45q2|AT-B26D|AT-AS50Q', - 'Alcatel' => 'Alcatel', - 'Nintendo' => 'Nintendo (3DS|Switch)', - // http://en.wikipedia.org/wiki/Amoi - 'Amoi' => 'Amoi', - // http://en.wikipedia.org/wiki/INQ - 'INQ' => 'INQ', - 'OnePlus' => 'ONEPLUS', - // @Tapatalk is a mobile app; http://support.tapatalk.com/threads/smf-2-0-2-os-and-browser-detection-plugin-and-tapatalk.15565/#post-79039 - 'GenericPhone' => 'Tapatalk|PDA;|SAGEM|\bmmp\b|pocket|\bpsp\b|symbian|Smartphone|smartfon|treo|up.browser|up.link|vodafone|\bwap\b|nokia|Series40|Series60|S60|SonyEricsson|N900|MAUI.*WAP.*Browser', - ); - - /** - * List of tablet devices. - * - * @var array - */ - protected static $tabletDevices = array( - // @todo: check for mobile friendly emails topic. - 'iPad' => 'iPad|iPad.*Mobile', - // Removed |^.*Android.*Nexus(?!(?:Mobile).)*$ - // @see #442 - // @todo Merge NexusTablet into GoogleTablet. - 'NexusTablet' => 'Android.*Nexus[\s]+(7|9|10)', - // https://en.wikipedia.org/wiki/Pixel_C - 'GoogleTablet' => 'Android.*Pixel C', - 'SamsungTablet' => 'SAMSUNG.*Tablet|Galaxy.*Tab|SC-01C|GT-P1000|GT-P1003|GT-P1010|GT-P3105|GT-P6210|GT-P6800|GT-P6810|GT-P7100|GT-P7300|GT-P7310|GT-P7500|GT-P7510|SCH-I800|SCH-I815|SCH-I905|SGH-I957|SGH-I987|SGH-T849|SGH-T859|SGH-T869|SPH-P100|GT-P3100|GT-P3108|GT-P3110|GT-P5100|GT-P5110|GT-P6200|GT-P7320|GT-P7511|GT-N8000|GT-P8510|SGH-I497|SPH-P500|SGH-T779|SCH-I705|SCH-I915|GT-N8013|GT-P3113|GT-P5113|GT-P8110|GT-N8010|GT-N8005|GT-N8020|GT-P1013|GT-P6201|GT-P7501|GT-N5100|GT-N5105|GT-N5110|SHV-E140K|SHV-E140L|SHV-E140S|SHV-E150S|SHV-E230K|SHV-E230L|SHV-E230S|SHW-M180K|SHW-M180L|SHW-M180S|SHW-M180W|SHW-M300W|SHW-M305W|SHW-M380K|SHW-M380S|SHW-M380W|SHW-M430W|SHW-M480K|SHW-M480S|SHW-M480W|SHW-M485W|SHW-M486W|SHW-M500W|GT-I9228|SCH-P739|SCH-I925|GT-I9200|GT-P5200|GT-P5210|GT-P5210X|SM-T311|SM-T310|SM-T310X|SM-T210|SM-T210R|SM-T211|SM-P600|SM-P601|SM-P605|SM-P900|SM-P901|SM-T217|SM-T217A|SM-T217S|SM-P6000|SM-T3100|SGH-I467|XE500|SM-T110|GT-P5220|GT-I9200X|GT-N5110X|GT-N5120|SM-P905|SM-T111|SM-T2105|SM-T315|SM-T320|SM-T320X|SM-T321|SM-T520|SM-T525|SM-T530NU|SM-T230NU|SM-T330NU|SM-T900|XE500T1C|SM-P605V|SM-P905V|SM-T337V|SM-T537V|SM-T707V|SM-T807V|SM-P600X|SM-P900X|SM-T210X|SM-T230|SM-T230X|SM-T325|GT-P7503|SM-T531|SM-T330|SM-T530|SM-T705|SM-T705C|SM-T535|SM-T331|SM-T800|SM-T700|SM-T537|SM-T807|SM-P907A|SM-T337A|SM-T537A|SM-T707A|SM-T807A|SM-T237|SM-T807P|SM-P607T|SM-T217T|SM-T337T|SM-T807T|SM-T116NQ|SM-T116BU|SM-P550|SM-T350|SM-T550|SM-T9000|SM-P9000|SM-T705Y|SM-T805|GT-P3113|SM-T710|SM-T810|SM-T815|SM-T360|SM-T533|SM-T113|SM-T335|SM-T715|SM-T560|SM-T670|SM-T677|SM-T377|SM-T567|SM-T357T|SM-T555|SM-T561|SM-T713|SM-T719|SM-T813|SM-T819|SM-T580|SM-T355Y?|SM-T280|SM-T817A|SM-T820|SM-W700|SM-P580|SM-T587|SM-P350|SM-P555M|SM-P355M|SM-T113NU|SM-T815Y|SM-T585|SM-T285|SM-T825|SM-W708|SM-T835|SM-T830|SM-T837V|SM-T720|SM-T510|SM-T387V|SM-P610|SM-T290|SM-T515|SM-T590|SM-T595|SM-T725|SM-T817P|SM-P585N0|SM-T395|SM-T295|SM-T865|SM-P610N|SM-P615|SM-T970|SM-T380|SM-T5950|SM-T905|SM-T231|SM-T500|SM-T860', // SCH-P709|SCH-P729|SM-T2558|GT-I9205 - Samsung Mega - treat them like a regular phone. - // http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html - 'Kindle' => 'Kindle|Silk.*Accelerated|Android.*\b(KFOT|KFTT|KFJWI|KFJWA|KFOTE|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|WFJWAE|KFSAWA|KFSAWI|KFASWI|KFARWI|KFFOWI|KFGIWI|KFMEWI)\b|Android.*Silk/[0-9.]+ like Chrome/[0-9.]+ (?!Mobile)', - // Only the Surface tablets with Windows RT are considered mobile. - // http://msdn.microsoft.com/en-us/library/ie/hh920767(v=vs.85).aspx - 'SurfaceTablet' => 'Windows NT [0-9.]+; ARM;.*(Tablet|ARMBJS)', - // http://shopping1.hp.com/is-bin/INTERSHOP.enfinity/WFS/WW-USSMBPublicStore-Site/en_US/-/USD/ViewStandardCatalog-Browse?CatalogCategoryID=JfIQ7EN5lqMAAAEyDcJUDwMT - 'HPTablet' => 'HP Slate (7|8|10)|HP ElitePad 900|hp-tablet|EliteBook.*Touch|HP 8|Slate 21|HP SlateBook 10', - // Watch out for PadFone, see #132. - // http://www.asus.com/de/Tablets_Mobile/Memo_Pad_Products/ - 'AsusTablet' => '^.*PadFone((?!Mobile).)*$|Transformer|TF101|TF101G|TF300T|TF300TG|TF300TL|TF700T|TF700KL|TF701T|TF810C|ME171|ME301T|ME302C|ME371MG|ME370T|ME372MG|ME172V|ME173X|ME400C|Slider SL101|\bK00F\b|\bK00C\b|\bK00E\b|\bK00L\b|TX201LA|ME176C|ME102A|\bM80TA\b|ME372CL|ME560CG|ME372CG|ME302KL| K010 | K011 | K017 | K01E |ME572C|ME103K|ME170C|ME171C|\bME70C\b|ME581C|ME581CL|ME8510C|ME181C|P01Y|PO1MA|P01Z|\bP027\b|\bP024\b|\bP00C\b', - 'BlackBerryTablet' => 'PlayBook|RIM Tablet', - 'HTCtablet' => 'HTC_Flyer_P512|HTC Flyer|HTC Jetstream|HTC-P715a|HTC EVO View 4G|PG41200|PG09410', - 'MotorolaTablet' => 'xoom|sholest|MZ615|MZ605|MZ505|MZ601|MZ602|MZ603|MZ604|MZ606|MZ607|MZ608|MZ609|MZ615|MZ616|MZ617', - 'NookTablet' => 'Android.*Nook|NookColor|nook browser|BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2', - // http://www.acer.ro/ac/ro/RO/content/drivers - // http://www.packardbell.co.uk/pb/en/GB/content/download (Packard Bell is part of Acer) - // http://us.acer.com/ac/en/US/content/group/tablets - // http://www.acer.de/ac/de/DE/content/models/tablets/ - // Can conflict with Micromax and Motorola phones codes. - 'AcerTablet' => 'Android.*; \b(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700|A701|W500|W500P|W501|W501P|W510|W511|W700|G100|G100W|B1-A71|B1-710|B1-711|A1-810|A1-811|A1-830)\b|W3-810|\bA3-A10\b|\bA3-A11\b|\bA3-A20\b|\bA3-A30|A3-A40', - // http://eu.computers.toshiba-europe.com/innovation/family/Tablets/1098744/banner_id/tablet_footerlink/ - // http://us.toshiba.com/tablets/tablet-finder - // http://www.toshiba.co.jp/regza/tablet/ - 'ToshibaTablet' => 'Android.*(AT100|AT105|AT200|AT205|AT270|AT275|AT300|AT305|AT1S5|AT500|AT570|AT700|AT830)|TOSHIBA.*FOLIO', - // http://www.nttdocomo.co.jp/english/service/developer/smart_phone/technical_info/spec/index.html - // http://www.lg.com/us/tablets - 'LGTablet' => '\bL-06C|LG-V909|LG-V900|LG-V700|LG-V510|LG-V500|LG-V410|LG-V400|LG-VK810\b', - 'FujitsuTablet' => 'Android.*\b(F-01D|F-02F|F-05E|F-10D|M532|Q572)\b', - // Prestigio Tablets http://www.prestigio.com/support - 'PrestigioTablet' => 'PMP3170B|PMP3270B|PMP3470B|PMP7170B|PMP3370B|PMP3570C|PMP5870C|PMP3670B|PMP5570C|PMP5770D|PMP3970B|PMP3870C|PMP5580C|PMP5880D|PMP5780D|PMP5588C|PMP7280C|PMP7280C3G|PMP7280|PMP7880D|PMP5597D|PMP5597|PMP7100D|PER3464|PER3274|PER3574|PER3884|PER5274|PER5474|PMP5097CPRO|PMP5097|PMP7380D|PMP5297C|PMP5297C_QUAD|PMP812E|PMP812E3G|PMP812F|PMP810E|PMP880TD|PMT3017|PMT3037|PMT3047|PMT3057|PMT7008|PMT5887|PMT5001|PMT5002', - // http://support.lenovo.com/en_GB/downloads/default.page?# - 'LenovoTablet' => 'Lenovo TAB|Idea(Tab|Pad)( A1|A10| K1|)|ThinkPad([ ]+)?Tablet|YT3-850M|YT3-X90L|YT3-X90F|YT3-X90X|Lenovo.*(S2109|S2110|S5000|S6000|K3011|A3000|A3500|A1000|A2107|A2109|A1107|A5500|A7600|B6000|B8000|B8080)(-|)(FL|F|HV|H|)|TB-X103F|TB-X304X|TB-X304F|TB-X304L|TB-X505F|TB-X505L|TB-X505X|TB-X605F|TB-X605L|TB-8703F|TB-8703X|TB-8703N|TB-8704N|TB-8704F|TB-8704X|TB-8704V|TB-7304F|TB-7304I|TB-7304X|Tab2A7-10F|Tab2A7-20F|TB2-X30L|YT3-X50L|YT3-X50F|YT3-X50M|YT-X705F|YT-X703F|YT-X703L|YT-X705L|YT-X705X|TB2-X30F|TB2-X30L|TB2-X30M|A2107A-F|A2107A-H|TB3-730F|TB3-730M|TB3-730X|TB-7504F|TB-7504X|TB-X704F|TB-X104F|TB3-X70F|TB-X705F|TB-8504F|TB3-X70L|TB3-710F|TB-X704L', - // http://www.dell.com/support/home/us/en/04/Products/tab_mob/tablets - 'DellTablet' => 'Venue 11|Venue 8|Venue 7|Dell Streak 10|Dell Streak 7', - // http://www.yarvik.com/en/matrix/tablets/ - 'YarvikTablet' => 'Android.*\b(TAB210|TAB211|TAB224|TAB250|TAB260|TAB264|TAB310|TAB360|TAB364|TAB410|TAB411|TAB420|TAB424|TAB450|TAB460|TAB461|TAB464|TAB465|TAB467|TAB468|TAB07-100|TAB07-101|TAB07-150|TAB07-151|TAB07-152|TAB07-200|TAB07-201-3G|TAB07-210|TAB07-211|TAB07-212|TAB07-214|TAB07-220|TAB07-400|TAB07-485|TAB08-150|TAB08-200|TAB08-201-3G|TAB08-201-30|TAB09-100|TAB09-211|TAB09-410|TAB10-150|TAB10-201|TAB10-211|TAB10-400|TAB10-410|TAB13-201|TAB274EUK|TAB275EUK|TAB374EUK|TAB462EUK|TAB474EUK|TAB9-200)\b', - 'MedionTablet' => 'Android.*\bOYO\b|LIFE.*(P9212|P9514|P9516|S9512)|LIFETAB', - 'ArnovaTablet' => '97G4|AN10G2|AN7bG3|AN7fG3|AN8G3|AN8cG3|AN7G3|AN9G3|AN7dG3|AN7dG3ST|AN7dG3ChildPad|AN10bG3|AN10bG3DT|AN9G2', - // http://www.intenso.de/kategorie_en.php?kategorie=33 - // @todo: http://www.nbhkdz.com/read/b8e64202f92a2df129126bff.html - investigate - 'IntensoTablet' => 'INM8002KP|INM1010FP|INM805ND|Intenso Tab|TAB1004', - // IRU.ru Tablets http://www.iru.ru/catalog/soho/planetable/ - 'IRUTablet' => 'M702pro', - 'MegafonTablet' => 'MegaFon V9|\bZTE V9\b|Android.*\bMT7A\b', - // http://www.e-boda.ro/tablete-pc.html - 'EbodaTablet' => 'E-Boda (Supreme|Impresspeed|Izzycomm|Essential)', - // http://www.allview.ro/produse/droseries/lista-tablete-pc/ - 'AllViewTablet' => 'Allview.*(Viva|Alldro|City|Speed|All TV|Frenzy|Quasar|Shine|TX1|AX1|AX2)', - // http://wiki.archosfans.com/index.php?title=Main_Page - // @note Rewrite the regex format after we add more UAs. - 'ArchosTablet' => '\b(101G9|80G9|A101IT)\b|Qilive 97R|Archos5|\bARCHOS (70|79|80|90|97|101|FAMILYPAD|)(b|c|)(G10| Cobalt| TITANIUM(HD|)| Xenon| Neon|XSK| 2| XS 2| PLATINUM| CARBON|GAMEPAD)\b', - // http://www.ainol.com/plugin.php?identifier=ainol&module=product - 'AinolTablet' => 'NOVO7|NOVO8|NOVO10|Novo7Aurora|Novo7Basic|NOVO7PALADIN|novo9-Spark', - 'NokiaLumiaTablet' => 'Lumia 2520', - // @todo: inspect http://esupport.sony.com/US/p/select-system.pl?DIRECTOR=DRIVER - // Readers http://www.atsuhiro-me.net/ebook/sony-reader/sony-reader-web-browser - // http://www.sony.jp/support/tablet/ - 'SonyTablet' => 'Sony.*Tablet|Xperia Tablet|Sony Tablet S|SO-03E|SGPT12|SGPT13|SGPT114|SGPT121|SGPT122|SGPT123|SGPT111|SGPT112|SGPT113|SGPT131|SGPT132|SGPT133|SGPT211|SGPT212|SGPT213|SGP311|SGP312|SGP321|EBRD1101|EBRD1102|EBRD1201|SGP351|SGP341|SGP511|SGP512|SGP521|SGP541|SGP551|SGP621|SGP641|SGP612|SOT31|SGP771|SGP611|SGP612|SGP712', - // http://www.support.philips.com/support/catalog/worldproducts.jsp?userLanguage=en&userCountry=cn&categoryid=3G_LTE_TABLET_SU_CN_CARE&title=3G%20tablets%20/%20LTE%20range&_dyncharset=UTF-8 - 'PhilipsTablet' => '\b(PI2010|PI3000|PI3100|PI3105|PI3110|PI3205|PI3210|PI3900|PI4010|PI7000|PI7100)\b', - // db + http://www.cube-tablet.com/buy-products.html - 'CubeTablet' => 'Android.*(K8GT|U9GT|U10GT|U16GT|U17GT|U18GT|U19GT|U20GT|U23GT|U30GT)|CUBE U8GT', - // http://www.cobyusa.com/?p=pcat&pcat_id=3001 - 'CobyTablet' => 'MID1042|MID1045|MID1125|MID1126|MID7012|MID7014|MID7015|MID7034|MID7035|MID7036|MID7042|MID7048|MID7127|MID8042|MID8048|MID8127|MID9042|MID9740|MID9742|MID7022|MID7010', - // http://www.match.net.cn/products.asp - 'MIDTablet' => 'M9701|M9000|M9100|M806|M1052|M806|T703|MID701|MID713|MID710|MID727|MID760|MID830|MID728|MID933|MID125|MID810|MID732|MID120|MID930|MID800|MID731|MID900|MID100|MID820|MID735|MID980|MID130|MID833|MID737|MID960|MID135|MID860|MID736|MID140|MID930|MID835|MID733|MID4X10', - // http://www.msi.com/support - // @todo Research the Windows Tablets. - 'MSITablet' => 'MSI \b(Primo 73K|Primo 73L|Primo 81L|Primo 77|Primo 93|Primo 75|Primo 76|Primo 73|Primo 81|Primo 91|Primo 90|Enjoy 71|Enjoy 7|Enjoy 10)\b', - // @todo http://www.kyoceramobile.com/support/drivers/ - // 'KyoceraTablet' => null, - // @todo http://intexuae.com/index.php/category/mobile-devices/tablets-products/ - // 'IntextTablet' => null, - // http://pdadb.net/index.php?m=pdalist&list=SMiT (NoName Chinese Tablets) - // http://www.imp3.net/14/show.php?itemid=20454 - 'SMiTTablet' => 'Android.*(\bMID\b|MID-560|MTV-T1200|MTV-PND531|MTV-P1101|MTV-PND530)', - // http://www.rock-chips.com/index.php?do=prod&pid=2 - 'RockChipTablet' => 'Android.*(RK2818|RK2808A|RK2918|RK3066)|RK2738|RK2808A', - // http://www.fly-phone.com/devices/tablets/ ; http://www.fly-phone.com/service/ - 'FlyTablet' => 'IQ310|Fly Vision', - // http://www.bqreaders.com/gb/tablets-prices-sale.html - 'bqTablet' => 'Android.*(bq)?.*\b(Elcano|Curie|Edison|Maxwell|Kepler|Pascal|Tesla|Hypatia|Platon|Newton|Livingstone|Cervantes|Avant|Aquaris ([E|M]10|M8))\b|Maxwell.*Lite|Maxwell.*Plus', - // http://www.huaweidevice.com/worldwide/productFamily.do?method=index&directoryId=5011&treeId=3290 - // http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index&directoryId=3372&treeId=0&tb=1&type=software (including legacy tablets) - 'HuaweiTablet' => 'MediaPad|MediaPad 7 Youth|IDEOS S7|S7-201c|S7-202u|S7-101|S7-103|S7-104|S7-105|S7-106|S7-201|S7-Slim|M2-A01L|BAH-L09|BAH-W09|AGS-L09|CMR-AL19', - // Nec or Medias Tab - 'NecTablet' => '\bN-06D|\bN-08D', - // Pantech Tablets: http://www.pantechusa.com/phones/ - 'PantechTablet' => 'Pantech.*P4100', - // Broncho Tablets: http://www.broncho.cn/ (hard to find) - 'BronchoTablet' => 'Broncho.*(N701|N708|N802|a710)', - // http://versusuk.com/support.html - 'VersusTablet' => 'TOUCHPAD.*[78910]|\bTOUCHTAB\b', - // http://www.zync.in/index.php/our-products/tablet-phablets - 'ZyncTablet' => 'z1000|Z99 2G|z930|z990|z909|Z919|z900', // Removed "z999" because of https://github.com/serbanghita/Mobile-Detect/issues/717 - // http://www.positivoinformatica.com.br/www/pessoal/tablet-ypy/ - 'PositivoTablet' => 'TB07STA|TB10STA|TB07FTA|TB10FTA', - // https://www.nabitablet.com/ - 'NabiTablet' => 'Android.*\bNabi', - 'KoboTablet' => 'Kobo Touch|\bK080\b|\bVox\b Build|\bArc\b Build', - // French Danew Tablets http://www.danew.com/produits-tablette.php - 'DanewTablet' => 'DSlide.*\b(700|701R|702|703R|704|802|970|971|972|973|974|1010|1012)\b', - // Texet Tablets and Readers http://www.texet.ru/tablet/ - 'TexetTablet' => 'NaviPad|TB-772A|TM-7045|TM-7055|TM-9750|TM-7016|TM-7024|TM-7026|TM-7041|TM-7043|TM-7047|TM-8041|TM-9741|TM-9747|TM-9748|TM-9751|TM-7022|TM-7021|TM-7020|TM-7011|TM-7010|TM-7023|TM-7025|TM-7037W|TM-7038W|TM-7027W|TM-9720|TM-9725|TM-9737W|TM-1020|TM-9738W|TM-9740|TM-9743W|TB-807A|TB-771A|TB-727A|TB-725A|TB-719A|TB-823A|TB-805A|TB-723A|TB-715A|TB-707A|TB-705A|TB-709A|TB-711A|TB-890HD|TB-880HD|TB-790HD|TB-780HD|TB-770HD|TB-721HD|TB-710HD|TB-434HD|TB-860HD|TB-840HD|TB-760HD|TB-750HD|TB-740HD|TB-730HD|TB-722HD|TB-720HD|TB-700HD|TB-500HD|TB-470HD|TB-431HD|TB-430HD|TB-506|TB-504|TB-446|TB-436|TB-416|TB-146SE|TB-126SE', - // Avoid detecting 'PLAYSTATION 3' as mobile. - 'PlaystationTablet' => 'Playstation.*(Portable|Vita)', - // http://www.trekstor.de/surftabs.html - 'TrekstorTablet' => 'ST10416-1|VT10416-1|ST70408-1|ST702xx-1|ST702xx-2|ST80208|ST97216|ST70104-2|VT10416-2|ST10216-2A|SurfTab', - // http://www.pyleaudio.com/Products.aspx?%2fproducts%2fPersonal-Electronics%2fTablets - 'PyleAudioTablet' => '\b(PTBL10CEU|PTBL10C|PTBL72BC|PTBL72BCEU|PTBL7CEU|PTBL7C|PTBL92BC|PTBL92BCEU|PTBL9CEU|PTBL9CUK|PTBL9C)\b', - // http://www.advandigital.com/index.php?link=content-product&jns=JP001 - // because of the short codenames we have to include whitespaces to reduce the possible conflicts. - 'AdvanTablet' => 'Android.* \b(E3A|T3X|T5C|T5B|T3E|T3C|T3B|T1J|T1F|T2A|T1H|T1i|E1C|T1-E|T5-A|T4|E1-B|T2Ci|T1-B|T1-D|O1-A|E1-A|T1-A|T3A|T4i)\b ', - // http://www.danytech.com/category/tablet-pc - 'DanyTechTablet' => 'Genius Tab G3|Genius Tab S2|Genius Tab Q3|Genius Tab G4|Genius Tab Q4|Genius Tab G-II|Genius TAB GII|Genius TAB GIII|Genius Tab S1', - // http://www.galapad.net/product.html ; https://github.com/serbanghita/Mobile-Detect/issues/761 - 'GalapadTablet' => 'Android [0-9.]+; [a-z-]+; \bG1\b', - // http://www.micromaxinfo.com/tablet/funbook - 'MicromaxTablet' => 'Funbook|Micromax.*\b(P250|P560|P360|P362|P600|P300|P350|P500|P275)\b', - // http://www.karbonnmobiles.com/products_tablet.php - 'KarbonnTablet' => 'Android.*\b(A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2)\b', - // http://www.myallfine.com/Products.asp - 'AllFineTablet' => 'Fine7 Genius|Fine7 Shine|Fine7 Air|Fine8 Style|Fine9 More|Fine10 Joy|Fine11 Wide', - // http://www.proscanvideo.com/products-search.asp?itemClass=TABLET&itemnmbr= - 'PROSCANTablet' => '\b(PEM63|PLT1023G|PLT1041|PLT1044|PLT1044G|PLT1091|PLT4311|PLT4311PL|PLT4315|PLT7030|PLT7033|PLT7033D|PLT7035|PLT7035D|PLT7044K|PLT7045K|PLT7045KB|PLT7071KG|PLT7072|PLT7223G|PLT7225G|PLT7777G|PLT7810K|PLT7849G|PLT7851G|PLT7852G|PLT8015|PLT8031|PLT8034|PLT8036|PLT8080K|PLT8082|PLT8088|PLT8223G|PLT8234G|PLT8235G|PLT8816K|PLT9011|PLT9045K|PLT9233G|PLT9735|PLT9760G|PLT9770G)\b', - // http://www.yonesnav.com/products/products.php - 'YONESTablet' => 'BQ1078|BC1003|BC1077|RK9702|BC9730|BC9001|IT9001|BC7008|BC7010|BC708|BC728|BC7012|BC7030|BC7027|BC7026', - // http://www.cjshowroom.com/eproducts.aspx?classcode=004001001 - // China manufacturer makes tablets for different small brands (eg. http://www.zeepad.net/index.html) - 'ChangJiaTablet' => 'TPC7102|TPC7103|TPC7105|TPC7106|TPC7107|TPC7201|TPC7203|TPC7205|TPC7210|TPC7708|TPC7709|TPC7712|TPC7110|TPC8101|TPC8103|TPC8105|TPC8106|TPC8203|TPC8205|TPC8503|TPC9106|TPC9701|TPC97101|TPC97103|TPC97105|TPC97106|TPC97111|TPC97113|TPC97203|TPC97603|TPC97809|TPC97205|TPC10101|TPC10103|TPC10106|TPC10111|TPC10203|TPC10205|TPC10503', - // http://www.gloryunion.cn/products.asp - // http://www.allwinnertech.com/en/apply/mobile.html - // http://www.ptcl.com.pk/pd_content.php?pd_id=284 (EVOTAB) - // @todo: Softwiner tablets? - // aka. Cute or Cool tablets. Not sure yet, must research to avoid collisions. - 'GUTablet' => 'TX-A1301|TX-M9002|Q702|kf026', // A12R|D75A|D77|D79|R83|A95|A106C|R15|A75|A76|D71|D72|R71|R73|R77|D82|R85|D92|A97|D92|R91|A10F|A77F|W71F|A78F|W78F|W81F|A97F|W91F|W97F|R16G|C72|C73E|K72|K73|R96G - // http://www.pointofview-online.com/showroom.php?shop_mode=product_listing&category_id=118 - 'PointOfViewTablet' => 'TAB-P506|TAB-navi-7-3G-M|TAB-P517|TAB-P-527|TAB-P701|TAB-P703|TAB-P721|TAB-P731N|TAB-P741|TAB-P825|TAB-P905|TAB-P925|TAB-PR945|TAB-PL1015|TAB-P1025|TAB-PI1045|TAB-P1325|TAB-PROTAB[0-9]+|TAB-PROTAB25|TAB-PROTAB26|TAB-PROTAB27|TAB-PROTAB26XL|TAB-PROTAB2-IPS9|TAB-PROTAB30-IPS9|TAB-PROTAB25XXL|TAB-PROTAB26-IPS10|TAB-PROTAB30-IPS10', - // http://www.overmax.pl/pl/katalog-produktow,p8/tablety,c14/ - // @todo: add more tests. - 'OvermaxTablet' => 'OV-(SteelCore|NewBase|Basecore|Baseone|Exellen|Quattor|EduTab|Solution|ACTION|BasicTab|TeddyTab|MagicTab|Stream|TB-08|TB-09)|Qualcore 1027', - // http://hclmetablet.com/India/index.php - 'HCLTablet' => 'HCL.*Tablet|Connect-3G-2.0|Connect-2G-2.0|ME Tablet U1|ME Tablet U2|ME Tablet G1|ME Tablet X1|ME Tablet Y2|ME Tablet Sync', - // http://www.edigital.hu/Tablet_es_e-book_olvaso/Tablet-c18385.html - 'DPSTablet' => 'DPS Dream 9|DPS Dual 7', - // http://www.visture.com/index.asp - 'VistureTablet' => 'V97 HD|i75 3G|Visture V4( HD)?|Visture V5( HD)?|Visture V10', - // http://www.mijncresta.nl/tablet - 'CrestaTablet' => 'CTP(-)?810|CTP(-)?818|CTP(-)?828|CTP(-)?838|CTP(-)?888|CTP(-)?978|CTP(-)?980|CTP(-)?987|CTP(-)?988|CTP(-)?989', - // MediaTek - http://www.mediatek.com/_en/01_products/02_proSys.php?cata_sn=1&cata1_sn=1&cata2_sn=309 - 'MediatekTablet' => '\bMT8125|MT8389|MT8135|MT8377\b', - // Concorde tab - 'ConcordeTablet' => 'Concorde([ ]+)?Tab|ConCorde ReadMan', - // GoClever Tablets - http://www.goclever.com/uk/products,c1/tablet,c5/ - 'GoCleverTablet' => 'GOCLEVER TAB|A7GOCLEVER|M1042|M7841|M742|R1042BK|R1041|TAB A975|TAB A7842|TAB A741|TAB A741L|TAB M723G|TAB M721|TAB A1021|TAB I921|TAB R721|TAB I720|TAB T76|TAB R70|TAB R76.2|TAB R106|TAB R83.2|TAB M813G|TAB I721|GCTA722|TAB I70|TAB I71|TAB S73|TAB R73|TAB R74|TAB R93|TAB R75|TAB R76.1|TAB A73|TAB A93|TAB A93.2|TAB T72|TAB R83|TAB R974|TAB R973|TAB A101|TAB A103|TAB A104|TAB A104.2|R105BK|M713G|A972BK|TAB A971|TAB R974.2|TAB R104|TAB R83.3|TAB A1042', - // Modecom Tablets - http://www.modecom.eu/tablets/portal/ - 'ModecomTablet' => 'FreeTAB 9000|FreeTAB 7.4|FreeTAB 7004|FreeTAB 7800|FreeTAB 2096|FreeTAB 7.5|FreeTAB 1014|FreeTAB 1001 |FreeTAB 8001|FreeTAB 9706|FreeTAB 9702|FreeTAB 7003|FreeTAB 7002|FreeTAB 1002|FreeTAB 7801|FreeTAB 1331|FreeTAB 1004|FreeTAB 8002|FreeTAB 8014|FreeTAB 9704|FreeTAB 1003', - // Vonino Tablets - 'VoninoTablet' => '\b(Argus[ _]?S|Diamond[ _]?79HD|Emerald[ _]?78E|Luna[ _]?70C|Onyx[ _]?S|Onyx[ _]?Z|Orin[ _]?HD|Orin[ _]?S|Otis[ _]?S|SpeedStar[ _]?S|Magnet[ _]?M9|Primus[ _]?94[ _]?3G|Primus[ _]?94HD|Primus[ _]?QS|Android.*\bQ8\b|Sirius[ _]?EVO[ _]?QS|Sirius[ _]?QS|Spirit[ _]?S)\b', - // ECS Tablets - http://www.ecs.com.tw/ECSWebSite/Product/Product_Tablet_List.aspx?CategoryID=14&MenuID=107&childid=M_107&LanID=0 - 'ECSTablet' => 'V07OT2|TM105A|S10OT1|TR10CS1', - // Storex Tablets - http://storex.fr/espace_client/support.html - // @note: no need to add all the tablet codes since they are guided by the first regex. - 'StorexTablet' => 'eZee[_\']?(Tab|Go)[0-9]+|TabLC7|Looney Tunes Tab', - // Generic Vodafone tablets. - 'VodafoneTablet' => 'SmartTab([ ]+)?[0-9]+|SmartTabII10|SmartTabII7|VF-1497|VFD 1400', - // French tablets - Essentiel B http://www.boulanger.fr/tablette_tactile_e-book/tablette_tactile_essentiel_b/cl_68908.htm?multiChoiceToDelete=brand&mc_brand=essentielb - // Aka: http://www.essentielb.fr/ - 'EssentielBTablet' => 'Smart[ \']?TAB[ ]+?[0-9]+|Family[ \']?TAB2', - // Ross & Moor - http://ross-moor.ru/ - 'RossMoorTablet' => 'RM-790|RM-997|RMD-878G|RMD-974R|RMT-705A|RMT-701|RME-601|RMT-501|RMT-711', - // i-mobile http://product.i-mobilephone.com/Mobile_Device - 'iMobileTablet' => 'i-mobile i-note', - // http://www.tolino.de/de/vergleichen/ - 'TolinoTablet' => 'tolino tab [0-9.]+|tolino shine', - // AudioSonic - a Kmart brand - // http://www.kmart.com.au/webapp/wcs/stores/servlet/Search?langId=-1&storeId=10701&catalogId=10001&categoryId=193001&pageSize=72¤tPage=1&searchCategory=193001%2b4294965664&sortBy=p_MaxPrice%7c1 - 'AudioSonicTablet' => '\bC-22Q|T7-QC|T-17B|T-17P\b', - // AMPE Tablets - http://www.ampe.com.my/product-category/tablets/ - // @todo: add them gradually to avoid conflicts. - 'AMPETablet' => 'Android.* A78 ', - // Skk Mobile - http://skkmobile.com.ph/product_tablets.php - 'SkkTablet' => 'Android.* (SKYPAD|PHOENIX|CYCLOPS)', - // Tecno Mobile (only tablet) - http://www.tecno-mobile.com/index.php/product?filterby=smart&list_order=all&page=1 - 'TecnoTablet' => 'TECNO P9|TECNO DP8D', - // JXD (consoles & tablets) - http://jxd.hk/products.asp?selectclassid=009008&clsid=3 - 'JXDTablet' => 'Android.* \b(F3000|A3300|JXD5000|JXD3000|JXD2000|JXD300B|JXD300|S5800|S7800|S602b|S5110b|S7300|S5300|S602|S603|S5100|S5110|S601|S7100a|P3000F|P3000s|P101|P200s|P1000m|P200m|P9100|P1000s|S6600b|S908|P1000|P300|S18|S6600|S9100)\b', - // i-Joy tablets - http://www.i-joy.es/en/cat/products/tablets/ - 'iJoyTablet' => 'Tablet (Spirit 7|Essentia|Galatea|Fusion|Onix 7|Landa|Titan|Scooby|Deox|Stella|Themis|Argon|Unique 7|Sygnus|Hexen|Finity 7|Cream|Cream X2|Jade|Neon 7|Neron 7|Kandy|Scape|Saphyr 7|Rebel|Biox|Rebel|Rebel 8GB|Myst|Draco 7|Myst|Tab7-004|Myst|Tadeo Jones|Tablet Boing|Arrow|Draco Dual Cam|Aurix|Mint|Amity|Revolution|Finity 9|Neon 9|T9w|Amity 4GB Dual Cam|Stone 4GB|Stone 8GB|Andromeda|Silken|X2|Andromeda II|Halley|Flame|Saphyr 9,7|Touch 8|Planet|Triton|Unique 10|Hexen 10|Memphis 4GB|Memphis 8GB|Onix 10)', - // http://www.intracon.eu/tablet - 'FX2Tablet' => 'FX2 PAD7|FX2 PAD10', - // http://www.xoro.de/produkte/ - // @note: Might be the same brand with 'Simply tablets' - 'XoroTablet' => 'KidsPAD 701|PAD[ ]?712|PAD[ ]?714|PAD[ ]?716|PAD[ ]?717|PAD[ ]?718|PAD[ ]?720|PAD[ ]?721|PAD[ ]?722|PAD[ ]?790|PAD[ ]?792|PAD[ ]?900|PAD[ ]?9715D|PAD[ ]?9716DR|PAD[ ]?9718DR|PAD[ ]?9719QR|PAD[ ]?9720QR|TelePAD1030|Telepad1032|TelePAD730|TelePAD731|TelePAD732|TelePAD735Q|TelePAD830|TelePAD9730|TelePAD795|MegaPAD 1331|MegaPAD 1851|MegaPAD 2151', - // http://www1.viewsonic.com/products/computing/tablets/ - 'ViewsonicTablet' => 'ViewPad 10pi|ViewPad 10e|ViewPad 10s|ViewPad E72|ViewPad7|ViewPad E100|ViewPad 7e|ViewSonic VB733|VB100a', - // https://www.verizonwireless.com/tablets/verizon/ - 'VerizonTablet' => 'QTAQZ3|QTAIR7|QTAQTZ3|QTASUN1|QTASUN2|QTAXIA1', - // http://www.odys.de/web/internet-tablet_en.html - 'OdysTablet' => 'LOOX|XENO10|ODYS[ -](Space|EVO|Xpress|NOON)|\bXELIO\b|Xelio10Pro|XELIO7PHONETAB|XELIO10EXTREME|XELIOPT2|NEO_QUAD10', - // http://www.captiva-power.de/products.html#tablets-en - 'CaptivaTablet' => 'CAPTIVA PAD', - // IconBIT - http://www.iconbit.com/products/tablets/ - 'IconbitTablet' => 'NetTAB|NT-3702|NT-3702S|NT-3702S|NT-3603P|NT-3603P|NT-0704S|NT-0704S|NT-3805C|NT-3805C|NT-0806C|NT-0806C|NT-0909T|NT-0909T|NT-0907S|NT-0907S|NT-0902S|NT-0902S', - // http://www.teclast.com/topic.php?channelID=70&topicID=140&pid=63 - 'TeclastTablet' => 'T98 4G|\bP80\b|\bX90HD\b|X98 Air|X98 Air 3G|\bX89\b|P80 3G|\bX80h\b|P98 Air|\bX89HD\b|P98 3G|\bP90HD\b|P89 3G|X98 3G|\bP70h\b|P79HD 3G|G18d 3G|\bP79HD\b|\bP89s\b|\bA88\b|\bP10HD\b|\bP19HD\b|G18 3G|\bP78HD\b|\bA78\b|\bP75\b|G17s 3G|G17h 3G|\bP85t\b|\bP90\b|\bP11\b|\bP98t\b|\bP98HD\b|\bG18d\b|\bP85s\b|\bP11HD\b|\bP88s\b|\bA80HD\b|\bA80se\b|\bA10h\b|\bP89\b|\bP78s\b|\bG18\b|\bP85\b|\bA70h\b|\bA70\b|\bG17\b|\bP18\b|\bA80s\b|\bA11s\b|\bP88HD\b|\bA80h\b|\bP76s\b|\bP76h\b|\bP98\b|\bA10HD\b|\bP78\b|\bP88\b|\bA11\b|\bA10t\b|\bP76a\b|\bP76t\b|\bP76e\b|\bP85HD\b|\bP85a\b|\bP86\b|\bP75HD\b|\bP76v\b|\bA12\b|\bP75a\b|\bA15\b|\bP76Ti\b|\bP81HD\b|\bA10\b|\bT760VE\b|\bT720HD\b|\bP76\b|\bP73\b|\bP71\b|\bP72\b|\bT720SE\b|\bC520Ti\b|\bT760\b|\bT720VE\b|T720-3GE|T720-WiFi', - // Onda - http://www.onda-tablet.com/buy-android-onda.html?dir=desc&limit=all&order=price - 'OndaTablet' => '\b(V975i|Vi30|VX530|V701|Vi60|V701s|Vi50|V801s|V719|Vx610w|VX610W|V819i|Vi10|VX580W|Vi10|V711s|V813|V811|V820w|V820|Vi20|V711|VI30W|V712|V891w|V972|V819w|V820w|Vi60|V820w|V711|V813s|V801|V819|V975s|V801|V819|V819|V818|V811|V712|V975m|V101w|V961w|V812|V818|V971|V971s|V919|V989|V116w|V102w|V973|Vi40)\b[\s]+|V10 \b4G\b', - 'JaytechTablet' => 'TPC-PA762', - 'BlaupunktTablet' => 'Endeavour 800NG|Endeavour 1010', - // http://www.digma.ru/support/download/ - // @todo: Ebooks also (if requested) - 'DigmaTablet' => '\b(iDx10|iDx9|iDx8|iDx7|iDxD7|iDxD8|iDsQ8|iDsQ7|iDsQ8|iDsD10|iDnD7|3TS804H|iDsQ11|iDj7|iDs10)\b', - // http://www.evolioshop.com/ro/tablete-pc.html - // http://www.evolio.ro/support/downloads_static.html?cat=2 - // @todo: Research some more - 'EvolioTablet' => 'ARIA_Mini_wifi|Aria[ _]Mini|Evolio X10|Evolio X7|Evolio X8|\bEvotab\b|\bNeura\b', - // @todo http://www.lavamobiles.com/tablets-data-cards - 'LavaTablet' => 'QPAD E704|\bIvoryS\b|E-TAB IVORY|\bE-TAB\b', - // http://www.breezetablet.com/ - 'AocTablet' => 'MW0811|MW0812|MW0922|MTK8382|MW1031|MW0831|MW0821|MW0931|MW0712', - // http://www.mpmaneurope.com/en/products/internet-tablets-14/android-tablets-14/ - 'MpmanTablet' => 'MP11 OCTA|MP10 OCTA|MPQC1114|MPQC1004|MPQC994|MPQC974|MPQC973|MPQC804|MPQC784|MPQC780|\bMPG7\b|MPDCG75|MPDCG71|MPDC1006|MP101DC|MPDC9000|MPDC905|MPDC706HD|MPDC706|MPDC705|MPDC110|MPDC100|MPDC99|MPDC97|MPDC88|MPDC8|MPDC77|MP709|MID701|MID711|MID170|MPDC703|MPQC1010', - // https://www.celkonmobiles.com/?_a=categoryphones&sid=2 - 'CelkonTablet' => 'CT695|CT888|CT[\s]?910|CT7 Tab|CT9 Tab|CT3 Tab|CT2 Tab|CT1 Tab|C820|C720|\bCT-1\b', - // http://www.wolderelectronics.com/productos/manuales-y-guias-rapidas/categoria-2-miTab - 'WolderTablet' => 'miTab \b(DIAMOND|SPACE|BROOKLYN|NEO|FLY|MANHATTAN|FUNK|EVOLUTION|SKY|GOCAR|IRON|GENIUS|POP|MINT|EPSILON|BROADWAY|JUMP|HOP|LEGEND|NEW AGE|LINE|ADVANCE|FEEL|FOLLOW|LIKE|LINK|LIVE|THINK|FREEDOM|CHICAGO|CLEVELAND|BALTIMORE-GH|IOWA|BOSTON|SEATTLE|PHOENIX|DALLAS|IN 101|MasterChef)\b', - 'MediacomTablet' => 'M-MPI10C3G|M-SP10EG|M-SP10EGP|M-SP10HXAH|M-SP7HXAH|M-SP10HXBH|M-SP8HXAH|M-SP8MXA', - // http://www.mi.com/en - 'MiTablet' => '\bMI PAD\b|\bHM NOTE 1W\b', - // http://www.nbru.cn/index.html - 'NibiruTablet' => 'Nibiru M1|Nibiru Jupiter One', - // http://navroad.com/products/produkty/tablety/ - // http://navroad.com/products/produkty/tablety/ - 'NexoTablet' => 'NEXO NOVA|NEXO 10|NEXO AVIO|NEXO FREE|NEXO GO|NEXO EVO|NEXO 3G|NEXO SMART|NEXO KIDDO|NEXO MOBI', - // http://leader-online.com/new_site/product-category/tablets/ - // http://www.leader-online.net.au/List/Tablet - 'LeaderTablet' => 'TBLT10Q|TBLT10I|TBL-10WDKB|TBL-10WDKBO2013|TBL-W230V2|TBL-W450|TBL-W500|SV572|TBLT7I|TBA-AC7-8G|TBLT79|TBL-8W16|TBL-10W32|TBL-10WKB|TBL-W100', - // http://www.datawind.com/ubislate/ - 'UbislateTablet' => 'UbiSlate[\s]?7C', - // http://www.pocketbook-int.com/ru/support - 'PocketBookTablet' => 'Pocketbook', - // http://www.kocaso.com/product_tablet.html - 'KocasoTablet' => '\b(TB-1207)\b', - // http://global.hisense.com/product/asia/tablet/Sero7/201412/t20141215_91832.htm - 'HisenseTablet' => '\b(F5281|E2371)\b', - // http://www.tesco.com/direct/hudl/ - 'Hudl' => 'Hudl HT7S3|Hudl 2', - // http://www.telstra.com.au/home-phone/thub-2/ - 'TelstraTablet' => 'T-Hub2', - 'GenericTablet' => 'Android.*\b97D\b|Tablet(?!.*PC)|BNTV250A|MID-WCDMA|LogicPD Zoom2|\bA7EB\b|CatNova8|A1_07|CT704|CT1002|\bM721\b|rk30sdk|\bEVOTAB\b|M758A|ET904|ALUMIUM10|Smartfren Tab|Endeavour 1010|Tablet-PC-4|Tagi Tab|\bM6pro\b|CT1020W|arc 10HD|\bTP750\b|\bQTAQZ3\b|WVT101|TM1088|KT107' - ); - - /** - * List of mobile Operating Systems. - * - * @var array - */ - protected static $operatingSystems = array( - 'AndroidOS' => 'Android', - 'BlackBerryOS' => 'blackberry|\bBB10\b|rim tablet os', - 'PalmOS' => 'PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino', - 'SymbianOS' => 'Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b', - // @reference: http://en.wikipedia.org/wiki/Windows_Mobile - 'WindowsMobileOS' => 'Windows CE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Windows Mobile|Windows Phone [0-9.]+|WCE;', - // @reference: http://en.wikipedia.org/wiki/Windows_Phone - // http://wifeng.cn/?r=blog&a=view&id=106 - // http://nicksnettravels.builttoroam.com/post/2011/01/10/Bogus-Windows-Phone-7-User-Agent-String.aspx - // http://msdn.microsoft.com/library/ms537503.aspx - // https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx - 'WindowsPhoneOS' => 'Windows Phone 10.0|Windows Phone 8.1|Windows Phone 8.0|Windows Phone OS|XBLWP7|ZuneWP7|Windows NT 6.[23]; ARM;', - 'iOS' => '\biPhone.*Mobile|\biPod|\biPad|AppleCoreMedia', - // https://en.wikipedia.org/wiki/IPadOS - 'iPadOS' => 'CPU OS 13', - // @reference https://en.m.wikipedia.org/wiki/Sailfish_OS - // https://sailfishos.org/ - 'SailfishOS' => 'Sailfish', - // http://en.wikipedia.org/wiki/MeeGo - // @todo: research MeeGo in UAs - 'MeeGoOS' => 'MeeGo', - // http://en.wikipedia.org/wiki/Maemo - // @todo: research Maemo in UAs - 'MaemoOS' => 'Maemo', - 'JavaOS' => 'J2ME/|\bMIDP\b|\bCLDC\b', // '|Java/' produces bug #135 - 'webOS' => 'webOS|hpwOS', - 'badaOS' => '\bBada\b', - 'BREWOS' => 'BREW', - ); - - /** - * List of mobile User Agents. - * - * IMPORTANT: This is a list of only mobile browsers. - * Mobile Detect 2.x supports only mobile browsers, - * it was never designed to detect all browsers. - * The change will come in 2017 in the 3.x release for PHP7. - * - * @var array - */ - protected static $browsers = array( - //'Vivaldi' => 'Vivaldi', - // @reference: https://developers.google.com/chrome/mobile/docs/user-agent - 'Chrome' => '\bCrMo\b|CriOS|Android.*Chrome/[.0-9]* (Mobile)?', - 'Dolfin' => '\bDolfin\b', - 'Opera' => 'Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR/[0-9.]+$|Coast/[0-9.]+', - 'Skyfire' => 'Skyfire', - // Added "Edge on iOS" https://github.com/serbanghita/Mobile-Detect/issues/764 - 'Edge' => '\bEdgiOS\b|Mobile Safari/[.0-9]* Edge', - 'IE' => 'IEMobile|MSIEMobile', // |Trident/[.0-9]+ - 'Firefox' => 'fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS', - 'Bolt' => 'bolt', - 'TeaShark' => 'teashark', - 'Blazer' => 'Blazer', - // @reference: http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3 - // Excluded "Edge on iOS" https://github.com/serbanghita/Mobile-Detect/issues/764 - 'Safari' => 'Version((?!\bEdgiOS\b).)*Mobile.*Safari|Safari.*Mobile|MobileSafari', - // http://en.wikipedia.org/wiki/Midori_(web_browser) - //'Midori' => 'midori', - //'Tizen' => 'Tizen', - 'WeChat' => '\bMicroMessenger\b', - 'UCBrowser' => 'UC.*Browser|UCWEB', - 'baiduboxapp' => 'baiduboxapp', - 'baidubrowser' => 'baidubrowser', - // https://github.com/serbanghita/Mobile-Detect/issues/7 - 'DiigoBrowser' => 'DiigoBrowser', - // http://www.puffinbrowser.com/index.php - // https://github.com/serbanghita/Mobile-Detect/issues/752 - // 'Puffin' => 'Puffin', - // http://mercury-browser.com/index.html - 'Mercury' => '\bMercury\b', - // http://en.wikipedia.org/wiki/Obigo_Browser - 'ObigoBrowser' => 'Obigo', - // http://en.wikipedia.org/wiki/NetFront - 'NetFront' => 'NF-Browser', - // @reference: http://en.wikipedia.org/wiki/Minimo - // http://en.wikipedia.org/wiki/Vision_Mobile_Browser - 'GenericBrowser' => 'NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger', - // @reference: https://en.wikipedia.org/wiki/Pale_Moon_(web_browser) - 'PaleMoon' => 'Android.*PaleMoon|Mobile.*PaleMoon', - ); - - /** - * Utilities. - * - * @var array - */ - protected static $utilities = array( - // Experimental. When a mobile device wants to switch to 'Desktop Mode'. - // http://scottcate.com/technology/windows-phone-8-ie10-desktop-or-mobile/ - // https://github.com/serbanghita/Mobile-Detect/issues/57#issuecomment-15024011 - // https://developers.facebook.com/docs/sharing/webmasters/crawler/ - 'Bot' => 'Googlebot|facebookexternalhit|Google-AMPHTML|s~amp-validator|AdsBot-Google|Google Keyword Suggestion|Facebot|YandexBot|YandexMobileBot|bingbot|ia_archiver|AhrefsBot|Ezooms|GSLFbot|WBSearchBot|Twitterbot|TweetmemeBot|Twikle|PaperLiBot|Wotbox|UnwindFetchor|Exabot|MJ12bot|YandexImages|TurnitinBot|Pingdom|contentkingapp|AspiegelBot', - 'MobileBot' => 'Googlebot-Mobile|AdsBot-Google-Mobile|YahooSeeker/M1A1-R2D2', - 'DesktopMode' => 'WPDesktop', - 'TV' => 'SonyDTV|HbbTV', // experimental - 'WebKit' => '(webkit)[ /]([\w.]+)', - // @todo: Include JXD consoles. - 'Console' => '\b(Nintendo|Nintendo WiiU|Nintendo 3DS|Nintendo Switch|PLAYSTATION|Xbox)\b', - 'Watch' => 'SM-V700', - ); - - /** - * All possible HTTP headers that represent the - * User-Agent string. - * - * @var array - */ - protected static $uaHttpHeaders = array( - // The default User-Agent string. - 'HTTP_USER_AGENT', - // Header can occur on devices using Opera Mini. - 'HTTP_X_OPERAMINI_PHONE_UA', - // Vodafone specific header: http://www.seoprinciple.com/mobile-web-community-still-angry-at-vodafone/24/ - 'HTTP_X_DEVICE_USER_AGENT', - 'HTTP_X_ORIGINAL_USER_AGENT', - 'HTTP_X_SKYFIRE_PHONE', - 'HTTP_X_BOLT_PHONE_UA', - 'HTTP_DEVICE_STOCK_UA', - 'HTTP_X_UCBROWSER_DEVICE_UA' - ); - - /** - * The individual segments that could exist in a User-Agent string. VER refers to the regular - * expression defined in the constant self::VER. - * - * @var array - */ - protected static $properties = array( - - // Build - 'Mobile' => 'Mobile/[VER]', - 'Build' => 'Build/[VER]', - 'Version' => 'Version/[VER]', - 'VendorID' => 'VendorID/[VER]', - - // Devices - 'iPad' => 'iPad.*CPU[a-z ]+[VER]', - 'iPhone' => 'iPhone.*CPU[a-z ]+[VER]', - 'iPod' => 'iPod.*CPU[a-z ]+[VER]', - //'BlackBerry' => array('BlackBerry[VER]', 'BlackBerry [VER];'), - 'Kindle' => 'Kindle/[VER]', - - // Browser - 'Chrome' => array('Chrome/[VER]', 'CriOS/[VER]', 'CrMo/[VER]'), - 'Coast' => array('Coast/[VER]'), - 'Dolfin' => 'Dolfin/[VER]', - // @reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox - 'Firefox' => array('Firefox/[VER]', 'FxiOS/[VER]'), - 'Fennec' => 'Fennec/[VER]', - // http://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx - // https://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx - 'Edge' => 'Edge/[VER]', - 'IE' => array('IEMobile/[VER];', 'IEMobile [VER]', 'MSIE [VER];', 'Trident/[0-9.]+;.*rv:[VER]'), - // http://en.wikipedia.org/wiki/NetFront - 'NetFront' => 'NetFront/[VER]', - 'NokiaBrowser' => 'NokiaBrowser/[VER]', - 'Opera' => array( ' OPR/[VER]', 'Opera Mini/[VER]', 'Version/[VER]' ), - 'Opera Mini' => 'Opera Mini/[VER]', - 'Opera Mobi' => 'Version/[VER]', - 'UCBrowser' => array( 'UCWEB[VER]', 'UC.*Browser/[VER]' ), - 'MQQBrowser' => 'MQQBrowser/[VER]', - 'MicroMessenger' => 'MicroMessenger/[VER]', - 'baiduboxapp' => 'baiduboxapp/[VER]', - 'baidubrowser' => 'baidubrowser/[VER]', - 'SamsungBrowser' => 'SamsungBrowser/[VER]', - 'Iron' => 'Iron/[VER]', - // @note: Safari 7534.48.3 is actually Version 5.1. - // @note: On BlackBerry the Version is overwriten by the OS. - 'Safari' => array( 'Version/[VER]', 'Safari/[VER]' ), - 'Skyfire' => 'Skyfire/[VER]', - 'Tizen' => 'Tizen/[VER]', - 'Webkit' => 'webkit[ /][VER]', - 'PaleMoon' => 'PaleMoon/[VER]', - 'SailfishBrowser' => 'SailfishBrowser/[VER]', - - // Engine - 'Gecko' => 'Gecko/[VER]', - 'Trident' => 'Trident/[VER]', - 'Presto' => 'Presto/[VER]', - 'Goanna' => 'Goanna/[VER]', - - // OS - 'iOS' => ' \bi?OS\b [VER][ ;]{1}', - 'Android' => 'Android [VER]', - 'Sailfish' => 'Sailfish [VER]', - 'BlackBerry' => array('BlackBerry[\w]+/[VER]', 'BlackBerry.*Version/[VER]', 'Version/[VER]'), - 'BREW' => 'BREW [VER]', - 'Java' => 'Java/[VER]', - // @reference: http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/08/29/introducing-the-ie9-on-windows-phone-mango-user-agent-string.aspx - // @reference: http://en.wikipedia.org/wiki/Windows_NT#Releases - 'Windows Phone OS' => array( 'Windows Phone OS [VER]', 'Windows Phone [VER]'), - 'Windows Phone' => 'Windows Phone [VER]', - 'Windows CE' => 'Windows CE/[VER]', - // http://social.msdn.microsoft.com/Forums/en-US/windowsdeveloperpreviewgeneral/thread/6be392da-4d2f-41b4-8354-8dcee20c85cd - 'Windows NT' => 'Windows NT [VER]', - 'Symbian' => array('SymbianOS/[VER]', 'Symbian/[VER]'), - 'webOS' => array('webOS/[VER]', 'hpwOS/[VER];'), - ); - - /** - * Construct an instance of this class. - * - * @param array $headers Specify the headers as injection. Should be PHP _SERVER flavored. - * If left empty, will use the global _SERVER['HTTP_*'] vars instead. - * @param string $userAgent Inject the User-Agent header. If null, will use HTTP_USER_AGENT - * from the $headers array instead. - */ - public function __construct( - array $headers = null, - $userAgent = null - ) { - $this->setHttpHeaders($headers); - $this->setUserAgent($userAgent); - } - - /** - * Get the current script version. - * This is useful for the demo.php file, - * so people can check on what version they are testing - * for mobile devices. - * - * @return string The version number in semantic version format. - */ - public static function getScriptVersion() - { - return self::VERSION; - } - - /** - * Set the HTTP Headers. Must be PHP-flavored. This method will reset existing headers. - * - * @param array $httpHeaders The headers to set. If null, then using PHP's _SERVER to extract - * the headers. The default null is left for backwards compatibility. - */ - public function setHttpHeaders($httpHeaders = null) - { - // use global _SERVER if $httpHeaders aren't defined - if (!is_array($httpHeaders) || !count($httpHeaders)) { - $httpHeaders = $_SERVER; - } - - // clear existing headers - $this->httpHeaders = array(); - - // Only save HTTP headers. In PHP land, that means only _SERVER vars that - // start with HTTP_. - foreach ($httpHeaders as $key => $value) { - if (substr($key, 0, 5) === 'HTTP_') { - $this->httpHeaders[$key] = $value; - } - } - - // In case we're dealing with CloudFront, we need to know. - $this->setCfHeaders($httpHeaders); - } - - /** - * Retrieves the HTTP headers. - * - * @return array - */ - public function getHttpHeaders() - { - return $this->httpHeaders; - } - - /** - * Retrieves a particular header. If it doesn't exist, no exception/error is caused. - * Simply null is returned. - * - * @param string $header The name of the header to retrieve. Can be HTTP compliant such as - * "User-Agent" or "X-Device-User-Agent" or can be php-esque with the - * all-caps, HTTP_ prefixed, underscore seperated awesomeness. - * - * @return string|null The value of the header. - */ - public function getHttpHeader($header) - { - // are we using PHP-flavored headers? - if (strpos($header, '_') === false) { - $header = str_replace('-', '_', $header); - $header = strtoupper($header); - } - - // test the alternate, too - $altHeader = 'HTTP_' . $header; - - //Test both the regular and the HTTP_ prefix - if (isset($this->httpHeaders[$header])) { - return $this->httpHeaders[$header]; - } elseif (isset($this->httpHeaders[$altHeader])) { - return $this->httpHeaders[$altHeader]; - } - - return null; - } - - public function getMobileHeaders() - { - return self::$mobileHeaders; - } - - /** - * Get all possible HTTP headers that - * can contain the User-Agent string. - * - * @return array List of HTTP headers. - */ - public function getUaHttpHeaders() - { - return self::$uaHttpHeaders; - } - - - /** - * Set CloudFront headers - * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-device - * - * @param array $cfHeaders List of HTTP headers - * - * @return boolean If there were CloudFront headers to be set - */ - public function setCfHeaders($cfHeaders = null) { - // use global _SERVER if $cfHeaders aren't defined - if (!is_array($cfHeaders) || !count($cfHeaders)) { - $cfHeaders = $_SERVER; - } - - // clear existing headers - $this->cloudfrontHeaders = array(); - - // Only save CLOUDFRONT headers. In PHP land, that means only _SERVER vars that - // start with cloudfront-. - $response = false; - foreach ($cfHeaders as $key => $value) { - if (substr(strtolower($key), 0, 16) === 'http_cloudfront_') { - $this->cloudfrontHeaders[strtoupper($key)] = $value; - $response = true; - } - } - - return $response; - } - - /** - * Retrieves the cloudfront headers. - * - * @return array - */ - public function getCfHeaders() - { - return $this->cloudfrontHeaders; - } - - /** - * @param string $userAgent - * @return string - */ - private function prepareUserAgent($userAgent) { - $userAgent = trim($userAgent); - $userAgent = substr($userAgent, 0, 500); - return $userAgent; - } - - /** - * Set the User-Agent to be used. - * - * @param string $userAgent The user agent string to set. - * - * @return string|null - */ - public function setUserAgent($userAgent = null) - { - // Invalidate cache due to #375 - $this->cache = array(); - - if (false === empty($userAgent)) { - return $this->userAgent = $this->prepareUserAgent($userAgent); - } else { - $this->userAgent = null; - foreach ($this->getUaHttpHeaders() as $altHeader) { - if (false === empty($this->httpHeaders[$altHeader])) { // @todo: should use getHttpHeader(), but it would be slow. (Serban) - $this->userAgent .= $this->httpHeaders[$altHeader] . " "; - } - } - - if (!empty($this->userAgent)) { - return $this->userAgent = $this->prepareUserAgent($this->userAgent); - } - } - - if (count($this->getCfHeaders()) > 0) { - return $this->userAgent = 'Amazon CloudFront'; - } - return $this->userAgent = null; - } - - /** - * Retrieve the User-Agent. - * - * @return string|null The user agent if it's set. - */ - public function getUserAgent() - { - return $this->userAgent; - } - - /** - * Set the detection type. Must be one of self::DETECTION_TYPE_MOBILE or - * self::DETECTION_TYPE_EXTENDED. Otherwise, nothing is set. - * - * @deprecated since version 2.6.9 - * - * @param string $type The type. Must be a self::DETECTION_TYPE_* constant. The default - * parameter is null which will default to self::DETECTION_TYPE_MOBILE. - */ - public function setDetectionType($type = null) - { - if ($type === null) { - $type = self::DETECTION_TYPE_MOBILE; - } - - if ($type !== self::DETECTION_TYPE_MOBILE && $type !== self::DETECTION_TYPE_EXTENDED) { - return; - } - - $this->detectionType = $type; - } - - public function getMatchingRegex() - { - return $this->matchingRegex; - } - - public function getMatchesArray() - { - return $this->matchesArray; - } - - /** - * Retrieve the list of known phone devices. - * - * @return array List of phone devices. - */ - public static function getPhoneDevices() - { - return self::$phoneDevices; - } - - /** - * Retrieve the list of known tablet devices. - * - * @return array List of tablet devices. - */ - public static function getTabletDevices() - { - return self::$tabletDevices; - } - - /** - * Alias for getBrowsers() method. - * - * @return array List of user agents. - */ - public static function getUserAgents() - { - return self::getBrowsers(); - } - - /** - * Retrieve the list of known browsers. Specifically, the user agents. - * - * @return array List of browsers / user agents. - */ - public static function getBrowsers() - { - return self::$browsers; - } - - /** - * Retrieve the list of known utilities. - * - * @return array List of utilities. - */ - public static function getUtilities() - { - return self::$utilities; - } - - /** - * Method gets the mobile detection rules. This method is used for the magic methods $detect->is*(). - * - * @deprecated since version 2.6.9 - * - * @return array All the rules (but not extended). - */ - public static function getMobileDetectionRules() - { - static $rules; - - if (!$rules) { - $rules = array_merge( - self::$phoneDevices, - self::$tabletDevices, - self::$operatingSystems, - self::$browsers - ); - } - - return $rules; - - } - - /** - * Method gets the mobile detection rules + utilities. - * The reason this is separate is because utilities rules - * don't necessary imply mobile. This method is used inside - * the new $detect->is('stuff') method. - * - * @deprecated since version 2.6.9 - * - * @return array All the rules + extended. - */ - public function getMobileDetectionRulesExtended() - { - static $rules; - - if (!$rules) { - // Merge all rules together. - $rules = array_merge( - self::$phoneDevices, - self::$tabletDevices, - self::$operatingSystems, - self::$browsers, - self::$utilities - ); - } - - return $rules; - } - - /** - * Retrieve the current set of rules. - * - * @deprecated since version 2.6.9 - * - * @return array - */ - public function getRules() - { - if ($this->detectionType == self::DETECTION_TYPE_EXTENDED) { - return self::getMobileDetectionRulesExtended(); - } else { - return self::getMobileDetectionRules(); - } - } - - /** - * Retrieve the list of mobile operating systems. - * - * @return array The list of mobile operating systems. - */ - public static function getOperatingSystems() - { - return self::$operatingSystems; - } - - /** - * Check the HTTP headers for signs of mobile. - * This is the fastest mobile check possible; it's used - * inside isMobile() method. - * - * @return bool - */ - public function checkHttpHeadersForMobile() - { - - foreach ($this->getMobileHeaders() as $mobileHeader => $matchType) { - if (isset($this->httpHeaders[$mobileHeader])) { - if (isset($matchType['matches']) && is_array($matchType['matches'])) { - foreach ($matchType['matches'] as $_match) { - if (strpos($this->httpHeaders[$mobileHeader], $_match) !== false) { - return true; - } - } - - return false; - } else { - return true; - } - } - } - - return false; - - } - - /** - * Magic overloading method. - * - * @method boolean is[...]() - * @param string $name - * @param array $arguments - * @return mixed - * @throws BadMethodCallException when the method doesn't exist and doesn't start with 'is' - */ - public function __call($name, $arguments) - { - // make sure the name starts with 'is', otherwise - if (substr($name, 0, 2) !== 'is') { - throw new BadMethodCallException("No such method exists: $name"); - } - - $this->setDetectionType(self::DETECTION_TYPE_MOBILE); - - $key = substr($name, 2); - - return $this->matchUAAgainstKey($key); - } - - /** - * Find a detection rule that matches the current User-agent. - * - * @param null $userAgent deprecated - * @return boolean - */ - protected function matchDetectionRulesAgainstUA($userAgent = null) - { - // Begin general search. - foreach ($this->getRules() as $_regex) { - if (empty($_regex)) { - continue; - } - - if ($this->match($_regex, $userAgent)) { - return true; - } - } - - return false; - } - - /** - * Search for a certain key in the rules array. - * If the key is found then try to match the corresponding - * regex against the User-Agent. - * - * @param string $key - * - * @return boolean - */ - protected function matchUAAgainstKey($key) - { - // Make the keys lowercase so we can match: isIphone(), isiPhone(), isiphone(), etc. - $key = strtolower($key); - if (false === isset($this->cache[$key])) { - - // change the keys to lower case - $_rules = array_change_key_case($this->getRules()); - - if (false === empty($_rules[$key])) { - $this->cache[$key] = $this->match($_rules[$key]); - } - - if (false === isset($this->cache[$key])) { - $this->cache[$key] = false; - } - } - - return $this->cache[$key]; - } - - /** - * Check if the device is mobile. - * Returns true if any type of mobile device detected, including special ones - * @param null $userAgent deprecated - * @param null $httpHeaders deprecated - * @return bool - */ - public function isMobile($userAgent = null, $httpHeaders = null) - { - - if ($httpHeaders) { - $this->setHttpHeaders($httpHeaders); - } - - if ($userAgent) { - $this->setUserAgent($userAgent); - } - - // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' - if ($this->getUserAgent() === 'Amazon CloudFront') { - $cfHeaders = $this->getCfHeaders(); - if(array_key_exists('HTTP_CLOUDFRONT_IS_MOBILE_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_MOBILE_VIEWER'] === 'true') { - return true; - } - } - - $this->setDetectionType(self::DETECTION_TYPE_MOBILE); - - if ($this->checkHttpHeadersForMobile()) { - return true; - } else { - return $this->matchDetectionRulesAgainstUA(); - } - - } - - /** - * Check if the device is a tablet. - * Return true if any type of tablet device is detected. - * - * @param string $userAgent deprecated - * @param array $httpHeaders deprecated - * @return bool - */ - public function isTablet($userAgent = null, $httpHeaders = null) - { - // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' - if ($this->getUserAgent() === 'Amazon CloudFront') { - $cfHeaders = $this->getCfHeaders(); - if(array_key_exists('HTTP_CLOUDFRONT_IS_TABLET_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_TABLET_VIEWER'] === 'true') { - return true; - } - } - - $this->setDetectionType(self::DETECTION_TYPE_MOBILE); - - foreach (self::$tabletDevices as $_regex) { - if ($this->match($_regex, $userAgent)) { - return true; - } - } - - return false; - } - - /** - * This method checks for a certain property in the - * userAgent. - * @todo: The httpHeaders part is not yet used. - * - * @param string $key - * @param string $userAgent deprecated - * @param string $httpHeaders deprecated - * @return bool|int|null - */ - public function is($key, $userAgent = null, $httpHeaders = null) - { - // Set the UA and HTTP headers only if needed (eg. batch mode). - if ($httpHeaders) { - $this->setHttpHeaders($httpHeaders); - } - - if ($userAgent) { - $this->setUserAgent($userAgent); - } - - $this->setDetectionType(self::DETECTION_TYPE_EXTENDED); - - return $this->matchUAAgainstKey($key); - } - - /** - * Some detection rules are relative (not standard), - * because of the diversity of devices, vendors and - * their conventions in representing the User-Agent or - * the HTTP headers. - * - * This method will be used to check custom regexes against - * the User-Agent string. - * - * @param $regex - * @param string $userAgent - * @return bool - * - * @todo: search in the HTTP headers too. - */ - public function match($regex, $userAgent = null) - { - $match = (bool) preg_match(sprintf('#%s#is', $regex), (false === empty($userAgent) ? $userAgent : $this->userAgent), $matches); - // If positive match is found, store the results for debug. - if ($match) { - $this->matchingRegex = $regex; - $this->matchesArray = $matches; - } - - return $match; - } - - /** - * Get the properties array. - * - * @return array - */ - public static function getProperties() - { - return self::$properties; - } - - /** - * Prepare the version number. - * - * @todo Remove the error supression from str_replace() call. - * - * @param string $ver The string version, like "2.6.21.2152"; - * - * @return float - */ - public function prepareVersionNo($ver) - { - $ver = str_replace(array('_', ' ', '/'), '.', $ver); - $arrVer = explode('.', $ver, 2); - - if (isset($arrVer[1])) { - $arrVer[1] = @str_replace('.', '', $arrVer[1]); // @todo: treat strings versions. - } - - return (float) implode('.', $arrVer); - } - - /** - * Check the version of the given property in the User-Agent. - * Will return a float number. (eg. 2_0 will return 2.0, 4.3.1 will return 4.31) - * - * @param string $propertyName The name of the property. See self::getProperties() array - * keys for all possible properties. - * @param string $type Either self::VERSION_TYPE_STRING to get a string value or - * self::VERSION_TYPE_FLOAT indicating a float value. This parameter - * is optional and defaults to self::VERSION_TYPE_STRING. Passing an - * invalid parameter will default to the this type as well. - * - * @return string|float The version of the property we are trying to extract. - */ - public function version($propertyName, $type = self::VERSION_TYPE_STRING) - { - if (empty($propertyName)) { - return false; - } - - // set the $type to the default if we don't recognize the type - if ($type !== self::VERSION_TYPE_STRING && $type !== self::VERSION_TYPE_FLOAT) { - $type = self::VERSION_TYPE_STRING; - } - - $properties = self::getProperties(); - - // Check if the property exists in the properties array. - if (true === isset($properties[$propertyName])) { - - // Prepare the pattern to be matched. - // Make sure we always deal with an array (string is converted). - $properties[$propertyName] = (array) $properties[$propertyName]; - - foreach ($properties[$propertyName] as $propertyMatchString) { - - $propertyPattern = str_replace('[VER]', self::VER, $propertyMatchString); - - // Identify and extract the version. - preg_match(sprintf('#%s#is', $propertyPattern), $this->userAgent, $match); - - if (false === empty($match[1])) { - $version = ($type == self::VERSION_TYPE_FLOAT ? $this->prepareVersionNo($match[1]) : $match[1]); - - return $version; - } - - } - - } - - return false; - } - - /** - * Retrieve the mobile grading, using self::MOBILE_GRADE_* constants. - * - * @return string One of the self::MOBILE_GRADE_* constants. - */ - public function mobileGrade() - { - $isMobile = $this->isMobile(); - - if ( - // Apple iOS 4-7.0 – Tested on the original iPad (4.3 / 5.0), iPad 2 (4.3 / 5.1 / 6.1), iPad 3 (5.1 / 6.0), iPad Mini (6.1), iPad Retina (7.0), iPhone 3GS (4.3), iPhone 4 (4.3 / 5.1), iPhone 4S (5.1 / 6.0), iPhone 5 (6.0), and iPhone 5S (7.0) - $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) >= 4.3 || - $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) >= 4.3 || - $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) >= 4.3 || - - // Android 2.1-2.3 - Tested on the HTC Incredible (2.2), original Droid (2.2), HTC Aria (2.1), Google Nexus S (2.3). Functional on 1.5 & 1.6 but performance may be sluggish, tested on Google G1 (1.5) - // Android 3.1 (Honeycomb) - Tested on the Samsung Galaxy Tab 10.1 and Motorola XOOM - // Android 4.0 (ICS) - Tested on a Galaxy Nexus. Note: transition performance can be poor on upgraded devices - // Android 4.1 (Jelly Bean) - Tested on a Galaxy Nexus and Galaxy 7 - ( $this->version('Android', self::VERSION_TYPE_FLOAT)>2.1 && $this->is('Webkit') ) || - - // Windows Phone 7.5-8 - Tested on the HTC Surround (7.5), HTC Trophy (7.5), LG-E900 (7.5), Nokia 800 (7.8), HTC Mazaa (7.8), Nokia Lumia 520 (8), Nokia Lumia 920 (8), HTC 8x (8) - $this->version('Windows Phone OS', self::VERSION_TYPE_FLOAT) >= 7.5 || - - // Tested on the Torch 9800 (6) and Style 9670 (6), BlackBerry® Torch 9810 (7), BlackBerry Z10 (10) - $this->is('BlackBerry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 6.0 || - // Blackberry Playbook (1.0-2.0) - Tested on PlayBook - $this->match('Playbook.*Tablet') || - - // Palm WebOS (1.4-3.0) - Tested on the Palm Pixi (1.4), Pre (1.4), Pre 2 (2.0), HP TouchPad (3.0) - ( $this->version('webOS', self::VERSION_TYPE_FLOAT) >= 1.4 && $this->match('Palm|Pre|Pixi') ) || - // Palm WebOS 3.0 - Tested on HP TouchPad - $this->match('hp.*TouchPad') || - - // Firefox Mobile 18 - Tested on Android 2.3 and 4.1 devices - ( $this->is('Firefox') && $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 18 ) || - - // Chrome for Android - Tested on Android 4.0, 4.1 device - ( $this->is('Chrome') && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 4.0 ) || - - // Skyfire 4.1 - Tested on Android 2.3 device - ( $this->is('Skyfire') && $this->version('Skyfire', self::VERSION_TYPE_FLOAT) >= 4.1 && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 ) || - - // Opera Mobile 11.5-12: Tested on Android 2.3 - ( $this->is('Opera') && $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11.5 && $this->is('AndroidOS') ) || - - // Meego 1.2 - Tested on Nokia 950 and N9 - $this->is('MeeGoOS') || - - // Sailfish OS - $this->is('SailfishOS') || - - // Tizen (pre-release) - Tested on early hardware - $this->is('Tizen') || - - // Samsung Bada 2.0 - Tested on a Samsung Wave 3, Dolphin browser - // @todo: more tests here! - $this->is('Dolfin') && $this->version('Bada', self::VERSION_TYPE_FLOAT) >= 2.0 || - - // UC Browser - Tested on Android 2.3 device - ( ($this->is('UC Browser') || $this->is('Dolfin')) && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 ) || - - // Kindle 3 and Fire - Tested on the built-in WebKit browser for each - ( $this->match('Kindle Fire') || - $this->is('Kindle') && $this->version('Kindle', self::VERSION_TYPE_FLOAT) >= 3.0 ) || - - // Nook Color 1.4.1 - Tested on original Nook Color, not Nook Tablet - $this->is('AndroidOS') && $this->is('NookTablet') || - - // Chrome Desktop 16-24 - Tested on OS X 10.7 and Windows 7 - $this->version('Chrome', self::VERSION_TYPE_FLOAT) >= 16 && !$isMobile || - - // Safari Desktop 5-6 - Tested on OS X 10.7 and Windows 7 - $this->version('Safari', self::VERSION_TYPE_FLOAT) >= 5.0 && !$isMobile || - - // Firefox Desktop 10-18 - Tested on OS X 10.7 and Windows 7 - $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 10.0 && !$isMobile || - - // Internet Explorer 7-9 - Tested on Windows XP, Vista and 7 - $this->version('IE', self::VERSION_TYPE_FLOAT) >= 7.0 && !$isMobile || - - // Opera Desktop 10-12 - Tested on OS X 10.7 and Windows 7 - $this->version('Opera', self::VERSION_TYPE_FLOAT) >= 10 && !$isMobile - ){ - return self::MOBILE_GRADE_A; - } - - if ( - $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT)<4.3 || - $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT)<4.3 || - $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT)<4.3 || - - // Blackberry 5.0: Tested on the Storm 2 9550, Bold 9770 - $this->is('Blackberry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 5 && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT)<6 || - - //Opera Mini (5.0-6.5) - Tested on iOS 3.2/4.3 and Android 2.3 - ($this->version('Opera Mini', self::VERSION_TYPE_FLOAT) >= 5.0 && $this->version('Opera Mini', self::VERSION_TYPE_FLOAT) <= 7.0 && - ($this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 || $this->is('iOS')) ) || - - // Nokia Symbian^3 - Tested on Nokia N8 (Symbian^3), C7 (Symbian^3), also works on N97 (Symbian^1) - $this->match('NokiaN8|NokiaC7|N97.*Series60|Symbian/3') || - - // @todo: report this (tested on Nokia N71) - $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11 && $this->is('SymbianOS') - ){ - return self::MOBILE_GRADE_B; - } - - if ( - // Blackberry 4.x - Tested on the Curve 8330 - $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) <= 5.0 || - // Windows Mobile - Tested on the HTC Leo (WinMo 5.2) - $this->match('MSIEMobile|Windows CE.*Mobile') || $this->version('Windows Mobile', self::VERSION_TYPE_FLOAT) <= 5.2 || - - // Tested on original iPhone (3.1), iPhone 3 (3.2) - $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) <= 3.2 || - $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) <= 3.2 || - $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) <= 3.2 || - - // Internet Explorer 7 and older - Tested on Windows XP - $this->version('IE', self::VERSION_TYPE_FLOAT) <= 7.0 && !$isMobile - ){ - return self::MOBILE_GRADE_C; - } - - // All older smartphone platforms and featurephones - Any device that doesn't support media queries - // will receive the basic, C grade experience. - return self::MOBILE_GRADE_C; - } -} + + * @author Nick Ilyin + * Original author: Victor Stanciu + * + * @version 2.8.37 + * + * Auto-generated isXXXX() magic methods. + * php -a examples/dump_magic_methods.php + * + * @method bool isiPhone() + * @method bool isBlackBerry() + * @method bool isPixel() + * @method bool isHTC() + * @method bool isNexus() + * @method bool isDell() + * @method bool isMotorola() + * @method bool isSamsung() + * @method bool isLG() + * @method bool isSony() + * @method bool isAsus() + * @method bool isXiaomi() + * @method bool isNokiaLumia() + * @method bool isMicromax() + * @method bool isPalm() + * @method bool isVertu() + * @method bool isPantech() + * @method bool isFly() + * @method bool isWiko() + * @method bool isiMobile() + * @method bool isSimValley() + * @method bool isWolfgang() + * @method bool isAlcatel() + * @method bool isNintendo() + * @method bool isAmoi() + * @method bool isINQ() + * @method bool isOnePlus() + * @method bool isGenericPhone() + * @method bool isiPad() + * @method bool isNexusTablet() + * @method bool isGoogleTablet() + * @method bool isSamsungTablet() + * @method bool isKindle() + * @method bool isSurfaceTablet() + * @method bool isHPTablet() + * @method bool isAsusTablet() + * @method bool isBlackBerryTablet() + * @method bool isHTCtablet() + * @method bool isMotorolaTablet() + * @method bool isNookTablet() + * @method bool isAcerTablet() + * @method bool isToshibaTablet() + * @method bool isLGTablet() + * @method bool isFujitsuTablet() + * @method bool isPrestigioTablet() + * @method bool isLenovoTablet() + * @method bool isDellTablet() + * @method bool isYarvikTablet() + * @method bool isMedionTablet() + * @method bool isArnovaTablet() + * @method bool isIntensoTablet() + * @method bool isIRUTablet() + * @method bool isMegafonTablet() + * @method bool isEbodaTablet() + * @method bool isAllViewTablet() + * @method bool isArchosTablet() + * @method bool isAinolTablet() + * @method bool isNokiaLumiaTablet() + * @method bool isSonyTablet() + * @method bool isPhilipsTablet() + * @method bool isCubeTablet() + * @method bool isCobyTablet() + * @method bool isMIDTablet() + * @method bool isMSITablet() + * @method bool isSMiTTablet() + * @method bool isRockChipTablet() + * @method bool isFlyTablet() + * @method bool isbqTablet() + * @method bool isHuaweiTablet() + * @method bool isNecTablet() + * @method bool isPantechTablet() + * @method bool isBronchoTablet() + * @method bool isVersusTablet() + * @method bool isZyncTablet() + * @method bool isPositivoTablet() + * @method bool isNabiTablet() + * @method bool isKoboTablet() + * @method bool isDanewTablet() + * @method bool isTexetTablet() + * @method bool isPlaystationTablet() + * @method bool isTrekstorTablet() + * @method bool isPyleAudioTablet() + * @method bool isAdvanTablet() + * @method bool isDanyTechTablet() + * @method bool isGalapadTablet() + * @method bool isMicromaxTablet() + * @method bool isKarbonnTablet() + * @method bool isAllFineTablet() + * @method bool isPROSCANTablet() + * @method bool isYONESTablet() + * @method bool isChangJiaTablet() + * @method bool isGUTablet() + * @method bool isPointOfViewTablet() + * @method bool isOvermaxTablet() + * @method bool isHCLTablet() + * @method bool isDPSTablet() + * @method bool isVistureTablet() + * @method bool isCrestaTablet() + * @method bool isMediatekTablet() + * @method bool isConcordeTablet() + * @method bool isGoCleverTablet() + * @method bool isModecomTablet() + * @method bool isVoninoTablet() + * @method bool isECSTablet() + * @method bool isStorexTablet() + * @method bool isVodafoneTablet() + * @method bool isEssentielBTablet() + * @method bool isRossMoorTablet() + * @method bool isiMobileTablet() + * @method bool isTolinoTablet() + * @method bool isAudioSonicTablet() + * @method bool isAMPETablet() + * @method bool isSkkTablet() + * @method bool isTecnoTablet() + * @method bool isJXDTablet() + * @method bool isiJoyTablet() + * @method bool isFX2Tablet() + * @method bool isXoroTablet() + * @method bool isViewsonicTablet() + * @method bool isVerizonTablet() + * @method bool isOdysTablet() + * @method bool isCaptivaTablet() + * @method bool isIconbitTablet() + * @method bool isTeclastTablet() + * @method bool isOndaTablet() + * @method bool isJaytechTablet() + * @method bool isBlaupunktTablet() + * @method bool isDigmaTablet() + * @method bool isEvolioTablet() + * @method bool isLavaTablet() + * @method bool isAocTablet() + * @method bool isMpmanTablet() + * @method bool isCelkonTablet() + * @method bool isWolderTablet() + * @method bool isMediacomTablet() + * @method bool isMiTablet() + * @method bool isNibiruTablet() + * @method bool isNexoTablet() + * @method bool isLeaderTablet() + * @method bool isUbislateTablet() + * @method bool isPocketBookTablet() + * @method bool isKocasoTablet() + * @method bool isHisenseTablet() + * @method bool isHudl() + * @method bool isTelstraTablet() + * @method bool isGenericTablet() + * @method bool isAndroidOS() + * @method bool isBlackBerryOS() + * @method bool isPalmOS() + * @method bool isSymbianOS() + * @method bool isWindowsMobileOS() + * @method bool isWindowsPhoneOS() + * @method bool isiOS() + * @method bool isiPadOS() + * @method bool isSailfishOS() + * @method bool isMeeGoOS() + * @method bool isMaemoOS() + * @method bool isJavaOS() + * @method bool iswebOS() + * @method bool isbadaOS() + * @method bool isBREWOS() + * @method bool isChrome() + * @method bool isDolfin() + * @method bool isOpera() + * @method bool isSkyfire() + * @method bool isEdge() + * @method bool isIE() + * @method bool isFirefox() + * @method bool isBolt() + * @method bool isTeaShark() + * @method bool isBlazer() + * @method bool isSafari() + * @method bool isWeChat() + * @method bool isUCBrowser() + * @method bool isbaiduboxapp() + * @method bool isbaidubrowser() + * @method bool isDiigoBrowser() + * @method bool isMercury() + * @method bool isObigoBrowser() + * @method bool isNetFront() + * @method bool isGenericBrowser() + * @method bool isPaleMoon() + * @method bool isBot() + * @method bool isMobileBot() + * @method bool isDesktopMode() + * @method bool isTV() + * @method bool isWebKit() + * @method bool isConsole() + * @method bool isWatch() + + */ +class Mobile_Detect +{ + /** + * Mobile detection type. + * + * @deprecated since version 2.6.9 + */ + public const DETECTION_TYPE_MOBILE = 'mobile'; + + /** + * Extended detection type. + * + * @deprecated since version 2.6.9 + */ + public const DETECTION_TYPE_EXTENDED = 'extended'; + + /** + * A frequently used regular expression to extract version #s. + * + * @deprecated since version 2.6.9 + */ + public const VER = '([\w._\+]+)'; + + /** + * Top-level device. + */ + public const MOBILE_GRADE_A = 'A'; + + /** + * Mid-level device. + */ + public const MOBILE_GRADE_B = 'B'; + + /** + * Low-level device. + */ + public const MOBILE_GRADE_C = 'C'; + + /** + * Stores the version number of the current release. + */ + public const VERSION = '2.8.37'; + + /** + * A type for the version() method indicating a string return value. + */ + public const VERSION_TYPE_STRING = 'text'; + + /** + * A type for the version() method indicating a float return value. + */ + public const VERSION_TYPE_FLOAT = 'float'; + + /** + * A cache for resolved matches + * @var array + */ + protected $cache = []; + + /** + * The User-Agent HTTP header is stored in here. + * @var string + */ + protected $userAgent = null; + + /** + * HTTP headers in the PHP-flavor. So HTTP_USER_AGENT and SERVER_SOFTWARE. + * @var array + */ + protected $httpHeaders = []; + + /** + * CloudFront headers. E.g. CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer & CloudFront-Is-Tablet-Viewer. + * @var array + */ + protected $cloudfrontHeaders = []; + + /** + * The matching Regex. + * This is good for debug. + * @var string + */ + protected $matchingRegex = null; + + /** + * The matches extracted from the regex expression. + * This is good for debug. + * + * @var string + */ + protected $matchesArray = null; + + /** + * The detection type, using self::DETECTION_TYPE_MOBILE or self::DETECTION_TYPE_EXTENDED. + * + * @deprecated since version 2.6.9 + * + * @var string + */ + protected $detectionType = self::DETECTION_TYPE_MOBILE; + + /** + * HTTP headers that trigger the 'isMobile' detection + * to be true. + * + * @var array + */ + protected static $mobileHeaders = [ + + 'HTTP_ACCEPT' => ['matches' => [ + // Opera Mini; @reference: http://dev.opera.com/articles/view/opera-binary-markup-language/ + 'application/x-obml2d', + // BlackBerry devices. + 'application/vnd.rim.html', + 'text/vnd.wap.wml', + 'application/vnd.wap.xhtml+xml', + ]], + 'HTTP_X_WAP_PROFILE' => null, + 'HTTP_X_WAP_CLIENTID' => null, + 'HTTP_WAP_CONNECTION' => null, + 'HTTP_PROFILE' => null, + // Reported by Opera on Nokia devices (eg. C3). + 'HTTP_X_OPERAMINI_PHONE_UA' => null, + 'HTTP_X_NOKIA_GATEWAY_ID' => null, + 'HTTP_X_ORANGE_ID' => null, + 'HTTP_X_VODAFONE_3GPDPCONTEXT' => null, + 'HTTP_X_HUAWEI_USERID' => null, + // Reported by Windows Smartphones. + 'HTTP_UA_OS' => null, + // Reported by Verizon, Vodafone proxy system. + 'HTTP_X_MOBILE_GATEWAY' => null, + // Seen this on HTC Sensation. SensationXE_Beats_Z715e. + 'HTTP_X_ATT_DEVICEID' => null, + // Seen this on a HTC. + 'HTTP_UA_CPU' => ['matches' => ['ARM']], + ]; + + /** + * List of mobile devices (phones). + * + * @var array + */ + protected static $phoneDevices = [ + 'iPhone' => '\biPhone\b|\biPod\b', // |\biTunes + 'BlackBerry' => 'BlackBerry|\bBB10\b|rim[0-9]+|\b(BBA100|BBB100|BBD100|BBE100|BBF100|STH100)\b-[0-9]+', + 'Pixel' => '; \bPixel\b', + 'HTC' => 'HTC|HTC.*(Sensation|Evo|Vision|Explorer|6800|8100|8900|A7272|S510e|C110e|Legend|Desire|T8282)|APX515CKT|Qtek9090|APA9292KT|HD_mini|Sensation.*Z710e|PG86100|Z715e|Desire.*(A8181|HD)|ADR6200|ADR6400L|ADR6425|001HT|Inspire 4G|Android.*\bEVO\b|T-Mobile G1|Z520m|Android [0-9.]+; Pixel', + 'Nexus' => 'Nexus One|Nexus S|Galaxy.*Nexus|Android.*Nexus.*Mobile|Nexus 4|Nexus 5|Nexus 5X|Nexus 6', + // @todo: Is 'Dell Streak' a tablet or a phone? ;) + 'Dell' => 'Dell[;]? (Streak|Aero|Venue|Venue Pro|Flash|Smoke|Mini 3iX)|XCD28|XCD35|\b001DL\b|\b101DL\b|\bGS01\b', + 'Motorola' => 'Motorola|DROIDX|DROID BIONIC|\bDroid\b.*Build|Android.*Xoom|HRI39|MOT-|A1260|A1680|A555|A853|A855|A953|A955|A956|Motorola.*ELECTRIFY|Motorola.*i1|i867|i940|MB200|MB300|MB501|MB502|MB508|MB511|MB520|MB525|MB526|MB611|MB612|MB632|MB810|MB855|MB860|MB861|MB865|MB870|ME501|ME502|ME511|ME525|ME600|ME632|ME722|ME811|ME860|ME863|ME865|MT620|MT710|MT716|MT720|MT810|MT870|MT917|Motorola.*TITANIUM|WX435|WX445|XT300|XT301|XT311|XT316|XT317|XT319|XT320|XT390|XT502|XT530|XT531|XT532|XT535|XT603|XT610|XT611|XT615|XT681|XT701|XT702|XT711|XT720|XT800|XT806|XT860|XT862|XT875|XT882|XT883|XT894|XT901|XT907|XT909|XT910|XT912|XT928|XT926|XT915|XT919|XT925|XT1021|\bMoto E\b|XT1068|XT1092|XT1052', + 'Samsung' => '\bSamsung\b|SM-G950F|SM-G955F|SM-G9250|GT-19300|SGH-I337|BGT-S5230|GT-B2100|GT-B2700|GT-B2710|GT-B3210|GT-B3310|GT-B3410|GT-B3730|GT-B3740|GT-B5510|GT-B5512|GT-B5722|GT-B6520|GT-B7300|GT-B7320|GT-B7330|GT-B7350|GT-B7510|GT-B7722|GT-B7800|GT-C3010|GT-C3011|GT-C3060|GT-C3200|GT-C3212|GT-C3212I|GT-C3262|GT-C3222|GT-C3300|GT-C3300K|GT-C3303|GT-C3303K|GT-C3310|GT-C3322|GT-C3330|GT-C3350|GT-C3500|GT-C3510|GT-C3530|GT-C3630|GT-C3780|GT-C5010|GT-C5212|GT-C6620|GT-C6625|GT-C6712|GT-E1050|GT-E1070|GT-E1075|GT-E1080|GT-E1081|GT-E1085|GT-E1087|GT-E1100|GT-E1107|GT-E1110|GT-E1120|GT-E1125|GT-E1130|GT-E1160|GT-E1170|GT-E1175|GT-E1180|GT-E1182|GT-E1200|GT-E1210|GT-E1225|GT-E1230|GT-E1390|GT-E2100|GT-E2120|GT-E2121|GT-E2152|GT-E2220|GT-E2222|GT-E2230|GT-E2232|GT-E2250|GT-E2370|GT-E2550|GT-E2652|GT-E3210|GT-E3213|GT-I5500|GT-I5503|GT-I5700|GT-I5800|GT-I5801|GT-I6410|GT-I6420|GT-I7110|GT-I7410|GT-I7500|GT-I8000|GT-I8150|GT-I8160|GT-I8190|GT-I8320|GT-I8330|GT-I8350|GT-I8530|GT-I8700|GT-I8703|GT-I8910|GT-I9000|GT-I9001|GT-I9003|GT-I9010|GT-I9020|GT-I9023|GT-I9070|GT-I9082|GT-I9100|GT-I9103|GT-I9220|GT-I9250|GT-I9300|GT-I9305|GT-I9500|GT-I9505|GT-M3510|GT-M5650|GT-M7500|GT-M7600|GT-M7603|GT-M8800|GT-M8910|GT-N7000|GT-S3110|GT-S3310|GT-S3350|GT-S3353|GT-S3370|GT-S3650|GT-S3653|GT-S3770|GT-S3850|GT-S5210|GT-S5220|GT-S5229|GT-S5230|GT-S5233|GT-S5250|GT-S5253|GT-S5260|GT-S5263|GT-S5270|GT-S5300|GT-S5330|GT-S5350|GT-S5360|GT-S5363|GT-S5369|GT-S5380|GT-S5380D|GT-S5560|GT-S5570|GT-S5600|GT-S5603|GT-S5610|GT-S5620|GT-S5660|GT-S5670|GT-S5690|GT-S5750|GT-S5780|GT-S5830|GT-S5839|GT-S6102|GT-S6500|GT-S7070|GT-S7200|GT-S7220|GT-S7230|GT-S7233|GT-S7250|GT-S7500|GT-S7530|GT-S7550|GT-S7562|GT-S7710|GT-S8000|GT-S8003|GT-S8500|GT-S8530|GT-S8600|SCH-A310|SCH-A530|SCH-A570|SCH-A610|SCH-A630|SCH-A650|SCH-A790|SCH-A795|SCH-A850|SCH-A870|SCH-A890|SCH-A930|SCH-A950|SCH-A970|SCH-A990|SCH-I100|SCH-I110|SCH-I400|SCH-I405|SCH-I500|SCH-I510|SCH-I515|SCH-I600|SCH-I730|SCH-I760|SCH-I770|SCH-I830|SCH-I910|SCH-I920|SCH-I959|SCH-LC11|SCH-N150|SCH-N300|SCH-R100|SCH-R300|SCH-R351|SCH-R400|SCH-R410|SCH-T300|SCH-U310|SCH-U320|SCH-U350|SCH-U360|SCH-U365|SCH-U370|SCH-U380|SCH-U410|SCH-U430|SCH-U450|SCH-U460|SCH-U470|SCH-U490|SCH-U540|SCH-U550|SCH-U620|SCH-U640|SCH-U650|SCH-U660|SCH-U700|SCH-U740|SCH-U750|SCH-U810|SCH-U820|SCH-U900|SCH-U940|SCH-U960|SCS-26UC|SGH-A107|SGH-A117|SGH-A127|SGH-A137|SGH-A157|SGH-A167|SGH-A177|SGH-A187|SGH-A197|SGH-A227|SGH-A237|SGH-A257|SGH-A437|SGH-A517|SGH-A597|SGH-A637|SGH-A657|SGH-A667|SGH-A687|SGH-A697|SGH-A707|SGH-A717|SGH-A727|SGH-A737|SGH-A747|SGH-A767|SGH-A777|SGH-A797|SGH-A817|SGH-A827|SGH-A837|SGH-A847|SGH-A867|SGH-A877|SGH-A887|SGH-A897|SGH-A927|SGH-B100|SGH-B130|SGH-B200|SGH-B220|SGH-C100|SGH-C110|SGH-C120|SGH-C130|SGH-C140|SGH-C160|SGH-C170|SGH-C180|SGH-C200|SGH-C207|SGH-C210|SGH-C225|SGH-C230|SGH-C417|SGH-C450|SGH-D307|SGH-D347|SGH-D357|SGH-D407|SGH-D415|SGH-D780|SGH-D807|SGH-D980|SGH-E105|SGH-E200|SGH-E315|SGH-E316|SGH-E317|SGH-E335|SGH-E590|SGH-E635|SGH-E715|SGH-E890|SGH-F300|SGH-F480|SGH-I200|SGH-I300|SGH-I320|SGH-I550|SGH-I577|SGH-I600|SGH-I607|SGH-I617|SGH-I627|SGH-I637|SGH-I677|SGH-I700|SGH-I717|SGH-I727|SGH-i747M|SGH-I777|SGH-I780|SGH-I827|SGH-I847|SGH-I857|SGH-I896|SGH-I897|SGH-I900|SGH-I907|SGH-I917|SGH-I927|SGH-I937|SGH-I997|SGH-J150|SGH-J200|SGH-L170|SGH-L700|SGH-M110|SGH-M150|SGH-M200|SGH-N105|SGH-N500|SGH-N600|SGH-N620|SGH-N625|SGH-N700|SGH-N710|SGH-P107|SGH-P207|SGH-P300|SGH-P310|SGH-P520|SGH-P735|SGH-P777|SGH-Q105|SGH-R210|SGH-R220|SGH-R225|SGH-S105|SGH-S307|SGH-T109|SGH-T119|SGH-T139|SGH-T209|SGH-T219|SGH-T229|SGH-T239|SGH-T249|SGH-T259|SGH-T309|SGH-T319|SGH-T329|SGH-T339|SGH-T349|SGH-T359|SGH-T369|SGH-T379|SGH-T409|SGH-T429|SGH-T439|SGH-T459|SGH-T469|SGH-T479|SGH-T499|SGH-T509|SGH-T519|SGH-T539|SGH-T559|SGH-T589|SGH-T609|SGH-T619|SGH-T629|SGH-T639|SGH-T659|SGH-T669|SGH-T679|SGH-T709|SGH-T719|SGH-T729|SGH-T739|SGH-T746|SGH-T749|SGH-T759|SGH-T769|SGH-T809|SGH-T819|SGH-T839|SGH-T919|SGH-T929|SGH-T939|SGH-T959|SGH-T989|SGH-U100|SGH-U200|SGH-U800|SGH-V205|SGH-V206|SGH-X100|SGH-X105|SGH-X120|SGH-X140|SGH-X426|SGH-X427|SGH-X475|SGH-X495|SGH-X497|SGH-X507|SGH-X600|SGH-X610|SGH-X620|SGH-X630|SGH-X700|SGH-X820|SGH-X890|SGH-Z130|SGH-Z150|SGH-Z170|SGH-ZX10|SGH-ZX20|SHW-M110|SPH-A120|SPH-A400|SPH-A420|SPH-A460|SPH-A500|SPH-A560|SPH-A600|SPH-A620|SPH-A660|SPH-A700|SPH-A740|SPH-A760|SPH-A790|SPH-A800|SPH-A820|SPH-A840|SPH-A880|SPH-A900|SPH-A940|SPH-A960|SPH-D600|SPH-D700|SPH-D710|SPH-D720|SPH-I300|SPH-I325|SPH-I330|SPH-I350|SPH-I500|SPH-I600|SPH-I700|SPH-L700|SPH-M100|SPH-M220|SPH-M240|SPH-M300|SPH-M305|SPH-M320|SPH-M330|SPH-M350|SPH-M360|SPH-M370|SPH-M380|SPH-M510|SPH-M540|SPH-M550|SPH-M560|SPH-M570|SPH-M580|SPH-M610|SPH-M620|SPH-M630|SPH-M800|SPH-M810|SPH-M850|SPH-M900|SPH-M910|SPH-M920|SPH-M930|SPH-N100|SPH-N200|SPH-N240|SPH-N300|SPH-N400|SPH-Z400|SWC-E100|SCH-i909|GT-N7100|GT-N7105|SCH-I535|SM-N900A|SGH-I317|SGH-T999L|GT-S5360B|GT-I8262|GT-S6802|GT-S6312|GT-S6310|GT-S5312|GT-S5310|GT-I9105|GT-I8510|GT-S6790N|SM-G7105|SM-N9005|GT-S5301|GT-I9295|GT-I9195|SM-C101|GT-S7392|GT-S7560|GT-B7610|GT-I5510|GT-S7582|GT-S7530E|GT-I8750|SM-G9006V|SM-G9008V|SM-G9009D|SM-G900A|SM-G900D|SM-G900F|SM-G900H|SM-G900I|SM-G900J|SM-G900K|SM-G900L|SM-G900M|SM-G900P|SM-G900R4|SM-G900S|SM-G900T|SM-G900V|SM-G900W8|SHV-E160K|SCH-P709|SCH-P729|SM-T2558|GT-I9205|SM-G9350|SM-J120F|SM-G920F|SM-G920V|SM-G930F|SM-N910C|SM-A310F|GT-I9190|SM-J500FN|SM-G903F|SM-J330F|SM-G610F|SM-G981B|SM-G892A|SM-A530F', + 'LG' => '\bLG\b;|LG[- ]?(C800|C900|E400|E610|E900|E-900|F160|F180K|F180L|F180S|730|855|L160|LS740|LS840|LS970|LU6200|MS690|MS695|MS770|MS840|MS870|MS910|P500|P700|P705|VM696|AS680|AS695|AX840|C729|E970|GS505|272|C395|E739BK|E960|L55C|L75C|LS696|LS860|P769BK|P350|P500|P509|P870|UN272|US730|VS840|VS950|LN272|LN510|LS670|LS855|LW690|MN270|MN510|P509|P769|P930|UN200|UN270|UN510|UN610|US670|US740|US760|UX265|UX840|VN271|VN530|VS660|VS700|VS740|VS750|VS910|VS920|VS930|VX9200|VX11000|AX840A|LW770|P506|P925|P999|E612|D955|D802|MS323|M257)|LM-G710', + 'Sony' => 'SonyST|SonyLT|SonyEricsson|SonyEricssonLT15iv|LT18i|E10i|LT28h|LT26w|SonyEricssonMT27i|C5303|C6902|C6903|C6906|C6943|D2533|SOV34|601SO|F8332', + 'Asus' => 'Asus.*Galaxy|PadFone.*Mobile', + 'Xiaomi' => '^(?!.*\bx11\b).*xiaomi.*$|POCOPHONE F1|MI 8|Redmi Note 9S|Redmi Note 5A Prime|N2G47H|M2001J2G|M2001J2I|M1805E10A|M2004J11G|M1902F1G|M2002J9G|M2004J19G|M2003J6A1G', + 'NokiaLumia' => 'Lumia [0-9]{3,4}', + // http://www.micromaxinfo.com/mobiles/smartphones + // Added because the codes might conflict with Acer Tablets. + 'Micromax' => 'Micromax.*\b(A210|A92|A88|A72|A111|A110Q|A115|A116|A110|A90S|A26|A51|A35|A54|A25|A27|A89|A68|A65|A57|A90)\b', + // @todo Complete the regex. + 'Palm' => 'PalmSource|Palm', // avantgo|blazer|elaine|hiptop|plucker|xiino ; + 'Vertu' => 'Vertu|Vertu.*Ltd|Vertu.*Ascent|Vertu.*Ayxta|Vertu.*Constellation(F|Quest)?|Vertu.*Monika|Vertu.*Signature', // Just for fun ;) + // http://www.pantech.co.kr/en/prod/prodList.do?gbrand=VEGA (PANTECH) + // Most of the VEGA devices are legacy. PANTECH seem to be newer devices based on Android. + 'Pantech' => 'PANTECH|IM-A850S|IM-A840S|IM-A830L|IM-A830K|IM-A830S|IM-A820L|IM-A810K|IM-A810S|IM-A800S|IM-T100K|IM-A725L|IM-A780L|IM-A775C|IM-A770K|IM-A760S|IM-A750K|IM-A740S|IM-A730S|IM-A720L|IM-A710K|IM-A690L|IM-A690S|IM-A650S|IM-A630K|IM-A600S|VEGA PTL21|PT003|P8010|ADR910L|P6030|P6020|P9070|P4100|P9060|P5000|CDM8992|TXT8045|ADR8995|IS11PT|P2030|P6010|P8000|PT002|IS06|CDM8999|P9050|PT001|TXT8040|P2020|P9020|P2000|P7040|P7000|C790', + // http://www.fly-phone.com/devices/smartphones/ ; Included only smartphones. + 'Fly' => 'IQ230|IQ444|IQ450|IQ440|IQ442|IQ441|IQ245|IQ256|IQ236|IQ255|IQ235|IQ245|IQ275|IQ240|IQ285|IQ280|IQ270|IQ260|IQ250', + // http://fr.wikomobile.com + 'Wiko' => 'KITE 4G|HIGHWAY|GETAWAY|STAIRWAY|DARKSIDE|DARKFULL|DARKNIGHT|DARKMOON|SLIDE|WAX 4G|RAINBOW|BLOOM|SUNSET|GOA(?!nna)|LENNY|BARRY|IGGY|OZZY|CINK FIVE|CINK PEAX|CINK PEAX 2|CINK SLIM|CINK SLIM 2|CINK +|CINK KING|CINK PEAX|CINK SLIM|SUBLIM', + 'iMobile' => 'i-mobile (IQ|i-STYLE|idea|ZAA|Hitz)', + // Added simvalley mobile just for fun. They have some interesting devices. + // http://www.simvalley.fr/telephonie---gps-_22_telephonie-mobile_telephones_.html + 'SimValley' => '\b(SP-80|XT-930|SX-340|XT-930|SX-310|SP-360|SP60|SPT-800|SP-120|SPT-800|SP-140|SPX-5|SPX-8|SP-100|SPX-8|SPX-12)\b', + // Wolfgang - a brand that is sold by Aldi supermarkets. + // http://www.wolfgangmobile.com/ + 'Wolfgang' => 'AT-B24D|AT-AS50HD|AT-AS40W|AT-AS55HD|AT-AS45q2|AT-B26D|AT-AS50Q', + 'Alcatel' => 'Alcatel', + 'Nintendo' => 'Nintendo (3DS|Switch)', + // http://en.wikipedia.org/wiki/Amoi + 'Amoi' => 'Amoi', + // http://en.wikipedia.org/wiki/INQ + 'INQ' => 'INQ', + 'OnePlus' => 'ONEPLUS', + // @Tapatalk is a mobile app; http://support.tapatalk.com/threads/smf-2-0-2-os-and-browser-detection-plugin-and-tapatalk.15565/#post-79039 + 'GenericPhone' => 'Tapatalk|PDA;|SAGEM|\bmmp\b|pocket|\bpsp\b|symbian|Smartphone|smartfon|treo|up.browser|up.link|vodafone|\bwap\b|nokia|Series40|Series60|S60|SonyEricsson|N900|MAUI.*WAP.*Browser', + ]; + + /** + * List of tablet devices. + * + * @var array + */ + protected static $tabletDevices = [ + // @todo: check for mobile friendly emails topic. + 'iPad' => 'iPad|iPad.*Mobile', + // Removed |^.*Android.*Nexus(?!(?:Mobile).)*$ + // @see #442 + // @todo Merge NexusTablet into GoogleTablet. + 'NexusTablet' => 'Android.*Nexus[\s]+(7|9|10)', + // https://en.wikipedia.org/wiki/Pixel_C + 'GoogleTablet' => 'Android.*Pixel C', + 'SamsungTablet' => 'SAMSUNG.*Tablet|Galaxy.*Tab|SC-01C|GT-P1000|GT-P1003|GT-P1010|GT-P3105|GT-P6210|GT-P6800|GT-P6810|GT-P7100|GT-P7300|GT-P7310|GT-P7500|GT-P7510|SCH-I800|SCH-I815|SCH-I905|SGH-I957|SGH-I987|SGH-T849|SGH-T859|SGH-T869|SPH-P100|GT-P3100|GT-P3108|GT-P3110|GT-P5100|GT-P5110|GT-P6200|GT-P7320|GT-P7511|GT-N8000|GT-P8510|SGH-I497|SPH-P500|SGH-T779|SCH-I705|SCH-I915|GT-N8013|GT-P3113|GT-P5113|GT-P8110|GT-N8010|GT-N8005|GT-N8020|GT-P1013|GT-P6201|GT-P7501|GT-N5100|GT-N5105|GT-N5110|SHV-E140K|SHV-E140L|SHV-E140S|SHV-E150S|SHV-E230K|SHV-E230L|SHV-E230S|SHW-M180K|SHW-M180L|SHW-M180S|SHW-M180W|SHW-M300W|SHW-M305W|SHW-M380K|SHW-M380S|SHW-M380W|SHW-M430W|SHW-M480K|SHW-M480S|SHW-M480W|SHW-M485W|SHW-M486W|SHW-M500W|GT-I9228|SCH-P739|SCH-I925|GT-I9200|GT-P5200|GT-P5210|GT-P5210X|SM-T311|SM-T310|SM-T310X|SM-T210|SM-T210R|SM-T211|SM-P600|SM-P601|SM-P605|SM-P900|SM-P901|SM-T217|SM-T217A|SM-T217S|SM-P6000|SM-T3100|SGH-I467|XE500|SM-T110|GT-P5220|GT-I9200X|GT-N5110X|GT-N5120|SM-P905|SM-T111|SM-T2105|SM-T315|SM-T320|SM-T320X|SM-T321|SM-T520|SM-T525|SM-T530NU|SM-T230NU|SM-T330NU|SM-T900|XE500T1C|SM-P605V|SM-P905V|SM-T337V|SM-T537V|SM-T707V|SM-T807V|SM-P600X|SM-P900X|SM-T210X|SM-T230|SM-T230X|SM-T325|GT-P7503|SM-T531|SM-T330|SM-T530|SM-T705|SM-T705C|SM-T535|SM-T331|SM-T800|SM-T700|SM-T537|SM-T807|SM-P907A|SM-T337A|SM-T537A|SM-T707A|SM-T807A|SM-T237|SM-T807P|SM-P607T|SM-T217T|SM-T337T|SM-T807T|SM-T116NQ|SM-T116BU|SM-P550|SM-T350|SM-T550|SM-T9000|SM-P9000|SM-T705Y|SM-T805|GT-P3113|SM-T710|SM-T810|SM-T815|SM-T360|SM-T533|SM-T113|SM-T335|SM-T715|SM-T560|SM-T670|SM-T677|SM-T377|SM-T567|SM-T357T|SM-T555|SM-T561|SM-T713|SM-T719|SM-T813|SM-T819|SM-T580|SM-T355Y?|SM-T280|SM-T817A|SM-T820|SM-W700|SM-P580|SM-T587|SM-P350|SM-P555M|SM-P355M|SM-T113NU|SM-T815Y|SM-T585|SM-T285|SM-T825|SM-W708|SM-T835|SM-T830|SM-T837V|SM-T720|SM-T510|SM-T387V|SM-P610|SM-T290|SM-T515|SM-T590|SM-T595|SM-T725|SM-T817P|SM-P585N0|SM-T395|SM-T295|SM-T865|SM-P610N|SM-P615|SM-T970|SM-T380|SM-T5950|SM-T905|SM-T231|SM-T500|SM-T860', // SCH-P709|SCH-P729|SM-T2558|GT-I9205 - Samsung Mega - treat them like a regular phone. + // http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html + 'Kindle' => 'Kindle|Silk.*Accelerated|Android.*\b(KFOT|KFTT|KFJWI|KFJWA|KFOTE|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|WFJWAE|KFSAWA|KFSAWI|KFASWI|KFARWI|KFFOWI|KFGIWI|KFMEWI)\b|Android.*Silk/[0-9.]+ like Chrome/[0-9.]+ (?!Mobile)', + // Only the Surface tablets with Windows RT are considered mobile. + // http://msdn.microsoft.com/en-us/library/ie/hh920767(v=vs.85).aspx + 'SurfaceTablet' => 'Windows NT [0-9.]+; ARM;.*(Tablet|ARMBJS)', + // http://shopping1.hp.com/is-bin/INTERSHOP.enfinity/WFS/WW-USSMBPublicStore-Site/en_US/-/USD/ViewStandardCatalog-Browse?CatalogCategoryID=JfIQ7EN5lqMAAAEyDcJUDwMT + 'HPTablet' => 'HP Slate (7|8|10)|HP ElitePad 900|hp-tablet|EliteBook.*Touch|HP 8|Slate 21|HP SlateBook 10', + // Watch out for PadFone, see #132. + // http://www.asus.com/de/Tablets_Mobile/Memo_Pad_Products/ + 'AsusTablet' => '^.*PadFone((?!Mobile).)*$|Transformer|TF101|TF101G|TF300T|TF300TG|TF300TL|TF700T|TF700KL|TF701T|TF810C|ME171|ME301T|ME302C|ME371MG|ME370T|ME372MG|ME172V|ME173X|ME400C|Slider SL101|\bK00F\b|\bK00C\b|\bK00E\b|\bK00L\b|TX201LA|ME176C|ME102A|\bM80TA\b|ME372CL|ME560CG|ME372CG|ME302KL| K010 | K011 | K017 | K01E |ME572C|ME103K|ME170C|ME171C|\bME70C\b|ME581C|ME581CL|ME8510C|ME181C|P01Y|PO1MA|P01Z|\bP027\b|\bP024\b|\bP00C\b', + 'BlackBerryTablet' => 'PlayBook|RIM Tablet', + 'HTCtablet' => 'HTC_Flyer_P512|HTC Flyer|HTC Jetstream|HTC-P715a|HTC EVO View 4G|PG41200|PG09410', + 'MotorolaTablet' => 'xoom|sholest|MZ615|MZ605|MZ505|MZ601|MZ602|MZ603|MZ604|MZ606|MZ607|MZ608|MZ609|MZ615|MZ616|MZ617', + 'NookTablet' => 'Android.*Nook|NookColor|nook browser|BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2', + // http://www.acer.ro/ac/ro/RO/content/drivers + // http://www.packardbell.co.uk/pb/en/GB/content/download (Packard Bell is part of Acer) + // http://us.acer.com/ac/en/US/content/group/tablets + // http://www.acer.de/ac/de/DE/content/models/tablets/ + // Can conflict with Micromax and Motorola phones codes. + 'AcerTablet' => 'Android.*; \b(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700|A701|W500|W500P|W501|W501P|W510|W511|W700|G100|G100W|B1-A71|B1-710|B1-711|A1-810|A1-811|A1-830)\b|W3-810|\bA3-A10\b|\bA3-A11\b|\bA3-A20\b|\bA3-A30|A3-A40', + // http://eu.computers.toshiba-europe.com/innovation/family/Tablets/1098744/banner_id/tablet_footerlink/ + // http://us.toshiba.com/tablets/tablet-finder + // http://www.toshiba.co.jp/regza/tablet/ + 'ToshibaTablet' => 'Android.*(AT100|AT105|AT200|AT205|AT270|AT275|AT300|AT305|AT1S5|AT500|AT570|AT700|AT830)|TOSHIBA.*FOLIO', + // http://www.nttdocomo.co.jp/english/service/developer/smart_phone/technical_info/spec/index.html + // http://www.lg.com/us/tablets + 'LGTablet' => '\bL-06C|LG-V909|LG-V900|LG-V700|LG-V510|LG-V500|LG-V410|LG-V400|LG-VK810\b', + 'FujitsuTablet' => 'Android.*\b(F-01D|F-02F|F-05E|F-10D|M532|Q572)\b', + // Prestigio Tablets http://www.prestigio.com/support + 'PrestigioTablet' => 'PMP3170B|PMP3270B|PMP3470B|PMP7170B|PMP3370B|PMP3570C|PMP5870C|PMP3670B|PMP5570C|PMP5770D|PMP3970B|PMP3870C|PMP5580C|PMP5880D|PMP5780D|PMP5588C|PMP7280C|PMP7280C3G|PMP7280|PMP7880D|PMP5597D|PMP5597|PMP7100D|PER3464|PER3274|PER3574|PER3884|PER5274|PER5474|PMP5097CPRO|PMP5097|PMP7380D|PMP5297C|PMP5297C_QUAD|PMP812E|PMP812E3G|PMP812F|PMP810E|PMP880TD|PMT3017|PMT3037|PMT3047|PMT3057|PMT7008|PMT5887|PMT5001|PMT5002', + // http://support.lenovo.com/en_GB/downloads/default.page?# + 'LenovoTablet' => 'Lenovo TAB|Idea(Tab|Pad)( A1|A10| K1|)|ThinkPad([ ]+)?Tablet|YT3-850M|YT3-X90L|YT3-X90F|YT3-X90X|Lenovo.*(S2109|S2110|S5000|S6000|K3011|A3000|A3500|A1000|A2107|A2109|A1107|A5500|A7600|B6000|B8000|B8080)(-|)(FL|F|HV|H|)|TB-X103F|TB-X304X|TB-X304F|TB-X304L|TB-X505F|TB-X505L|TB-X505X|TB-X605F|TB-X605L|TB-8703F|TB-8703X|TB-8703N|TB-8704N|TB-8704F|TB-8704X|TB-8704V|TB-7304F|TB-7304I|TB-7304X|Tab2A7-10F|Tab2A7-20F|TB2-X30L|YT3-X50L|YT3-X50F|YT3-X50M|YT-X705F|YT-X703F|YT-X703L|YT-X705L|YT-X705X|TB2-X30F|TB2-X30L|TB2-X30M|A2107A-F|A2107A-H|TB3-730F|TB3-730M|TB3-730X|TB-7504F|TB-7504X|TB-X704F|TB-X104F|TB3-X70F|TB-X705F|TB-8504F|TB3-X70L|TB3-710F|TB-X704L', + // http://www.dell.com/support/home/us/en/04/Products/tab_mob/tablets + 'DellTablet' => 'Venue 11|Venue 8|Venue 7|Dell Streak 10|Dell Streak 7', + // http://www.yarvik.com/en/matrix/tablets/ + 'YarvikTablet' => 'Android.*\b(TAB210|TAB211|TAB224|TAB250|TAB260|TAB264|TAB310|TAB360|TAB364|TAB410|TAB411|TAB420|TAB424|TAB450|TAB460|TAB461|TAB464|TAB465|TAB467|TAB468|TAB07-100|TAB07-101|TAB07-150|TAB07-151|TAB07-152|TAB07-200|TAB07-201-3G|TAB07-210|TAB07-211|TAB07-212|TAB07-214|TAB07-220|TAB07-400|TAB07-485|TAB08-150|TAB08-200|TAB08-201-3G|TAB08-201-30|TAB09-100|TAB09-211|TAB09-410|TAB10-150|TAB10-201|TAB10-211|TAB10-400|TAB10-410|TAB13-201|TAB274EUK|TAB275EUK|TAB374EUK|TAB462EUK|TAB474EUK|TAB9-200)\b', + 'MedionTablet' => 'Android.*\bOYO\b|LIFE.*(P9212|P9514|P9516|S9512)|LIFETAB', + 'ArnovaTablet' => '97G4|AN10G2|AN7bG3|AN7fG3|AN8G3|AN8cG3|AN7G3|AN9G3|AN7dG3|AN7dG3ST|AN7dG3ChildPad|AN10bG3|AN10bG3DT|AN9G2', + // http://www.intenso.de/kategorie_en.php?kategorie=33 + // @todo: http://www.nbhkdz.com/read/b8e64202f92a2df129126bff.html - investigate + 'IntensoTablet' => 'INM8002KP|INM1010FP|INM805ND|Intenso Tab|TAB1004', + // IRU.ru Tablets http://www.iru.ru/catalog/soho/planetable/ + 'IRUTablet' => 'M702pro', + 'MegafonTablet' => 'MegaFon V9|\bZTE V9\b|Android.*\bMT7A\b', + // http://www.e-boda.ro/tablete-pc.html + 'EbodaTablet' => 'E-Boda (Supreme|Impresspeed|Izzycomm|Essential)', + // http://www.allview.ro/produse/droseries/lista-tablete-pc/ + 'AllViewTablet' => 'Allview.*(Viva|Alldro|City|Speed|All TV|Frenzy|Quasar|Shine|TX1|AX1|AX2)', + // http://wiki.archosfans.com/index.php?title=Main_Page + // @note Rewrite the regex format after we add more UAs. + 'ArchosTablet' => '\b(101G9|80G9|A101IT)\b|Qilive 97R|Archos5|\bARCHOS (70|79|80|90|97|101|FAMILYPAD|)(b|c|)(G10| Cobalt| TITANIUM(HD|)| Xenon| Neon|XSK| 2| XS 2| PLATINUM| CARBON|GAMEPAD)\b', + // http://www.ainol.com/plugin.php?identifier=ainol&module=product + 'AinolTablet' => 'NOVO7|NOVO8|NOVO10|Novo7Aurora|Novo7Basic|NOVO7PALADIN|novo9-Spark', + 'NokiaLumiaTablet' => 'Lumia 2520', + // @todo: inspect http://esupport.sony.com/US/p/select-system.pl?DIRECTOR=DRIVER + // Readers http://www.atsuhiro-me.net/ebook/sony-reader/sony-reader-web-browser + // http://www.sony.jp/support/tablet/ + 'SonyTablet' => 'Sony.*Tablet|Xperia Tablet|Sony Tablet S|SO-03E|SGPT12|SGPT13|SGPT114|SGPT121|SGPT122|SGPT123|SGPT111|SGPT112|SGPT113|SGPT131|SGPT132|SGPT133|SGPT211|SGPT212|SGPT213|SGP311|SGP312|SGP321|EBRD1101|EBRD1102|EBRD1201|SGP351|SGP341|SGP511|SGP512|SGP521|SGP541|SGP551|SGP621|SGP641|SGP612|SOT31|SGP771|SGP611|SGP612|SGP712', + // http://www.support.philips.com/support/catalog/worldproducts.jsp?userLanguage=en&userCountry=cn&categoryid=3G_LTE_TABLET_SU_CN_CARE&title=3G%20tablets%20/%20LTE%20range&_dyncharset=UTF-8 + 'PhilipsTablet' => '\b(PI2010|PI3000|PI3100|PI3105|PI3110|PI3205|PI3210|PI3900|PI4010|PI7000|PI7100)\b', + // db + http://www.cube-tablet.com/buy-products.html + 'CubeTablet' => 'Android.*(K8GT|U9GT|U10GT|U16GT|U17GT|U18GT|U19GT|U20GT|U23GT|U30GT)|CUBE U8GT', + // http://www.cobyusa.com/?p=pcat&pcat_id=3001 + 'CobyTablet' => 'MID1042|MID1045|MID1125|MID1126|MID7012|MID7014|MID7015|MID7034|MID7035|MID7036|MID7042|MID7048|MID7127|MID8042|MID8048|MID8127|MID9042|MID9740|MID9742|MID7022|MID7010', + // http://www.match.net.cn/products.asp + 'MIDTablet' => 'M9701|M9000|M9100|M806|M1052|M806|T703|MID701|MID713|MID710|MID727|MID760|MID830|MID728|MID933|MID125|MID810|MID732|MID120|MID930|MID800|MID731|MID900|MID100|MID820|MID735|MID980|MID130|MID833|MID737|MID960|MID135|MID860|MID736|MID140|MID930|MID835|MID733|MID4X10', + // http://www.msi.com/support + // @todo Research the Windows Tablets. + 'MSITablet' => 'MSI \b(Primo 73K|Primo 73L|Primo 81L|Primo 77|Primo 93|Primo 75|Primo 76|Primo 73|Primo 81|Primo 91|Primo 90|Enjoy 71|Enjoy 7|Enjoy 10)\b', + // @todo http://www.kyoceramobile.com/support/drivers/ + // 'KyoceraTablet' => null, + // @todo http://intexuae.com/index.php/category/mobile-devices/tablets-products/ + // 'IntextTablet' => null, + // http://pdadb.net/index.php?m=pdalist&list=SMiT (NoName Chinese Tablets) + // http://www.imp3.net/14/show.php?itemid=20454 + 'SMiTTablet' => 'Android.*(\bMID\b|MID-560|MTV-T1200|MTV-PND531|MTV-P1101|MTV-PND530)', + // http://www.rock-chips.com/index.php?do=prod&pid=2 + 'RockChipTablet' => 'Android.*(RK2818|RK2808A|RK2918|RK3066)|RK2738|RK2808A', + // http://www.fly-phone.com/devices/tablets/ ; http://www.fly-phone.com/service/ + 'FlyTablet' => 'IQ310|Fly Vision', + // http://www.bqreaders.com/gb/tablets-prices-sale.html + 'bqTablet' => 'Android.*(bq)?.*\b(Elcano|Curie|Edison|Maxwell|Kepler|Pascal|Tesla|Hypatia|Platon|Newton|Livingstone|Cervantes|Avant|Aquaris ([E|M]10|M8))\b|Maxwell.*Lite|Maxwell.*Plus', + // http://www.huaweidevice.com/worldwide/productFamily.do?method=index&directoryId=5011&treeId=3290 + // http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index&directoryId=3372&treeId=0&tb=1&type=software (including legacy tablets) + 'HuaweiTablet' => 'MediaPad|MediaPad 7 Youth|IDEOS S7|S7-201c|S7-202u|S7-101|S7-103|S7-104|S7-105|S7-106|S7-201|S7-Slim|M2-A01L|BAH-L09|BAH-W09|AGS-L09|CMR-AL19', + // Nec or Medias Tab + 'NecTablet' => '\bN-06D|\bN-08D', + // Pantech Tablets: http://www.pantechusa.com/phones/ + 'PantechTablet' => 'Pantech.*P4100', + // Broncho Tablets: http://www.broncho.cn/ (hard to find) + 'BronchoTablet' => 'Broncho.*(N701|N708|N802|a710)', + // http://versusuk.com/support.html + 'VersusTablet' => 'TOUCHPAD.*[78910]|\bTOUCHTAB\b', + // http://www.zync.in/index.php/our-products/tablet-phablets + 'ZyncTablet' => 'z1000|Z99 2G|z930|z990|z909|Z919|z900', // Removed "z999" because of https://github.com/serbanghita/Mobile-Detect/issues/717 + // http://www.positivoinformatica.com.br/www/pessoal/tablet-ypy/ + 'PositivoTablet' => 'TB07STA|TB10STA|TB07FTA|TB10FTA', + // https://www.nabitablet.com/ + 'NabiTablet' => 'Android.*\bNabi', + 'KoboTablet' => 'Kobo Touch|\bK080\b|\bVox\b Build|\bArc\b Build', + // French Danew Tablets http://www.danew.com/produits-tablette.php + 'DanewTablet' => 'DSlide.*\b(700|701R|702|703R|704|802|970|971|972|973|974|1010|1012)\b', + // Texet Tablets and Readers http://www.texet.ru/tablet/ + 'TexetTablet' => 'NaviPad|TB-772A|TM-7045|TM-7055|TM-9750|TM-7016|TM-7024|TM-7026|TM-7041|TM-7043|TM-7047|TM-8041|TM-9741|TM-9747|TM-9748|TM-9751|TM-7022|TM-7021|TM-7020|TM-7011|TM-7010|TM-7023|TM-7025|TM-7037W|TM-7038W|TM-7027W|TM-9720|TM-9725|TM-9737W|TM-1020|TM-9738W|TM-9740|TM-9743W|TB-807A|TB-771A|TB-727A|TB-725A|TB-719A|TB-823A|TB-805A|TB-723A|TB-715A|TB-707A|TB-705A|TB-709A|TB-711A|TB-890HD|TB-880HD|TB-790HD|TB-780HD|TB-770HD|TB-721HD|TB-710HD|TB-434HD|TB-860HD|TB-840HD|TB-760HD|TB-750HD|TB-740HD|TB-730HD|TB-722HD|TB-720HD|TB-700HD|TB-500HD|TB-470HD|TB-431HD|TB-430HD|TB-506|TB-504|TB-446|TB-436|TB-416|TB-146SE|TB-126SE', + // Avoid detecting 'PLAYSTATION 3' as mobile. + 'PlaystationTablet' => 'Playstation.*(Portable|Vita)', + // http://www.trekstor.de/surftabs.html + 'TrekstorTablet' => 'ST10416-1|VT10416-1|ST70408-1|ST702xx-1|ST702xx-2|ST80208|ST97216|ST70104-2|VT10416-2|ST10216-2A|SurfTab', + // http://www.pyleaudio.com/Products.aspx?%2fproducts%2fPersonal-Electronics%2fTablets + 'PyleAudioTablet' => '\b(PTBL10CEU|PTBL10C|PTBL72BC|PTBL72BCEU|PTBL7CEU|PTBL7C|PTBL92BC|PTBL92BCEU|PTBL9CEU|PTBL9CUK|PTBL9C)\b', + // http://www.advandigital.com/index.php?link=content-product&jns=JP001 + // because of the short codenames we have to include whitespaces to reduce the possible conflicts. + 'AdvanTablet' => 'Android.* \b(E3A|T3X|T5C|T5B|T3E|T3C|T3B|T1J|T1F|T2A|T1H|T1i|E1C|T1-E|T5-A|T4|E1-B|T2Ci|T1-B|T1-D|O1-A|E1-A|T1-A|T3A|T4i)\b ', + // http://www.danytech.com/category/tablet-pc + 'DanyTechTablet' => 'Genius Tab G3|Genius Tab S2|Genius Tab Q3|Genius Tab G4|Genius Tab Q4|Genius Tab G-II|Genius TAB GII|Genius TAB GIII|Genius Tab S1', + // http://www.galapad.net/product.html ; https://github.com/serbanghita/Mobile-Detect/issues/761 + 'GalapadTablet' => 'Android [0-9.]+; [a-z-]+; \bG1\b', + // http://www.micromaxinfo.com/tablet/funbook + 'MicromaxTablet' => 'Funbook|Micromax.*\b(P250|P560|P360|P362|P600|P300|P350|P500|P275)\b', + // http://www.karbonnmobiles.com/products_tablet.php + 'KarbonnTablet' => 'Android.*\b(A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2)\b', + // http://www.myallfine.com/Products.asp + 'AllFineTablet' => 'Fine7 Genius|Fine7 Shine|Fine7 Air|Fine8 Style|Fine9 More|Fine10 Joy|Fine11 Wide', + // http://www.proscanvideo.com/products-search.asp?itemClass=TABLET&itemnmbr= + 'PROSCANTablet' => '\b(PEM63|PLT1023G|PLT1041|PLT1044|PLT1044G|PLT1091|PLT4311|PLT4311PL|PLT4315|PLT7030|PLT7033|PLT7033D|PLT7035|PLT7035D|PLT7044K|PLT7045K|PLT7045KB|PLT7071KG|PLT7072|PLT7223G|PLT7225G|PLT7777G|PLT7810K|PLT7849G|PLT7851G|PLT7852G|PLT8015|PLT8031|PLT8034|PLT8036|PLT8080K|PLT8082|PLT8088|PLT8223G|PLT8234G|PLT8235G|PLT8816K|PLT9011|PLT9045K|PLT9233G|PLT9735|PLT9760G|PLT9770G)\b', + // http://www.yonesnav.com/products/products.php + 'YONESTablet' => 'BQ1078|BC1003|BC1077|RK9702|BC9730|BC9001|IT9001|BC7008|BC7010|BC708|BC728|BC7012|BC7030|BC7027|BC7026', + // http://www.cjshowroom.com/eproducts.aspx?classcode=004001001 + // China manufacturer makes tablets for different small brands (eg. http://www.zeepad.net/index.html) + 'ChangJiaTablet' => 'TPC7102|TPC7103|TPC7105|TPC7106|TPC7107|TPC7201|TPC7203|TPC7205|TPC7210|TPC7708|TPC7709|TPC7712|TPC7110|TPC8101|TPC8103|TPC8105|TPC8106|TPC8203|TPC8205|TPC8503|TPC9106|TPC9701|TPC97101|TPC97103|TPC97105|TPC97106|TPC97111|TPC97113|TPC97203|TPC97603|TPC97809|TPC97205|TPC10101|TPC10103|TPC10106|TPC10111|TPC10203|TPC10205|TPC10503', + // http://www.gloryunion.cn/products.asp + // http://www.allwinnertech.com/en/apply/mobile.html + // http://www.ptcl.com.pk/pd_content.php?pd_id=284 (EVOTAB) + // @todo: Softwiner tablets? + // aka. Cute or Cool tablets. Not sure yet, must research to avoid collisions. + 'GUTablet' => 'TX-A1301|TX-M9002|Q702|kf026', // A12R|D75A|D77|D79|R83|A95|A106C|R15|A75|A76|D71|D72|R71|R73|R77|D82|R85|D92|A97|D92|R91|A10F|A77F|W71F|A78F|W78F|W81F|A97F|W91F|W97F|R16G|C72|C73E|K72|K73|R96G + // http://www.pointofview-online.com/showroom.php?shop_mode=product_listing&category_id=118 + 'PointOfViewTablet' => 'TAB-P506|TAB-navi-7-3G-M|TAB-P517|TAB-P-527|TAB-P701|TAB-P703|TAB-P721|TAB-P731N|TAB-P741|TAB-P825|TAB-P905|TAB-P925|TAB-PR945|TAB-PL1015|TAB-P1025|TAB-PI1045|TAB-P1325|TAB-PROTAB[0-9]+|TAB-PROTAB25|TAB-PROTAB26|TAB-PROTAB27|TAB-PROTAB26XL|TAB-PROTAB2-IPS9|TAB-PROTAB30-IPS9|TAB-PROTAB25XXL|TAB-PROTAB26-IPS10|TAB-PROTAB30-IPS10', + // http://www.overmax.pl/pl/katalog-produktow,p8/tablety,c14/ + // @todo: add more tests. + 'OvermaxTablet' => 'OV-(SteelCore|NewBase|Basecore|Baseone|Exellen|Quattor|EduTab|Solution|ACTION|BasicTab|TeddyTab|MagicTab|Stream|TB-08|TB-09)|Qualcore 1027', + // http://hclmetablet.com/India/index.php + 'HCLTablet' => 'HCL.*Tablet|Connect-3G-2.0|Connect-2G-2.0|ME Tablet U1|ME Tablet U2|ME Tablet G1|ME Tablet X1|ME Tablet Y2|ME Tablet Sync', + // http://www.edigital.hu/Tablet_es_e-book_olvaso/Tablet-c18385.html + 'DPSTablet' => 'DPS Dream 9|DPS Dual 7', + // http://www.visture.com/index.asp + 'VistureTablet' => 'V97 HD|i75 3G|Visture V4( HD)?|Visture V5( HD)?|Visture V10', + // http://www.mijncresta.nl/tablet + 'CrestaTablet' => 'CTP(-)?810|CTP(-)?818|CTP(-)?828|CTP(-)?838|CTP(-)?888|CTP(-)?978|CTP(-)?980|CTP(-)?987|CTP(-)?988|CTP(-)?989', + // MediaTek - http://www.mediatek.com/_en/01_products/02_proSys.php?cata_sn=1&cata1_sn=1&cata2_sn=309 + 'MediatekTablet' => '\bMT8125|MT8389|MT8135|MT8377\b', + // Concorde tab + 'ConcordeTablet' => 'Concorde([ ]+)?Tab|ConCorde ReadMan', + // GoClever Tablets - http://www.goclever.com/uk/products,c1/tablet,c5/ + 'GoCleverTablet' => 'GOCLEVER TAB|A7GOCLEVER|M1042|M7841|M742|R1042BK|R1041|TAB A975|TAB A7842|TAB A741|TAB A741L|TAB M723G|TAB M721|TAB A1021|TAB I921|TAB R721|TAB I720|TAB T76|TAB R70|TAB R76.2|TAB R106|TAB R83.2|TAB M813G|TAB I721|GCTA722|TAB I70|TAB I71|TAB S73|TAB R73|TAB R74|TAB R93|TAB R75|TAB R76.1|TAB A73|TAB A93|TAB A93.2|TAB T72|TAB R83|TAB R974|TAB R973|TAB A101|TAB A103|TAB A104|TAB A104.2|R105BK|M713G|A972BK|TAB A971|TAB R974.2|TAB R104|TAB R83.3|TAB A1042', + // Modecom Tablets - http://www.modecom.eu/tablets/portal/ + 'ModecomTablet' => 'FreeTAB 9000|FreeTAB 7.4|FreeTAB 7004|FreeTAB 7800|FreeTAB 2096|FreeTAB 7.5|FreeTAB 1014|FreeTAB 1001 |FreeTAB 8001|FreeTAB 9706|FreeTAB 9702|FreeTAB 7003|FreeTAB 7002|FreeTAB 1002|FreeTAB 7801|FreeTAB 1331|FreeTAB 1004|FreeTAB 8002|FreeTAB 8014|FreeTAB 9704|FreeTAB 1003', + // Vonino Tablets + 'VoninoTablet' => '\b(Argus[ _]?S|Diamond[ _]?79HD|Emerald[ _]?78E|Luna[ _]?70C|Onyx[ _]?S|Onyx[ _]?Z|Orin[ _]?HD|Orin[ _]?S|Otis[ _]?S|SpeedStar[ _]?S|Magnet[ _]?M9|Primus[ _]?94[ _]?3G|Primus[ _]?94HD|Primus[ _]?QS|Android.*\bQ8\b|Sirius[ _]?EVO[ _]?QS|Sirius[ _]?QS|Spirit[ _]?S)\b', + // ECS Tablets - http://www.ecs.com.tw/ECSWebSite/Product/Product_Tablet_List.aspx?CategoryID=14&MenuID=107&childid=M_107&LanID=0 + 'ECSTablet' => 'V07OT2|TM105A|S10OT1|TR10CS1', + // Storex Tablets - http://storex.fr/espace_client/support.html + // @note: no need to add all the tablet codes since they are guided by the first regex. + 'StorexTablet' => 'eZee[_\']?(Tab|Go)[0-9]+|TabLC7|Looney Tunes Tab', + // Generic Vodafone tablets. + 'VodafoneTablet' => 'SmartTab([ ]+)?[0-9]+|SmartTabII10|SmartTabII7|VF-1497|VFD 1400', + // French tablets - Essentiel B http://www.boulanger.fr/tablette_tactile_e-book/tablette_tactile_essentiel_b/cl_68908.htm?multiChoiceToDelete=brand&mc_brand=essentielb + // Aka: http://www.essentielb.fr/ + 'EssentielBTablet' => 'Smart[ \']?TAB[ ]+?[0-9]+|Family[ \']?TAB2', + // Ross & Moor - http://ross-moor.ru/ + 'RossMoorTablet' => 'RM-790|RM-997|RMD-878G|RMD-974R|RMT-705A|RMT-701|RME-601|RMT-501|RMT-711', + // i-mobile http://product.i-mobilephone.com/Mobile_Device + 'iMobileTablet' => 'i-mobile i-note', + // http://www.tolino.de/de/vergleichen/ + 'TolinoTablet' => 'tolino tab [0-9.]+|tolino shine', + // AudioSonic - a Kmart brand + // http://www.kmart.com.au/webapp/wcs/stores/servlet/Search?langId=-1&storeId=10701&catalogId=10001&categoryId=193001&pageSize=72¤tPage=1&searchCategory=193001%2b4294965664&sortBy=p_MaxPrice%7c1 + 'AudioSonicTablet' => '\bC-22Q|T7-QC|T-17B|T-17P\b', + // AMPE Tablets - http://www.ampe.com.my/product-category/tablets/ + // @todo: add them gradually to avoid conflicts. + 'AMPETablet' => 'Android.* A78 ', + // Skk Mobile - http://skkmobile.com.ph/product_tablets.php + 'SkkTablet' => 'Android.* (SKYPAD|PHOENIX|CYCLOPS)', + // Tecno Mobile (only tablet) - http://www.tecno-mobile.com/index.php/product?filterby=smart&list_order=all&page=1 + 'TecnoTablet' => 'TECNO P9|TECNO DP8D', + // JXD (consoles & tablets) - http://jxd.hk/products.asp?selectclassid=009008&clsid=3 + 'JXDTablet' => 'Android.* \b(F3000|A3300|JXD5000|JXD3000|JXD2000|JXD300B|JXD300|S5800|S7800|S602b|S5110b|S7300|S5300|S602|S603|S5100|S5110|S601|S7100a|P3000F|P3000s|P101|P200s|P1000m|P200m|P9100|P1000s|S6600b|S908|P1000|P300|S18|S6600|S9100)\b', + // i-Joy tablets - http://www.i-joy.es/en/cat/products/tablets/ + 'iJoyTablet' => 'Tablet (Spirit 7|Essentia|Galatea|Fusion|Onix 7|Landa|Titan|Scooby|Deox|Stella|Themis|Argon|Unique 7|Sygnus|Hexen|Finity 7|Cream|Cream X2|Jade|Neon 7|Neron 7|Kandy|Scape|Saphyr 7|Rebel|Biox|Rebel|Rebel 8GB|Myst|Draco 7|Myst|Tab7-004|Myst|Tadeo Jones|Tablet Boing|Arrow|Draco Dual Cam|Aurix|Mint|Amity|Revolution|Finity 9|Neon 9|T9w|Amity 4GB Dual Cam|Stone 4GB|Stone 8GB|Andromeda|Silken|X2|Andromeda II|Halley|Flame|Saphyr 9,7|Touch 8|Planet|Triton|Unique 10|Hexen 10|Memphis 4GB|Memphis 8GB|Onix 10)', + // http://www.intracon.eu/tablet + 'FX2Tablet' => 'FX2 PAD7|FX2 PAD10', + // http://www.xoro.de/produkte/ + // @note: Might be the same brand with 'Simply tablets' + 'XoroTablet' => 'KidsPAD 701|PAD[ ]?712|PAD[ ]?714|PAD[ ]?716|PAD[ ]?717|PAD[ ]?718|PAD[ ]?720|PAD[ ]?721|PAD[ ]?722|PAD[ ]?790|PAD[ ]?792|PAD[ ]?900|PAD[ ]?9715D|PAD[ ]?9716DR|PAD[ ]?9718DR|PAD[ ]?9719QR|PAD[ ]?9720QR|TelePAD1030|Telepad1032|TelePAD730|TelePAD731|TelePAD732|TelePAD735Q|TelePAD830|TelePAD9730|TelePAD795|MegaPAD 1331|MegaPAD 1851|MegaPAD 2151', + // http://www1.viewsonic.com/products/computing/tablets/ + 'ViewsonicTablet' => 'ViewPad 10pi|ViewPad 10e|ViewPad 10s|ViewPad E72|ViewPad7|ViewPad E100|ViewPad 7e|ViewSonic VB733|VB100a', + // https://www.verizonwireless.com/tablets/verizon/ + 'VerizonTablet' => 'QTAQZ3|QTAIR7|QTAQTZ3|QTASUN1|QTASUN2|QTAXIA1', + // http://www.odys.de/web/internet-tablet_en.html + 'OdysTablet' => 'LOOX|XENO10|ODYS[ -](Space|EVO|Xpress|NOON)|\bXELIO\b|Xelio10Pro|XELIO7PHONETAB|XELIO10EXTREME|XELIOPT2|NEO_QUAD10', + // http://www.captiva-power.de/products.html#tablets-en + 'CaptivaTablet' => 'CAPTIVA PAD', + // IconBIT - http://www.iconbit.com/products/tablets/ + 'IconbitTablet' => 'NetTAB|NT-3702|NT-3702S|NT-3702S|NT-3603P|NT-3603P|NT-0704S|NT-0704S|NT-3805C|NT-3805C|NT-0806C|NT-0806C|NT-0909T|NT-0909T|NT-0907S|NT-0907S|NT-0902S|NT-0902S', + // http://www.teclast.com/topic.php?channelID=70&topicID=140&pid=63 + 'TeclastTablet' => 'T98 4G|\bP80\b|\bX90HD\b|X98 Air|X98 Air 3G|\bX89\b|P80 3G|\bX80h\b|P98 Air|\bX89HD\b|P98 3G|\bP90HD\b|P89 3G|X98 3G|\bP70h\b|P79HD 3G|G18d 3G|\bP79HD\b|\bP89s\b|\bA88\b|\bP10HD\b|\bP19HD\b|G18 3G|\bP78HD\b|\bA78\b|\bP75\b|G17s 3G|G17h 3G|\bP85t\b|\bP90\b|\bP11\b|\bP98t\b|\bP98HD\b|\bG18d\b|\bP85s\b|\bP11HD\b|\bP88s\b|\bA80HD\b|\bA80se\b|\bA10h\b|\bP89\b|\bP78s\b|\bG18\b|\bP85\b|\bA70h\b|\bA70\b|\bG17\b|\bP18\b|\bA80s\b|\bA11s\b|\bP88HD\b|\bA80h\b|\bP76s\b|\bP76h\b|\bP98\b|\bA10HD\b|\bP78\b|\bP88\b|\bA11\b|\bA10t\b|\bP76a\b|\bP76t\b|\bP76e\b|\bP85HD\b|\bP85a\b|\bP86\b|\bP75HD\b|\bP76v\b|\bA12\b|\bP75a\b|\bA15\b|\bP76Ti\b|\bP81HD\b|\bA10\b|\bT760VE\b|\bT720HD\b|\bP76\b|\bP73\b|\bP71\b|\bP72\b|\bT720SE\b|\bC520Ti\b|\bT760\b|\bT720VE\b|T720-3GE|T720-WiFi', + // Onda - http://www.onda-tablet.com/buy-android-onda.html?dir=desc&limit=all&order=price + 'OndaTablet' => '\b(V975i|Vi30|VX530|V701|Vi60|V701s|Vi50|V801s|V719|Vx610w|VX610W|V819i|Vi10|VX580W|Vi10|V711s|V813|V811|V820w|V820|Vi20|V711|VI30W|V712|V891w|V972|V819w|V820w|Vi60|V820w|V711|V813s|V801|V819|V975s|V801|V819|V819|V818|V811|V712|V975m|V101w|V961w|V812|V818|V971|V971s|V919|V989|V116w|V102w|V973|Vi40)\b[\s]+|V10 \b4G\b', + 'JaytechTablet' => 'TPC-PA762', + 'BlaupunktTablet' => 'Endeavour 800NG|Endeavour 1010', + // http://www.digma.ru/support/download/ + // @todo: Ebooks also (if requested) + 'DigmaTablet' => '\b(iDx10|iDx9|iDx8|iDx7|iDxD7|iDxD8|iDsQ8|iDsQ7|iDsQ8|iDsD10|iDnD7|3TS804H|iDsQ11|iDj7|iDs10)\b', + // http://www.evolioshop.com/ro/tablete-pc.html + // http://www.evolio.ro/support/downloads_static.html?cat=2 + // @todo: Research some more + 'EvolioTablet' => 'ARIA_Mini_wifi|Aria[ _]Mini|Evolio X10|Evolio X7|Evolio X8|\bEvotab\b|\bNeura\b', + // @todo http://www.lavamobiles.com/tablets-data-cards + 'LavaTablet' => 'QPAD E704|\bIvoryS\b|E-TAB IVORY|\bE-TAB\b', + // http://www.breezetablet.com/ + 'AocTablet' => 'MW0811|MW0812|MW0922|MTK8382|MW1031|MW0831|MW0821|MW0931|MW0712', + // http://www.mpmaneurope.com/en/products/internet-tablets-14/android-tablets-14/ + 'MpmanTablet' => 'MP11 OCTA|MP10 OCTA|MPQC1114|MPQC1004|MPQC994|MPQC974|MPQC973|MPQC804|MPQC784|MPQC780|\bMPG7\b|MPDCG75|MPDCG71|MPDC1006|MP101DC|MPDC9000|MPDC905|MPDC706HD|MPDC706|MPDC705|MPDC110|MPDC100|MPDC99|MPDC97|MPDC88|MPDC8|MPDC77|MP709|MID701|MID711|MID170|MPDC703|MPQC1010', + // https://www.celkonmobiles.com/?_a=categoryphones&sid=2 + 'CelkonTablet' => 'CT695|CT888|CT[\s]?910|CT7 Tab|CT9 Tab|CT3 Tab|CT2 Tab|CT1 Tab|C820|C720|\bCT-1\b', + // http://www.wolderelectronics.com/productos/manuales-y-guias-rapidas/categoria-2-miTab + 'WolderTablet' => 'miTab \b(DIAMOND|SPACE|BROOKLYN|NEO|FLY|MANHATTAN|FUNK|EVOLUTION|SKY|GOCAR|IRON|GENIUS|POP|MINT|EPSILON|BROADWAY|JUMP|HOP|LEGEND|NEW AGE|LINE|ADVANCE|FEEL|FOLLOW|LIKE|LINK|LIVE|THINK|FREEDOM|CHICAGO|CLEVELAND|BALTIMORE-GH|IOWA|BOSTON|SEATTLE|PHOENIX|DALLAS|IN 101|MasterChef)\b', + 'MediacomTablet' => 'M-MPI10C3G|M-SP10EG|M-SP10EGP|M-SP10HXAH|M-SP7HXAH|M-SP10HXBH|M-SP8HXAH|M-SP8MXA', + // http://www.mi.com/en + 'MiTablet' => '\bMI PAD\b|\bHM NOTE 1W\b', + // http://www.nbru.cn/index.html + 'NibiruTablet' => 'Nibiru M1|Nibiru Jupiter One', + // http://navroad.com/products/produkty/tablety/ + // http://navroad.com/products/produkty/tablety/ + 'NexoTablet' => 'NEXO NOVA|NEXO 10|NEXO AVIO|NEXO FREE|NEXO GO|NEXO EVO|NEXO 3G|NEXO SMART|NEXO KIDDO|NEXO MOBI', + // http://leader-online.com/new_site/product-category/tablets/ + // http://www.leader-online.net.au/List/Tablet + 'LeaderTablet' => 'TBLT10Q|TBLT10I|TBL-10WDKB|TBL-10WDKBO2013|TBL-W230V2|TBL-W450|TBL-W500|SV572|TBLT7I|TBA-AC7-8G|TBLT79|TBL-8W16|TBL-10W32|TBL-10WKB|TBL-W100', + // http://www.datawind.com/ubislate/ + 'UbislateTablet' => 'UbiSlate[\s]?7C', + // http://www.pocketbook-int.com/ru/support + 'PocketBookTablet' => 'Pocketbook', + // http://www.kocaso.com/product_tablet.html + 'KocasoTablet' => '\b(TB-1207)\b', + // http://global.hisense.com/product/asia/tablet/Sero7/201412/t20141215_91832.htm + 'HisenseTablet' => '\b(F5281|E2371)\b', + // http://www.tesco.com/direct/hudl/ + 'Hudl' => 'Hudl HT7S3|Hudl 2', + // http://www.telstra.com.au/home-phone/thub-2/ + 'TelstraTablet' => 'T-Hub2', + 'GenericTablet' => 'Android.*\b97D\b|Tablet(?!.*PC)|BNTV250A|MID-WCDMA|LogicPD Zoom2|\bA7EB\b|CatNova8|A1_07|CT704|CT1002|\bM721\b|rk30sdk|\bEVOTAB\b|M758A|ET904|ALUMIUM10|Smartfren Tab|Endeavour 1010|Tablet-PC-4|Tagi Tab|\bM6pro\b|CT1020W|arc 10HD|\bTP750\b|\bQTAQZ3\b|WVT101|TM1088|KT107', + ]; + + /** + * List of mobile Operating Systems. + * + * @var array + */ + protected static $operatingSystems = [ + 'AndroidOS' => 'Android', + 'BlackBerryOS' => 'blackberry|\bBB10\b|rim tablet os', + 'PalmOS' => 'PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino', + 'SymbianOS' => 'Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b', + // @reference: http://en.wikipedia.org/wiki/Windows_Mobile + 'WindowsMobileOS' => 'Windows CE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Windows Mobile|Windows Phone [0-9.]+|WCE;', + // @reference: http://en.wikipedia.org/wiki/Windows_Phone + // http://wifeng.cn/?r=blog&a=view&id=106 + // http://nicksnettravels.builttoroam.com/post/2011/01/10/Bogus-Windows-Phone-7-User-Agent-String.aspx + // http://msdn.microsoft.com/library/ms537503.aspx + // https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx + 'WindowsPhoneOS' => 'Windows Phone 10.0|Windows Phone 8.1|Windows Phone 8.0|Windows Phone OS|XBLWP7|ZuneWP7|Windows NT 6.[23]; ARM;', + 'iOS' => '\biPhone.*Mobile|\biPod|\biPad|AppleCoreMedia', + // https://en.wikipedia.org/wiki/IPadOS + 'iPadOS' => 'CPU OS 13', + // @reference https://en.m.wikipedia.org/wiki/Sailfish_OS + // https://sailfishos.org/ + 'SailfishOS' => 'Sailfish', + // http://en.wikipedia.org/wiki/MeeGo + // @todo: research MeeGo in UAs + 'MeeGoOS' => 'MeeGo', + // http://en.wikipedia.org/wiki/Maemo + // @todo: research Maemo in UAs + 'MaemoOS' => 'Maemo', + 'JavaOS' => 'J2ME/|\bMIDP\b|\bCLDC\b', // '|Java/' produces bug #135 + 'webOS' => 'webOS|hpwOS', + 'badaOS' => '\bBada\b', + 'BREWOS' => 'BREW', + ]; + + /** + * List of mobile User Agents. + * + * IMPORTANT: This is a list of only mobile browsers. + * Mobile Detect 2.x supports only mobile browsers, + * it was never designed to detect all browsers. + * The change will come in 2017 in the 3.x release for PHP7. + * + * @var array + */ + protected static $browsers = [ + //'Vivaldi' => 'Vivaldi', + // @reference: https://developers.google.com/chrome/mobile/docs/user-agent + 'Chrome' => '\bCrMo\b|CriOS|Android.*Chrome/[.0-9]* (Mobile)?', + 'Dolfin' => '\bDolfin\b', + 'Opera' => 'Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR/[0-9.]+$|Coast/[0-9.]+', + 'Skyfire' => 'Skyfire', + // Added "Edge on iOS" https://github.com/serbanghita/Mobile-Detect/issues/764 + 'Edge' => '\bEdgiOS\b|Mobile Safari/[.0-9]* Edge', + 'IE' => 'IEMobile|MSIEMobile', // |Trident/[.0-9]+ + 'Firefox' => 'fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS', + 'Bolt' => 'bolt', + 'TeaShark' => 'teashark', + 'Blazer' => 'Blazer', + // @reference: http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3 + // Excluded "Edge on iOS" https://github.com/serbanghita/Mobile-Detect/issues/764 + 'Safari' => 'Version((?!\bEdgiOS\b).)*Mobile.*Safari|Safari.*Mobile|MobileSafari', + // http://en.wikipedia.org/wiki/Midori_(web_browser) + //'Midori' => 'midori', + //'Tizen' => 'Tizen', + 'WeChat' => '\bMicroMessenger\b', + 'UCBrowser' => 'UC.*Browser|UCWEB', + 'baiduboxapp' => 'baiduboxapp', + 'baidubrowser' => 'baidubrowser', + // https://github.com/serbanghita/Mobile-Detect/issues/7 + 'DiigoBrowser' => 'DiigoBrowser', + // http://www.puffinbrowser.com/index.php + // https://github.com/serbanghita/Mobile-Detect/issues/752 + // 'Puffin' => 'Puffin', + // http://mercury-browser.com/index.html + 'Mercury' => '\bMercury\b', + // http://en.wikipedia.org/wiki/Obigo_Browser + 'ObigoBrowser' => 'Obigo', + // http://en.wikipedia.org/wiki/NetFront + 'NetFront' => 'NF-Browser', + // @reference: http://en.wikipedia.org/wiki/Minimo + // http://en.wikipedia.org/wiki/Vision_Mobile_Browser + 'GenericBrowser' => 'NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger', + // @reference: https://en.wikipedia.org/wiki/Pale_Moon_(web_browser) + 'PaleMoon' => 'Android.*PaleMoon|Mobile.*PaleMoon', + ]; + + /** + * Utilities. + * + * @var array + */ + protected static $utilities = [ + // Experimental. When a mobile device wants to switch to 'Desktop Mode'. + // http://scottcate.com/technology/windows-phone-8-ie10-desktop-or-mobile/ + // https://github.com/serbanghita/Mobile-Detect/issues/57#issuecomment-15024011 + // https://developers.facebook.com/docs/sharing/webmasters/crawler/ + 'Bot' => 'Googlebot|facebookexternalhit|Google-AMPHTML|s~amp-validator|AdsBot-Google|Google Keyword Suggestion|Facebot|YandexBot|YandexMobileBot|bingbot|ia_archiver|AhrefsBot|Ezooms|GSLFbot|WBSearchBot|Twitterbot|TweetmemeBot|Twikle|PaperLiBot|Wotbox|UnwindFetchor|Exabot|MJ12bot|YandexImages|TurnitinBot|Pingdom|contentkingapp|AspiegelBot', + 'MobileBot' => 'Googlebot-Mobile|AdsBot-Google-Mobile|YahooSeeker/M1A1-R2D2', + 'DesktopMode' => 'WPDesktop', + 'TV' => 'SonyDTV|HbbTV', // experimental + 'WebKit' => '(webkit)[ /]([\w.]+)', + // @todo: Include JXD consoles. + 'Console' => '\b(Nintendo|Nintendo WiiU|Nintendo 3DS|Nintendo Switch|PLAYSTATION|Xbox)\b', + 'Watch' => 'SM-V700', + ]; + + /** + * All possible HTTP headers that represent the + * User-Agent string. + * + * @var array + */ + protected static $uaHttpHeaders = [ + // The default User-Agent string. + 'HTTP_USER_AGENT', + // Header can occur on devices using Opera Mini. + 'HTTP_X_OPERAMINI_PHONE_UA', + // Vodafone specific header: http://www.seoprinciple.com/mobile-web-community-still-angry-at-vodafone/24/ + 'HTTP_X_DEVICE_USER_AGENT', + 'HTTP_X_ORIGINAL_USER_AGENT', + 'HTTP_X_SKYFIRE_PHONE', + 'HTTP_X_BOLT_PHONE_UA', + 'HTTP_DEVICE_STOCK_UA', + 'HTTP_X_UCBROWSER_DEVICE_UA', + ]; + + /** + * The individual segments that could exist in a User-Agent string. VER refers to the regular + * expression defined in the constant self::VER. + * + * @var array + */ + protected static $properties = [ + + // Build + 'Mobile' => 'Mobile/[VER]', + 'Build' => 'Build/[VER]', + 'Version' => 'Version/[VER]', + 'VendorID' => 'VendorID/[VER]', + + // Devices + 'iPad' => 'iPad.*CPU[a-z ]+[VER]', + 'iPhone' => 'iPhone.*CPU[a-z ]+[VER]', + 'iPod' => 'iPod.*CPU[a-z ]+[VER]', + //'BlackBerry' => array('BlackBerry[VER]', 'BlackBerry [VER];'), + 'Kindle' => 'Kindle/[VER]', + + // Browser + 'Chrome' => ['Chrome/[VER]', 'CriOS/[VER]', 'CrMo/[VER]'], + 'Coast' => ['Coast/[VER]'], + 'Dolfin' => 'Dolfin/[VER]', + // @reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox + 'Firefox' => ['Firefox/[VER]', 'FxiOS/[VER]'], + 'Fennec' => 'Fennec/[VER]', + // http://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx + // https://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx + 'Edge' => 'Edge/[VER]', + 'IE' => ['IEMobile/[VER];', 'IEMobile [VER]', 'MSIE [VER];', 'Trident/[0-9.]+;.*rv:[VER]'], + // http://en.wikipedia.org/wiki/NetFront + 'NetFront' => 'NetFront/[VER]', + 'NokiaBrowser' => 'NokiaBrowser/[VER]', + 'Opera' => [ ' OPR/[VER]', 'Opera Mini/[VER]', 'Version/[VER]' ], + 'Opera Mini' => 'Opera Mini/[VER]', + 'Opera Mobi' => 'Version/[VER]', + 'UCBrowser' => [ 'UCWEB[VER]', 'UC.*Browser/[VER]' ], + 'MQQBrowser' => 'MQQBrowser/[VER]', + 'MicroMessenger' => 'MicroMessenger/[VER]', + 'baiduboxapp' => 'baiduboxapp/[VER]', + 'baidubrowser' => 'baidubrowser/[VER]', + 'SamsungBrowser' => 'SamsungBrowser/[VER]', + 'Iron' => 'Iron/[VER]', + // @note: Safari 7534.48.3 is actually Version 5.1. + // @note: On BlackBerry the Version is overwriten by the OS. + 'Safari' => [ 'Version/[VER]', 'Safari/[VER]' ], + 'Skyfire' => 'Skyfire/[VER]', + 'Tizen' => 'Tizen/[VER]', + 'Webkit' => 'webkit[ /][VER]', + 'PaleMoon' => 'PaleMoon/[VER]', + 'SailfishBrowser' => 'SailfishBrowser/[VER]', + + // Engine + 'Gecko' => 'Gecko/[VER]', + 'Trident' => 'Trident/[VER]', + 'Presto' => 'Presto/[VER]', + 'Goanna' => 'Goanna/[VER]', + + // OS + 'iOS' => ' \bi?OS\b [VER][ ;]{1}', + 'Android' => 'Android [VER]', + 'Sailfish' => 'Sailfish [VER]', + 'BlackBerry' => ['BlackBerry[\w]+/[VER]', 'BlackBerry.*Version/[VER]', 'Version/[VER]'], + 'BREW' => 'BREW [VER]', + 'Java' => 'Java/[VER]', + // @reference: http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/08/29/introducing-the-ie9-on-windows-phone-mango-user-agent-string.aspx + // @reference: http://en.wikipedia.org/wiki/Windows_NT#Releases + 'Windows Phone OS' => [ 'Windows Phone OS [VER]', 'Windows Phone [VER]'], + 'Windows Phone' => 'Windows Phone [VER]', + 'Windows CE' => 'Windows CE/[VER]', + // http://social.msdn.microsoft.com/Forums/en-US/windowsdeveloperpreviewgeneral/thread/6be392da-4d2f-41b4-8354-8dcee20c85cd + 'Windows NT' => 'Windows NT [VER]', + 'Symbian' => ['SymbianOS/[VER]', 'Symbian/[VER]'], + 'webOS' => ['webOS/[VER]', 'hpwOS/[VER];'], + ]; + + /** + * Construct an instance of this class. + * + * @param array $headers Specify the headers as injection. Should be PHP _SERVER flavored. + * If left empty, will use the global _SERVER['HTTP_*'] vars instead. + * @param string $userAgent Inject the User-Agent header. If null, will use HTTP_USER_AGENT + * from the $headers array instead. + */ + public function __construct( + array $headers = null, + $userAgent = null + ) { + $this->setHttpHeaders($headers); + $this->setUserAgent($userAgent); + } + + /** + * Get the current script version. + * This is useful for the demo.php file, + * so people can check on what version they are testing + * for mobile devices. + * + * @return string The version number in semantic version format. + */ + public static function getScriptVersion() + { + return self::VERSION; + } + + /** + * Set the HTTP Headers. Must be PHP-flavored. This method will reset existing headers. + * + * @param array $httpHeaders The headers to set. If null, then using PHP's _SERVER to extract + * the headers. The default null is left for backwards compatibility. + */ + public function setHttpHeaders($httpHeaders = null) + { + // use global _SERVER if $httpHeaders aren't defined + if (!is_array($httpHeaders) || !count($httpHeaders)) { + $httpHeaders = $_SERVER; + } + + // clear existing headers + $this->httpHeaders = []; + + // Only save HTTP headers. In PHP land, that means only _SERVER vars that + // start with HTTP_. + foreach ($httpHeaders as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $this->httpHeaders[$key] = $value; + } + } + + // In case we're dealing with CloudFront, we need to know. + $this->setCfHeaders($httpHeaders); + } + + /** + * Retrieves the HTTP headers. + * + * @return array + */ + public function getHttpHeaders() + { + return $this->httpHeaders; + } + + /** + * Retrieves a particular header. If it doesn't exist, no exception/error is caused. + * Simply null is returned. + * + * @param string $header The name of the header to retrieve. Can be HTTP compliant such as + * "User-Agent" or "X-Device-User-Agent" or can be php-esque with the + * all-caps, HTTP_ prefixed, underscore seperated awesomeness. + * + * @return string|null The value of the header. + */ + public function getHttpHeader($header) + { + // are we using PHP-flavored headers? + if (strpos($header, '_') === false) { + $header = str_replace('-', '_', $header); + $header = strtoupper($header); + } + + // test the alternate, too + $altHeader = 'HTTP_' . $header; + + //Test both the regular and the HTTP_ prefix + if (isset($this->httpHeaders[$header])) { + return $this->httpHeaders[$header]; + } elseif (isset($this->httpHeaders[$altHeader])) { + return $this->httpHeaders[$altHeader]; + } + + return null; + } + + public function getMobileHeaders() + { + return self::$mobileHeaders; + } + + /** + * Get all possible HTTP headers that + * can contain the User-Agent string. + * + * @return array List of HTTP headers. + */ + public function getUaHttpHeaders() + { + return self::$uaHttpHeaders; + } + + + /** + * Set CloudFront headers + * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-device + * + * @param array $cfHeaders List of HTTP headers + * + * @return boolean If there were CloudFront headers to be set + */ + public function setCfHeaders($cfHeaders = null) + { + // use global _SERVER if $cfHeaders aren't defined + if (!is_array($cfHeaders) || !count($cfHeaders)) { + $cfHeaders = $_SERVER; + } + + // clear existing headers + $this->cloudfrontHeaders = []; + + // Only save CLOUDFRONT headers. In PHP land, that means only _SERVER vars that + // start with cloudfront-. + $response = false; + foreach ($cfHeaders as $key => $value) { + if (substr(strtolower($key), 0, 16) === 'http_cloudfront_') { + $this->cloudfrontHeaders[strtoupper($key)] = $value; + $response = true; + } + } + + return $response; + } + + /** + * Retrieves the cloudfront headers. + * + * @return array + */ + public function getCfHeaders() + { + return $this->cloudfrontHeaders; + } + + /** + * @param string $userAgent + * @return string + */ + private function prepareUserAgent($userAgent) + { + $userAgent = trim($userAgent); + $userAgent = substr($userAgent, 0, 500); + return $userAgent; + } + + /** + * Set the User-Agent to be used. + * + * @param string $userAgent The user agent string to set. + * + * @return string|null + */ + public function setUserAgent($userAgent = null) + { + // Invalidate cache due to #375 + $this->cache = []; + + if (false === empty($userAgent)) { + return $this->userAgent = $this->prepareUserAgent($userAgent); + } else { + $this->userAgent = null; + foreach ($this->getUaHttpHeaders() as $altHeader) { + if (false === empty($this->httpHeaders[$altHeader])) { // @todo: should use getHttpHeader(), but it would be slow. (Serban) + $this->userAgent .= $this->httpHeaders[$altHeader] . " "; + } + } + + if (!empty($this->userAgent)) { + return $this->userAgent = $this->prepareUserAgent($this->userAgent); + } + } + + if (count($this->getCfHeaders()) > 0) { + return $this->userAgent = 'Amazon CloudFront'; + } + return $this->userAgent = null; + } + + /** + * Retrieve the User-Agent. + * + * @return string|null The user agent if it's set. + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Set the detection type. Must be one of self::DETECTION_TYPE_MOBILE or + * self::DETECTION_TYPE_EXTENDED. Otherwise, nothing is set. + * + * @deprecated since version 2.6.9 + * + * @param string $type The type. Must be a self::DETECTION_TYPE_* constant. The default + * parameter is null which will default to self::DETECTION_TYPE_MOBILE. + */ + public function setDetectionType($type = null) + { + if ($type === null) { + $type = self::DETECTION_TYPE_MOBILE; + } + + if ($type !== self::DETECTION_TYPE_MOBILE && $type !== self::DETECTION_TYPE_EXTENDED) { + return; + } + + $this->detectionType = $type; + } + + public function getMatchingRegex() + { + return $this->matchingRegex; + } + + public function getMatchesArray() + { + return $this->matchesArray; + } + + /** + * Retrieve the list of known phone devices. + * + * @return array List of phone devices. + */ + public static function getPhoneDevices() + { + return self::$phoneDevices; + } + + /** + * Retrieve the list of known tablet devices. + * + * @return array List of tablet devices. + */ + public static function getTabletDevices() + { + return self::$tabletDevices; + } + + /** + * Alias for getBrowsers() method. + * + * @return array List of user agents. + */ + public static function getUserAgents() + { + return self::getBrowsers(); + } + + /** + * Retrieve the list of known browsers. Specifically, the user agents. + * + * @return array List of browsers / user agents. + */ + public static function getBrowsers() + { + return self::$browsers; + } + + /** + * Retrieve the list of known utilities. + * + * @return array List of utilities. + */ + public static function getUtilities() + { + return self::$utilities; + } + + /** + * Method gets the mobile detection rules. This method is used for the magic methods $detect->is*(). + * + * @deprecated since version 2.6.9 + * + * @return array All the rules (but not extended). + */ + public static function getMobileDetectionRules() + { + static $rules; + + if (!$rules) { + $rules = array_merge( + self::$phoneDevices, + self::$tabletDevices, + self::$operatingSystems, + self::$browsers + ); + } + + return $rules; + } + + /** + * Method gets the mobile detection rules + utilities. + * The reason this is separate is because utilities rules + * don't necessary imply mobile. This method is used inside + * the new $detect->is('stuff') method. + * + * @deprecated since version 2.6.9 + * + * @return array All the rules + extended. + */ + public function getMobileDetectionRulesExtended() + { + static $rules; + + if (!$rules) { + // Merge all rules together. + $rules = array_merge( + self::$phoneDevices, + self::$tabletDevices, + self::$operatingSystems, + self::$browsers, + self::$utilities + ); + } + + return $rules; + } + + /** + * Retrieve the current set of rules. + * + * @deprecated since version 2.6.9 + * + * @return array + */ + public function getRules() + { + if ($this->detectionType == self::DETECTION_TYPE_EXTENDED) { + return self::getMobileDetectionRulesExtended(); + } else { + return self::getMobileDetectionRules(); + } + } + + /** + * Retrieve the list of mobile operating systems. + * + * @return array The list of mobile operating systems. + */ + public static function getOperatingSystems() + { + return self::$operatingSystems; + } + + /** + * Check the HTTP headers for signs of mobile. + * This is the fastest mobile check possible; it's used + * inside isMobile() method. + * + * @return bool + */ + public function checkHttpHeadersForMobile() + { + foreach ($this->getMobileHeaders() as $mobileHeader => $matchType) { + if (isset($this->httpHeaders[$mobileHeader])) { + if (isset($matchType['matches']) && is_array($matchType['matches'])) { + foreach ($matchType['matches'] as $_match) { + if (strpos($this->httpHeaders[$mobileHeader], $_match) !== false) { + return true; + } + } + + return false; + } else { + return true; + } + } + } + + return false; + } + + /** + * Magic overloading method. + * + * @method boolean is[...]() + * @param string $name + * @param array $arguments + * @return mixed + * @throws BadMethodCallException when the method doesn't exist and doesn't start with 'is' + */ + public function __call($name, $arguments) + { + // make sure the name starts with 'is', otherwise + if (substr($name, 0, 2) !== 'is') { + throw new BadMethodCallException("No such method exists: $name"); + } + + $this->setDetectionType(self::DETECTION_TYPE_MOBILE); + + $key = substr($name, 2); + + return $this->matchUAAgainstKey($key); + } + + /** + * Find a detection rule that matches the current User-agent. + * + * @param null $userAgent deprecated + * @return boolean + */ + protected function matchDetectionRulesAgainstUA($userAgent = null) + { + // Begin general search. + foreach ($this->getRules() as $_regex) { + if (empty($_regex)) { + continue; + } + + if ($this->match($_regex, $userAgent)) { + return true; + } + } + + return false; + } + + /** + * Search for a certain key in the rules array. + * If the key is found then try to match the corresponding + * regex against the User-Agent. + * + * @param string $key + * + * @return boolean + */ + protected function matchUAAgainstKey($key) + { + // Make the keys lowercase so we can match: isIphone(), isiPhone(), isiphone(), etc. + $key = strtolower($key); + if (false === isset($this->cache[$key])) { + + // change the keys to lower case + $_rules = array_change_key_case($this->getRules()); + + if (false === empty($_rules[$key])) { + $this->cache[$key] = $this->match($_rules[$key]); + } + + if (false === isset($this->cache[$key])) { + $this->cache[$key] = false; + } + } + + return $this->cache[$key]; + } + + /** + * Check if the device is mobile. + * Returns true if any type of mobile device detected, including special ones + * @param null $userAgent deprecated + * @param null $httpHeaders deprecated + * @return bool + */ + public function isMobile($userAgent = null, $httpHeaders = null) + { + if ($httpHeaders) { + $this->setHttpHeaders($httpHeaders); + } + + if ($userAgent) { + $this->setUserAgent($userAgent); + } + + // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' + if ($this->getUserAgent() === 'Amazon CloudFront') { + $cfHeaders = $this->getCfHeaders(); + if (array_key_exists('HTTP_CLOUDFRONT_IS_MOBILE_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_MOBILE_VIEWER'] === 'true') { + return true; + } + } + + $this->setDetectionType(self::DETECTION_TYPE_MOBILE); + + if ($this->checkHttpHeadersForMobile()) { + return true; + } else { + return $this->matchDetectionRulesAgainstUA(); + } + } + + /** + * Check if the device is a tablet. + * Return true if any type of tablet device is detected. + * + * @param string $userAgent deprecated + * @param array $httpHeaders deprecated + * @return bool + */ + public function isTablet($userAgent = null, $httpHeaders = null) + { + // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' + if ($this->getUserAgent() === 'Amazon CloudFront') { + $cfHeaders = $this->getCfHeaders(); + if (array_key_exists('HTTP_CLOUDFRONT_IS_TABLET_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_TABLET_VIEWER'] === 'true') { + return true; + } + } + + $this->setDetectionType(self::DETECTION_TYPE_MOBILE); + + foreach (self::$tabletDevices as $_regex) { + if ($this->match($_regex, $userAgent)) { + return true; + } + } + + return false; + } + + /** + * This method checks for a certain property in the + * userAgent. + * @todo: The httpHeaders part is not yet used. + * + * @param string $key + * @param string $userAgent deprecated + * @param string $httpHeaders deprecated + * @return bool|int|null + */ + public function is($key, $userAgent = null, $httpHeaders = null) + { + // Set the UA and HTTP headers only if needed (eg. batch mode). + if ($httpHeaders) { + $this->setHttpHeaders($httpHeaders); + } + + if ($userAgent) { + $this->setUserAgent($userAgent); + } + + $this->setDetectionType(self::DETECTION_TYPE_EXTENDED); + + return $this->matchUAAgainstKey($key); + } + + /** + * Some detection rules are relative (not standard), + * because of the diversity of devices, vendors and + * their conventions in representing the User-Agent or + * the HTTP headers. + * + * This method will be used to check custom regexes against + * the User-Agent string. + * + * @param $regex + * @param string $userAgent + * @return bool + * + * @todo: search in the HTTP headers too. + */ + public function match($regex, $userAgent = null) + { + $match = (bool) preg_match(sprintf('#%s#is', $regex), (false === empty($userAgent) ? $userAgent : $this->userAgent), $matches); + // If positive match is found, store the results for debug. + if ($match) { + $this->matchingRegex = $regex; + $this->matchesArray = $matches; + } + + return $match; + } + + /** + * Get the properties array. + * + * @return array + */ + public static function getProperties() + { + return self::$properties; + } + + /** + * Prepare the version number. + * + * @todo Remove the error supression from str_replace() call. + * + * @param string $ver The string version, like "2.6.21.2152"; + * + * @return float + */ + public function prepareVersionNo($ver) + { + $ver = str_replace(['_', ' ', '/'], '.', $ver); + $arrVer = explode('.', $ver, 2); + + if (isset($arrVer[1])) { + $arrVer[1] = @str_replace('.', '', $arrVer[1]); // @todo: treat strings versions. + } + + return (float) implode('.', $arrVer); + } + + /** + * Check the version of the given property in the User-Agent. + * Will return a float number. (eg. 2_0 will return 2.0, 4.3.1 will return 4.31) + * + * @param string $propertyName The name of the property. See self::getProperties() array + * keys for all possible properties. + * @param string $type Either self::VERSION_TYPE_STRING to get a string value or + * self::VERSION_TYPE_FLOAT indicating a float value. This parameter + * is optional and defaults to self::VERSION_TYPE_STRING. Passing an + * invalid parameter will default to the this type as well. + * + * @return string|float The version of the property we are trying to extract. + */ + public function version($propertyName, $type = self::VERSION_TYPE_STRING) + { + if (empty($propertyName)) { + return false; + } + + // set the $type to the default if we don't recognize the type + if ($type !== self::VERSION_TYPE_STRING && $type !== self::VERSION_TYPE_FLOAT) { + $type = self::VERSION_TYPE_STRING; + } + + $properties = self::getProperties(); + + // Check if the property exists in the properties array. + if (true === isset($properties[$propertyName])) { + + // Prepare the pattern to be matched. + // Make sure we always deal with an array (string is converted). + $properties[$propertyName] = (array) $properties[$propertyName]; + + foreach ($properties[$propertyName] as $propertyMatchString) { + $propertyPattern = str_replace('[VER]', self::VER, $propertyMatchString); + + // Identify and extract the version. + preg_match(sprintf('#%s#is', $propertyPattern), $this->userAgent, $match); + + if (false === empty($match[1])) { + $version = ($type == self::VERSION_TYPE_FLOAT ? $this->prepareVersionNo($match[1]) : $match[1]); + + return $version; + } + } + } + + return false; + } + + /** + * Retrieve the mobile grading, using self::MOBILE_GRADE_* constants. + * + * @return string One of the self::MOBILE_GRADE_* constants. + */ + public function mobileGrade() + { + $isMobile = $this->isMobile(); + + if ( + // Apple iOS 4-7.0 – Tested on the original iPad (4.3 / 5.0), iPad 2 (4.3 / 5.1 / 6.1), iPad 3 (5.1 / 6.0), iPad Mini (6.1), iPad Retina (7.0), iPhone 3GS (4.3), iPhone 4 (4.3 / 5.1), iPhone 4S (5.1 / 6.0), iPhone 5 (6.0), and iPhone 5S (7.0) + $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) >= 4.3 || + $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) >= 4.3 || + $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) >= 4.3 || + + // Android 2.1-2.3 - Tested on the HTC Incredible (2.2), original Droid (2.2), HTC Aria (2.1), Google Nexus S (2.3). Functional on 1.5 & 1.6 but performance may be sluggish, tested on Google G1 (1.5) + // Android 3.1 (Honeycomb) - Tested on the Samsung Galaxy Tab 10.1 and Motorola XOOM + // Android 4.0 (ICS) - Tested on a Galaxy Nexus. Note: transition performance can be poor on upgraded devices + // Android 4.1 (Jelly Bean) - Tested on a Galaxy Nexus and Galaxy 7 + ($this->version('Android', self::VERSION_TYPE_FLOAT)>2.1 && $this->is('Webkit')) || + + // Windows Phone 7.5-8 - Tested on the HTC Surround (7.5), HTC Trophy (7.5), LG-E900 (7.5), Nokia 800 (7.8), HTC Mazaa (7.8), Nokia Lumia 520 (8), Nokia Lumia 920 (8), HTC 8x (8) + $this->version('Windows Phone OS', self::VERSION_TYPE_FLOAT) >= 7.5 || + + // Tested on the Torch 9800 (6) and Style 9670 (6), BlackBerry® Torch 9810 (7), BlackBerry Z10 (10) + $this->is('BlackBerry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 6.0 || + // Blackberry Playbook (1.0-2.0) - Tested on PlayBook + $this->match('Playbook.*Tablet') || + + // Palm WebOS (1.4-3.0) - Tested on the Palm Pixi (1.4), Pre (1.4), Pre 2 (2.0), HP TouchPad (3.0) + ($this->version('webOS', self::VERSION_TYPE_FLOAT) >= 1.4 && $this->match('Palm|Pre|Pixi')) || + // Palm WebOS 3.0 - Tested on HP TouchPad + $this->match('hp.*TouchPad') || + + // Firefox Mobile 18 - Tested on Android 2.3 and 4.1 devices + ($this->is('Firefox') && $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 18) || + + // Chrome for Android - Tested on Android 4.0, 4.1 device + ($this->is('Chrome') && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 4.0) || + + // Skyfire 4.1 - Tested on Android 2.3 device + ($this->is('Skyfire') && $this->version('Skyfire', self::VERSION_TYPE_FLOAT) >= 4.1 && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3) || + + // Opera Mobile 11.5-12: Tested on Android 2.3 + ($this->is('Opera') && $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11.5 && $this->is('AndroidOS')) || + + // Meego 1.2 - Tested on Nokia 950 and N9 + $this->is('MeeGoOS') || + + // Sailfish OS + $this->is('SailfishOS') || + + // Tizen (pre-release) - Tested on early hardware + $this->is('Tizen') || + + // Samsung Bada 2.0 - Tested on a Samsung Wave 3, Dolphin browser + // @todo: more tests here! + $this->is('Dolfin') && $this->version('Bada', self::VERSION_TYPE_FLOAT) >= 2.0 || + + // UC Browser - Tested on Android 2.3 device + (($this->is('UC Browser') || $this->is('Dolfin')) && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3) || + + // Kindle 3 and Fire - Tested on the built-in WebKit browser for each + ($this->match('Kindle Fire') || + $this->is('Kindle') && $this->version('Kindle', self::VERSION_TYPE_FLOAT) >= 3.0) || + + // Nook Color 1.4.1 - Tested on original Nook Color, not Nook Tablet + $this->is('AndroidOS') && $this->is('NookTablet') || + + // Chrome Desktop 16-24 - Tested on OS X 10.7 and Windows 7 + $this->version('Chrome', self::VERSION_TYPE_FLOAT) >= 16 && !$isMobile || + + // Safari Desktop 5-6 - Tested on OS X 10.7 and Windows 7 + $this->version('Safari', self::VERSION_TYPE_FLOAT) >= 5.0 && !$isMobile || + + // Firefox Desktop 10-18 - Tested on OS X 10.7 and Windows 7 + $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 10.0 && !$isMobile || + + // Internet Explorer 7-9 - Tested on Windows XP, Vista and 7 + $this->version('IE', self::VERSION_TYPE_FLOAT) >= 7.0 && !$isMobile || + + // Opera Desktop 10-12 - Tested on OS X 10.7 and Windows 7 + $this->version('Opera', self::VERSION_TYPE_FLOAT) >= 10 && !$isMobile + ) { + return self::MOBILE_GRADE_A; + } + + if ( + $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT)<4.3 || + $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT)<4.3 || + $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT)<4.3 || + + // Blackberry 5.0: Tested on the Storm 2 9550, Bold 9770 + $this->is('Blackberry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 5 && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT)<6 || + + //Opera Mini (5.0-6.5) - Tested on iOS 3.2/4.3 and Android 2.3 + ($this->version('Opera Mini', self::VERSION_TYPE_FLOAT) >= 5.0 && $this->version('Opera Mini', self::VERSION_TYPE_FLOAT) <= 7.0 && + ($this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 || $this->is('iOS'))) || + + // Nokia Symbian^3 - Tested on Nokia N8 (Symbian^3), C7 (Symbian^3), also works on N97 (Symbian^1) + $this->match('NokiaN8|NokiaC7|N97.*Series60|Symbian/3') || + + // @todo: report this (tested on Nokia N71) + $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11 && $this->is('SymbianOS') + ) { + return self::MOBILE_GRADE_B; + } + + if ( + // Blackberry 4.x - Tested on the Curve 8330 + $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) <= 5.0 || + // Windows Mobile - Tested on the HTC Leo (WinMo 5.2) + $this->match('MSIEMobile|Windows CE.*Mobile') || $this->version('Windows Mobile', self::VERSION_TYPE_FLOAT) <= 5.2 || + + // Tested on original iPhone (3.1), iPhone 3 (3.2) + $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) <= 3.2 || + $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) <= 3.2 || + $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) <= 3.2 || + + // Internet Explorer 7 and older - Tested on Windows XP + $this->version('IE', self::VERSION_TYPE_FLOAT) <= 7.0 && !$isMobile + ) { + return self::MOBILE_GRADE_C; + } + + // All older smartphone platforms and featurephones - Any device that doesn't support media queries + // will receive the basic, C grade experience. + return self::MOBILE_GRADE_C; + } +} diff --git a/objects/Object.php b/objects/Object.php index 14d5a48b34..6c7b7b77f9 100644 --- a/objects/Object.php +++ b/objects/Object.php @@ -1,826 +1,863 @@ -load($id); - } - } - - protected function load($id) { - $row = self::getFromDb($id); - if (empty($row)) { - return false; - } - foreach ($row as $key => $value) { - $this->$key = $value; - } - return true; - } - - public static function getNowFromDB() { - global $global; - $sql = "SELECT NOW() as my_date_field"; - $res = sqlDAL::readSql($sql); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - $row = $data; - } else { - $row = false; - } - return $row; - } - - public static function setGlobalTimeZone() { - global $advancedCustom, $timezoneOriginal; - if (!isset($timezoneOriginal)) { - $timezoneOriginal = date_default_timezone_get(); - } - if (!empty($_COOKIE['timezone']) && $_COOKIE['timezone'] !== 'undefined') { - $timezone = $_COOKIE['timezone']; - } else { - $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type); - $timezone = $timeZOnesOptions[$advancedCustom->timeZone->value]; - } - if (empty($timezone) || $timezone == 'undefined') { - return false; - } - date_default_timezone_set($timezone); - } - - protected static function getFromDb($id) { - global $global; - $id = intval($id); - $sql = "SELECT * FROM " . static::getTableName() . " WHERE id = ? 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, "i", array($id), true); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - $row = $data; - } else { - $row = false; - } - return $row; - } - - public static function getAll() { - global $global; - if (!static::isTableInstalled()) { - return false; - } - $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; - - $sql .= self::getSqlFromPost(); - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - 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; - } - - public static function getAllActive() { - global $global; - if (!static::isTableInstalled()) { - return false; - } - $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='a' "; - - $sql .= self::getSqlFromPost(); - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - 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; - } - - public static function getTotal() { - //will receive - //current=1&rowCount=10&sort[sender]=asc&searchPhrase= - global $global; - if (!static::isTableInstalled()) { - return 0; - } - $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; - $sql .= self::getSqlSearchFromPost(); - $res = sqlDAL::readSql($sql); - $countRow = sqlDAL::num_rows($res); - sqlDAL::close($res); - return $countRow; - } - - public static function getSqlFromPost($keyPrefix = "") { - global $global; - $sql = self::getSqlSearchFromPost(); - - if (empty($_POST['sort']) && !empty($_GET['order'][0]['dir'])) { - $index = intval($_GET['order'][0]['column']); - $_GET['columns'][$index]['data']; - $_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir']; - } - - // add a security here - if (!empty($_POST['sort'])) { - foreach ($_POST['sort'] as $key => $value) { - $_POST['sort'][xss_esc($key)] = xss_esc($value); - } - } - - if (!empty($_POST['sort'])) { - $orderBy = array(); - foreach ($_POST['sort'] as $key => $value) { - $key = $global['mysqli']->real_escape_string($key); - //$value = $global['mysqli']->real_escape_string($value); - $direction = "ASC"; - if (strtoupper($value) === "DESC") { - $direction = "DESC"; - } - $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); - $key = trim($key); - if (strpos($key, '.') === false) { - $key = "`{$key}`"; - } - $orderBy[] = " {$keyPrefix}{$key} {$value} "; - } - $sql .= " ORDER BY " . implode(",", $orderBy); - } - - $sql .= self::getSqlLimit(); - return $sql; - } - - public static function getSqlLimit() { - global $global; - $sql = ""; - - if (empty($_POST['rowCount']) && !empty($_GET['length'])) { - $_POST['rowCount'] = intval($_GET['length']); - } - - if (empty($_POST['current']) && !empty($_GET['start'])) { - $_POST['current'] = ($_GET['start'] / $_GET['length']) + 1; - } elseif (empty($_POST['current']) && isset($_GET['start'])) { - $_POST['current'] = 1; - } - - $_POST['current'] = getCurrentPage(); - $_POST['rowCount'] = getRowCount(); - - if (!empty($_POST['rowCount']) && !empty($_POST['current']) && $_POST['rowCount'] > 0) { - $_POST['rowCount'] = intval($_POST['rowCount']); - $_POST['current'] = intval($_POST['current']); - $current = ($_POST['current'] - 1) * $_POST['rowCount']; - $current = $current < 0 ? 0 : $current; - $sql .= " LIMIT $current, {$_POST['rowCount']} "; - } else { - $_POST['current'] = 0; - $_POST['rowCount'] = 0; - $sql .= " LIMIT 1000 "; - } - return $sql; - } - - public static function getSqlDateFilter() { - $sql = ''; - $created_year = intval(@$_REQUEST['created_year']); - $created_month = intval(@$_REQUEST['created_month']); - $modified_year = intval(@$_REQUEST['modified_year']); - $modified_month = intval(@$_REQUEST['modified_month']); - - if(!empty($created_year)){ - $sql .= " AND YEAR(created) = $created_year "; - } - if(!empty($created_month)){ - $sql .= " AND MONTH(created) = $created_month "; - } - if(!empty($modified_year)){ - $sql .= " AND YEAR(modified) = $modified_year "; - } - if(!empty($modified_month)){ - $sql .= " AND MONTH(modified) = $modified_month "; - } - - return $sql; - } - - public static function getSqlSearchFromPost() { - $sql = self::getSqlDateFilter(); - if (!empty($_POST['searchPhrase'])) { - $_GET['q'] = $_POST['searchPhrase']; - } elseif (!empty($_GET['search']['value'])) { - $_GET['q'] = $_GET['search']['value']; - } - if (!empty($_GET['q'])) { - global $global; - $search = $global['mysqli']->real_escape_string(xss_esc($_GET['q'])); - - $like = array(); - $searchFields = static::getSearchFieldsNames(); - foreach ($searchFields as $value) { - if(!str_contains($value, '.') && !str_contains($value, '`')){ - $value = "`{$value}`"; - } - $like[] = " {$value} LIKE '%{$search}%' "; - // for accent insensitive - $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; - } - if (!empty($like)) { - $sql .= " AND (" . implode(" OR ", $like) . ")"; - } else { - $sql .= " AND 1=1 "; - } - } - - return $sql; - } - - public function save() { - if (!$this->tableExists()) { - _error_log("Save error, table " . static::getTableName() . " does not exists", AVideoLog::$ERROR); - return false; - } - global $global; - $fieldsName = $this->getAllFields(); - if (!empty($this->id)) { - $sql = "UPDATE " . static::getTableName() . " SET "; - $fields = array(); - foreach ($fieldsName as $value) { - if (strtolower($value) == 'created') { - // do nothing - } elseif (strtolower($value) == 'modified') { - $fields[] = " {$value} = now() "; - } elseif (strtolower($value) == 'timezone') { - if(empty($this->$value)){ - $this->$value = date_default_timezone_get(); - } - $fields[] = " `{$value}` = '{$this->$value}' "; - } elseif (is_numeric($this->$value)) { - $fields[] = " `{$value}` = {$this->$value} "; - } elseif (strtolower($this->$value) == 'null') { - $fields[] = " `{$value}` = NULL "; - } else { - $fields[] = " `{$value}` = '{$this->$value}' "; - } - } - $sql .= implode(", ", $fields); - $sql .= " WHERE id = {$this->id}"; - } else { - $sql = "INSERT INTO " . static::getTableName() . " ( "; - $sql .= "`" . implode("`,`", $fieldsName) . "` )"; - $fields = array(); - foreach ($fieldsName as $value) { - if (is_string($value) && (strtolower($value) == 'created' || strtolower($value) == 'modified')) { - $fields[] = " now() "; - } elseif (is_string($value) && strtolower($value) == 'timezone') { - if(empty($this->$value)){ - $this->$value = date_default_timezone_get(); - } - $fields[] = " '{$this->$value}' "; - } elseif (!isset($this->$value) || (is_string($this->$value) && strtolower($this->$value) == 'null')) { - $fields[] = " NULL "; - } else if (is_string($this->$value) || is_numeric($this->$value)) { - $fields[] = " '{$this->$value}' "; - } else { - $fields[] = " NULL "; - } - } - $sql .= " VALUES (" . implode(", ", $fields) . ")"; - } - //if(static::getTableName() == 'subscriptions') echo $sql; - $insert_row = sqlDAL::writeSql($sql); - - if ($insert_row) { - if (empty($this->id)) { - $id = $global['mysqli']->insert_id; - } else { - $id = $this->id; - } - return $id; - } else { - _error_log("ObjectYPT::save Error on save: " . $sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error, AVideoLog::$ERROR); - return false; - } - } - - private function getAllFields() { - global $global, $mysqlDatabase; - $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '" . static::getTableName() . "'"; - $res = sqlDAL::readSql($sql, "s", array($mysqlDatabase)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $rows[] = $row["COLUMN_NAME"]; - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $rows; - } - - public function delete() { - global $global; - if (!empty($this->id)) { - $sql = "DELETE FROM " . static::getTableName() . " "; - $sql .= " WHERE id = ?"; - $global['lastQuery'] = $sql; - //_error_log("Delete Query: ".$sql); - return sqlDAL::writeSql($sql, "i", array($this->id)); - } - _error_log("Id for table " . static::getTableName() . " not defined for deletion ". json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)), AVideoLog::$ERROR); - return false; - } - - static function shouldUseDatabase($content){ - global $advancedCustom, $global; - if(!empty($global['doNotUseCacheDatabase'])){ - return false; - } - $maxLen = 60000; - - if(empty($advancedCustom)){ - $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); - } - if(empty($advancedCustom->doNotSaveCacheOnFilesystem) && class_exists('Cache') && self::isTableInstalled('CachesInDB')){ - $json = _json_encode($content); - $len = strlen($json); - if($len>$maxLen/2){ - return false; - } - if(class_exists('CachesInDB')){ - $content = CachesInDB::encodeContent($json); - }else{ - $content = base64_encode($json); - } - - $len = strlen($content); - if(!empty($len) && $len<$maxLen){ - return $content; - }else if(!empty($len)){ - //_error_log('Object::setCache '.$len); - } - } - return false; - } - - public static function setCache($name, $value) { - if($content = self::shouldUseDatabase($value)){ - return Cache::_setCache($name, $content); - } - - $content = _json_encode($value); - if (empty($content)) { - $content = $value; - } - - if(empty($content)){ - return false; - } - - $cachefile = self::getCacheFileName($name); - //make_path($cachefile); - - $bytes = @file_put_contents($cachefile, $content); - self::setSessionCache($name, $value); - return array('bytes' => $bytes, 'cachefile' => $cachefile); - } - - public static function cleanCacheName($name) { - $name = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $name); - $name = preg_replace('/[!#$&\'()*+,:;=?@[\\]% -]+/', '_', trim(strtolower(cleanString($name)))); - $name = preg_replace('/\/{2,}/', '/', trim(strtolower(cleanString($name)))); - if (function_exists('mb_ereg_replace')) { - $name = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).\\/\\\])", '', $name); - // Remove any runs of periods (thanks falstro!) - $name = mb_ereg_replace("([\.]{2,})", '', $name); - } - return preg_replace('/[\x00-\x1F\x7F]/u', '', $name); - } - - /** - * - * @param type $name - * @param type $lifetime, if is = 0 it is unlimited - * @return type - */ - public static function getCache($name, $lifetime = 60, $ignoreSessionCache = false) { - global $global; - if(!empty($global['ignoreAllCache'])){ - return null; - } - self::setLastUsedCacheMode("No cache detected $name, $lifetime, " . intval($ignoreSessionCache)); - if (isCommandLineInterface()) { - return null; - } - if (isBot()) { - $lifetime = 0; - } - global $getCachesProcessed, $_getCache; - - if (empty($_getCache)) { - $_getCache = array(); - } - - if (empty($getCachesProcessed)) { - $getCachesProcessed = array(); - } - $cachefile = self::getCacheFileName($name, false); - //var_dump($cachefile);//exit; - self::setLastUsedCacheFile($cachefile); - //_error_log('getCache: cachefile '.$cachefile); - if (!empty($_getCache[$name])) { - //_error_log('getCache: '.__LINE__); - self::setLastUsedCacheMode("Global Variable \$_getCache[$name]"); - return $_getCache[$name]; - } - - if (empty($getCachesProcessed[$name])) { - $getCachesProcessed[$name] = 0; - } - $getCachesProcessed[$name]++; - - if (!empty($_GET['lifetime'])) { - $lifetime = intval($_GET['lifetime']); - } - - if (empty($ignoreSessionCache)) { - $session = self::getSessionCache($name, $lifetime); - if (!empty($session)) { - $_getCache[$name] = $session; - //_error_log('getCache: '.__LINE__); - return $session; - } - } - - if(self::shouldUseDatabase('')){ - $cache = Cache::getCache($name, $lifetime); - if(!empty($cache)){ - return $cache; - } - } - - /* - if (preg_match('/firstpage/i', $cachefile)) { - echo var_dump($cachefile) . PHP_EOL; - $trace = debug_backtrace(); - $backtrace_lite = array(); - foreach ($trace as $call) { - echo $call['function'] . " " . $call['file'] . " line " . $call['line'] . PHP_EOL; - }exit; - } - /** - */ - if (file_exists($cachefile) && (empty($lifetime) || time() - $lifetime <= filemtime($cachefile))) { - //if(preg_match('/getStats/', $cachefile)){echo $cachefile,'
';} - self::setLastUsedCacheMode("Local File $cachefile"); - $c = @url_get_contents($cachefile); - $json = _json_decode($c); - - if (empty($json) && !is_object($json) && !is_array($json)) { - $json = $c; - } - - self::setSessionCache($name, $json); - $_getCache[$name] = $json; - //_error_log('getCache: '.__LINE__); - return $json; - } elseif (file_exists($cachefile)) { - self::deleteCache($name); - @unlink($cachefile); - } - //if(preg_match('/getChannelsWithMoreViews30/i', $name)){var_dump($name, $cachefile, file_exists($cachefile) , $lifetime, time() - $lifetime, filemtime($cachefile));exit;} - //_error_log("YPTObject::getCache log error [{$name}] $cachefile filemtime = ".filemtime($cachefile)); - return null; - } - - private static function setLastUsedCacheMode($mode) { - global $_lastCacheMode; - $_lastCacheMode = $mode; - } - - private static function setLastUsedCacheFile($cachefile) { - global $_lastCacheFile; - $_lastCacheFile = $cachefile; - } - - public static function getLastUsedCacheInfo() { - global $_lastCacheFile, $_lastCacheMode; - return array('file' => $_lastCacheFile, 'mode' => $_lastCacheMode); - } - - public static function deleteCache($name) { - if (empty($name) || !class_exists('Cache')) { - return false; - } - - Cache::deleteCache($name); - - global $__getAVideoCache; - unset($__getAVideoCache); - //_error_log('deleteCache: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $cachefile = self::getCacheFileName($name, false); - @unlink($cachefile); - self::deleteSessionCache($name); - ObjectYPT::deleteCacheFromPattern($name); - } - - static function deleteCachePattern($pattern) { - global $__getAVideoCache; - unset($__getAVideoCache); - $tmpDir = self::getCacheDir(); - $array = _glob($tmpDir, $pattern); - _error_log('deleteCachePattern: ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - foreach ($array as $value) { - _error_log("Object::deleteCachePattern file [{$value}]"); - @unlink($value); - } - _session_start(); - foreach ($_SESSION['user']['sessionCache'] as $key => $value) { - if (preg_match($pattern, $key)) { - _error_log("Object::deleteCachePattern session [{$key}]"); - $_SESSION['user']['sessionCache'][$key] = null; - unset($_SESSION['user']['sessionCache'][$key]); - } - } - } - - public static function deleteALLCache() { - if(class_exists('Cache')){ - Cache::deleteAllCache(); - } - self::deleteAllSessionCache(); - $lockFile = getVideosDir() . '.deleteALLCache.lock'; - if (file_exists($lockFile) && filectime($lockFile) > strtotime('-5 minutes')) { - _error_log('clearCache is in progress ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - return false; - } - $start = microtime(true); - _error_log('deleteALLCache starts '); - global $__getAVideoCache; - unset($__getAVideoCache); - //_error_log('deleteALLCache: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $tmpDir = self::getCacheDir('', false); - - $newtmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . uniqid(); - _error_log("deleteALLCache rename($tmpDir, $newtmpDir) "); - rename($tmpDir, $newtmpDir); - if (is_dir($tmpDir)) { - _error_log('deleteALLCache 1 rmdir ' . $tmpDir); - rrmdir($tmpDir); - } else if(preg_match('/videos.cache/', $newtmpDir)){ - // only delete if it is on the videos dir. otherwise it is on the /tmp dit and the system will delete it - _error_log('deleteALLCache 2 rmdir ' . $newtmpDir); - rrmdirCommandLine($newtmpDir, true); - } - self::setLastDeleteALLCacheTime(); - unlink($lockFile); - $end = microtime(true) - $start; - _error_log("deleteALLCache end in {$end} seconds"); - return true; - } - - public static function getCacheDir($filename = '', $createDir=true) { - global $_getCacheDir, $global; - - if (!isset($_getCacheDir)) { - $_getCacheDir = array(); - } - - if (!empty($_getCacheDir[$filename])) { - return $_getCacheDir[$filename]; - } - - $tmpDir = getTmpDir(); - $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - $tmpDir .= "YPTObjectCache" . DIRECTORY_SEPARATOR; - - $filename = self::cleanCacheName($filename); - if (!empty($filename)) { - $tmpDir .= $filename . DIRECTORY_SEPARATOR; - - $domain = getDomain(); - // make sure you separete http and https cache - $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http'; - - $tmpDir .= "{$protocol}_{$domain}" . DIRECTORY_SEPARATOR; - - if (class_exists("User_Location")) { - $loc = User_Location::getThisUserLocation(); - if (!empty($loc) && !empty($loc['country_code']) && $loc['country_code']!='-') { - $tmpDir .= $loc['country_code'] . DIRECTORY_SEPARATOR; - } - } - - if (User::isLogged()) { - if (User::isAdmin()) { - $tmpDir .= 'admin_' . md5("admin" . $global['salt']) . DIRECTORY_SEPARATOR; - } else { - $tmpDir .= 'user_' . md5("user" . $global['salt']) . DIRECTORY_SEPARATOR; - } - } else { - $tmpDir .= 'notlogged_' . md5("notlogged" . $global['salt']) . DIRECTORY_SEPARATOR; - } - } - $tmpDir = fixPath($tmpDir); - if($createDir){ - make_path($tmpDir); - } - if (!file_exists($tmpDir . "index.html") && is_writable($tmpDir)) {// to avoid search into the directory - _file_put_contents($tmpDir . "index.html", time()); - } - - $_getCacheDir[$filename] = $tmpDir; - return $tmpDir; - } - - public static function getCacheFileName($name, $createDir=true) { - global $global; - $tmpDir = self::getCacheDir($name, $createDir); - $uniqueHash = md5($name . $global['salt']); // add salt for security reasons - return $tmpDir . $uniqueHash . '.cache'; - } - - public static function deleteCacheFromPattern($name) { - if (empty($name)) { - return false; - } - $tmpDir = getTmpDir(); - //_error_log('deleteCacheFromPattern: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $name = self::cleanCacheName($name); - $ignoreLocationDirectoryName = (strpos($name, DIRECTORY_SEPARATOR) !== false); - $filePattern = $tmpDir . DIRECTORY_SEPARATOR . $name; - foreach (glob("{$filePattern}*") as $filename) { - unlink($filename); - } - self::deleteSessionCache($name); - } - - /** - * Make sure you start the session before any output - * @param type $name - * @param type $value - */ - public static function setSessionCache($name, $value) { - $name = self::cleanCacheName($name); - _session_start(); - $_SESSION['user']['sessionCache'][$name]['value'] = json_encode($value); - $_SESSION['user']['sessionCache'][$name]['time'] = time(); - if (empty($_SESSION['user']['sessionCache']['time'])) { - $_SESSION['user']['sessionCache']['time'] = time(); - } - } - - /** - * - * @param type $name - * @param type $lifetime, if is = 0 it is unlimited - * @return type - */ - public static function getSessionCache($name, $lifetime = 60) { - $name = self::cleanCacheName($name); - if (!empty($_GET['lifetime'])) { - $lifetime = intval($_GET['lifetime']); - } - if (!empty($_SESSION['user']['sessionCache'][$name])) { - if ((empty($lifetime) || time() - $lifetime <= $_SESSION['user']['sessionCache'][$name]['time'])) { - $c = $_SESSION['user']['sessionCache'][$name]['value']; - self::setLastUsedCacheMode("Session cache \$_SESSION['user']['sessionCache'][$name]"); - $json = _json_decode($c); - if (is_string($json) && strtolower($json) === 'false') { - $json = false; - } - return $json; - } - _session_start(); - unset($_SESSION['user']['sessionCache'][$name]); - } - return null; - } - - public static function clearSessionCache() { - unset($_SESSION['user']['sessionCache']); - } - - private static function getLastDeleteALLCacheTimeFile() { - $tmpDir = getTmpDir(); - $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/"; - $tmpDir .= "lastDeleteALLCacheTime.cache"; - return $tmpDir; - } - - public static function setLastDeleteALLCacheTime() { - $file = self::getLastDeleteALLCacheTimeFile(); - //_error_log("ObjectYPT::setLastDeleteALLCacheTime {$file}"); - return file_put_contents($file, time()); - } - - public static function getLastDeleteALLCacheTime() { - global $getLastDeleteALLCacheTime; - if (empty($getLastDeleteALLCacheTime)) { - $getLastDeleteALLCacheTime = (int) @file_get_contents(self::getLastDeleteALLCacheTimeFile(), time()); - } - return $getLastDeleteALLCacheTime; - } - - public static function checkSessionCacheBasedOnLastDeleteALLCacheTime() { - /* - var_dump( - $session_var['time'], - self::getLastDeleteALLCacheTime(), - humanTiming($session_var['time']), - humanTiming(self::getLastDeleteALLCacheTime()), - $session_var['time'] <= self::getLastDeleteALLCacheTime()); - * - */ - if (empty($_SESSION['user']['sessionCache']['time']) || $_SESSION['user']['sessionCache']['time'] <= self::getLastDeleteALLCacheTime()) { - self::deleteAllSessionCache(); - return false; - } - return true; - } - - public static function deleteSessionCache($name) { - $name = self::cleanCacheName($name); - _session_start(); - $_SESSION['user']['sessionCache'][$name] = null; - unset($_SESSION['user']['sessionCache'][$name]); - } - - public static function deleteAllSessionCache() { - _session_start(); - unset($_SESSION['user']['sessionCache']); - return empty($_SESSION['user']['sessionCache']); - } - - public function tableExists() { - return self::isTableInstalled(); - } - - public static function isTableInstalled($tableName = "") { - global $global, $tableExists; - if (empty($tableName)) { - $tableName = static::getTableName(); - } - if (empty($tableName)) { - return false; - } - if (!isset($tableExists[$tableName])) { - $sql = "SHOW TABLES LIKE '" . $tableName . "'"; - //_error_log("isTableInstalled: ({$sql})"); - $res = sqlDAL::readSql($sql); - $result = sqlDal::num_rows($res); - sqlDAL::close($res); - $tableExists[$tableName] = !empty($result); - } - return $tableExists[$tableName]; - } - - static function clientTimezoneToDatabaseTimezone($clientDate) { - - if (!preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/', $clientDate)) { - return $clientDate; - } - - global $timezoneOriginal; - $currentTimezone = date_default_timezone_get(); - $time = strtotime($clientDate); - date_default_timezone_set($timezoneOriginal); - - $dbDate = date('Y-m-d H:i:s', $time); - - date_default_timezone_set($currentTimezone); - return $dbDate; - } - -} - -//abstract class Object extends ObjectYPT{}; +load($id); + } + } + + protected function load($id) + { + $row = self::getFromDb($id); + if (empty($row)) { + return false; + } + foreach ($row as $key => $value) { + $this->$key = $value; + } + return true; + } + + public static function getNowFromDB() + { + global $global; + $sql = "SELECT NOW() as my_date_field"; + $res = sqlDAL::readSql($sql); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + $row = $data; + } else { + $row = false; + } + return $row; + } + + public static function setGlobalTimeZone() + { + global $advancedCustom, $timezoneOriginal; + if (!isset($timezoneOriginal)) { + $timezoneOriginal = date_default_timezone_get(); + } + if (!empty($_COOKIE['timezone']) && $_COOKIE['timezone'] !== 'undefined') { + $timezone = $_COOKIE['timezone']; + } else { + $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type); + $timezone = $timeZOnesOptions[$advancedCustom->timeZone->value]; + } + if (empty($timezone) || $timezone == 'undefined') { + return false; + } + date_default_timezone_set($timezone); + } + + protected static function getFromDb($id) + { + global $global; + $id = intval($id); + $sql = "SELECT * FROM " . static::getTableName() . " WHERE id = ? 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, "i", [$id], true); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + $row = $data; + } else { + $row = false; + } + return $row; + } + + public static function getAll() + { + global $global; + if (!static::isTableInstalled()) { + return false; + } + $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; + + $sql .= self::getSqlFromPost(); + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + public static function getAllActive() + { + global $global; + if (!static::isTableInstalled()) { + return false; + } + $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='a' "; + + $sql .= self::getSqlFromPost(); + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + public static function getTotal() + { + //will receive + //current=1&rowCount=10&sort[sender]=asc&searchPhrase= + global $global; + if (!static::isTableInstalled()) { + return 0; + } + $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; + $sql .= self::getSqlSearchFromPost(); + $res = sqlDAL::readSql($sql); + $countRow = sqlDAL::num_rows($res); + sqlDAL::close($res); + return $countRow; + } + + public static function getSqlFromPost($keyPrefix = "") + { + global $global; + $sql = self::getSqlSearchFromPost(); + + if (empty($_POST['sort']) && !empty($_GET['order'][0]['dir'])) { + $index = intval($_GET['order'][0]['column']); + $_GET['columns'][$index]['data']; + $_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir']; + } + + // add a security here + if (!empty($_POST['sort'])) { + foreach ($_POST['sort'] as $key => $value) { + $_POST['sort'][xss_esc($key)] = xss_esc($value); + } + } + + if (!empty($_POST['sort'])) { + $orderBy = []; + foreach ($_POST['sort'] as $key => $value) { + $key = $global['mysqli']->real_escape_string($key); + //$value = $global['mysqli']->real_escape_string($value); + $direction = "ASC"; + if (strtoupper($value) === "DESC") { + $direction = "DESC"; + } + $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); + $key = trim($key); + if (strpos($key, '.') === false) { + $key = "`{$key}`"; + } + $orderBy[] = " {$keyPrefix}{$key} {$value} "; + } + $sql .= " ORDER BY " . implode(",", $orderBy); + } + + $sql .= self::getSqlLimit(); + return $sql; + } + + public static function getSqlLimit() + { + global $global; + $sql = ''; + + if (empty($_POST['rowCount']) && !empty($_GET['length'])) { + $_POST['rowCount'] = intval($_GET['length']); + } + + if (empty($_POST['current']) && !empty($_GET['start'])) { + $_POST['current'] = ($_GET['start'] / $_GET['length']) + 1; + } elseif (empty($_POST['current']) && isset($_GET['start'])) { + $_POST['current'] = 1; + } + + $_POST['current'] = getCurrentPage(); + $_POST['rowCount'] = getRowCount(); + + if (!empty($_POST['rowCount']) && !empty($_POST['current']) && $_POST['rowCount'] > 0) { + $_POST['rowCount'] = intval($_POST['rowCount']); + $_POST['current'] = intval($_POST['current']); + $current = ($_POST['current'] - 1) * $_POST['rowCount']; + $current = $current < 0 ? 0 : $current; + $sql .= " LIMIT $current, {$_POST['rowCount']} "; + } else { + $_POST['current'] = 0; + $_POST['rowCount'] = 0; + $sql .= " LIMIT 1000 "; + } + return $sql; + } + + public static function getSqlDateFilter() + { + $sql = ''; + $created_year = intval(@$_REQUEST['created_year']); + $created_month = intval(@$_REQUEST['created_month']); + $modified_year = intval(@$_REQUEST['modified_year']); + $modified_month = intval(@$_REQUEST['modified_month']); + + if (!empty($created_year)) { + $sql .= " AND YEAR(created) = $created_year "; + } + if (!empty($created_month)) { + $sql .= " AND MONTH(created) = $created_month "; + } + if (!empty($modified_year)) { + $sql .= " AND YEAR(modified) = $modified_year "; + } + if (!empty($modified_month)) { + $sql .= " AND MONTH(modified) = $modified_month "; + } + + return $sql; + } + + public static function getSqlSearchFromPost() + { + $sql = self::getSqlDateFilter(); + if (!empty($_POST['searchPhrase'])) { + $_GET['q'] = $_POST['searchPhrase']; + } elseif (!empty($_GET['search']['value'])) { + $_GET['q'] = $_GET['search']['value']; + } + if (!empty($_GET['q'])) { + global $global; + $search = $global['mysqli']->real_escape_string(xss_esc($_GET['q'])); + + $like = []; + $searchFields = static::getSearchFieldsNames(); + foreach ($searchFields as $value) { + if (!str_contains($value, '.') && !str_contains($value, '`')) { + $value = "`{$value}`"; + } + $like[] = " {$value} LIKE '%{$search}%' "; + // for accent insensitive + $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; + } + if (!empty($like)) { + $sql .= " AND (" . implode(" OR ", $like) . ")"; + } else { + $sql .= " AND 1=1 "; + } + } + + return $sql; + } + + public function save() + { + if (!$this->tableExists()) { + _error_log("Save error, table " . static::getTableName() . " does not exists", AVideoLog::$ERROR); + return false; + } + global $global; + $fieldsName = $this->getAllFields(); + if (!empty($this->id)) { + $sql = "UPDATE " . static::getTableName() . " SET "; + $fields = []; + foreach ($fieldsName as $value) { + if (strtolower($value) == 'created') { + // do nothing + } elseif (strtolower($value) == 'modified') { + $fields[] = " {$value} = now() "; + } elseif (strtolower($value) == 'timezone') { + if (empty($this->$value)) { + $this->$value = date_default_timezone_get(); + } + $fields[] = " `{$value}` = '{$this->$value}' "; + } elseif (is_numeric($this->$value)) { + $fields[] = " `{$value}` = {$this->$value} "; + } elseif (strtolower($this->$value) == 'null') { + $fields[] = " `{$value}` = NULL "; + } else { + $fields[] = " `{$value}` = '{$this->$value}' "; + } + } + $sql .= implode(", ", $fields); + $sql .= " WHERE id = {$this->id}"; + } else { + $sql = "INSERT INTO " . static::getTableName() . " ( "; + $sql .= "`" . implode("`,`", $fieldsName) . "` )"; + $fields = []; + foreach ($fieldsName as $value) { + if (is_string($value) && (strtolower($value) == 'created' || strtolower($value) == 'modified')) { + $fields[] = " now() "; + } elseif (is_string($value) && strtolower($value) == 'timezone') { + if (empty($this->$value)) { + $this->$value = date_default_timezone_get(); + } + $fields[] = " '{$this->$value}' "; + } elseif (!isset($this->$value) || (is_string($this->$value) && strtolower($this->$value) == 'null')) { + $fields[] = " NULL "; + } elseif (is_string($this->$value) || is_numeric($this->$value)) { + $fields[] = " '{$this->$value}' "; + } else { + $fields[] = " NULL "; + } + } + $sql .= " VALUES (" . implode(", ", $fields) . ")"; + } + //if(static::getTableName() == 'subscriptions') echo $sql; + $insert_row = sqlDAL::writeSql($sql); + + if ($insert_row) { + if (empty($this->id)) { + $id = $global['mysqli']->insert_id; + } else { + $id = $this->id; + } + return $id; + } else { + _error_log("ObjectYPT::save Error on save: " . $sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error, AVideoLog::$ERROR); + return false; + } + } + + private function getAllFields() + { + global $global, $mysqlDatabase; + $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '" . static::getTableName() . "'"; + $res = sqlDAL::readSql($sql, "s", [$mysqlDatabase]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row["COLUMN_NAME"]; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + public function delete() + { + global $global; + if (!empty($this->id)) { + $sql = "DELETE FROM " . static::getTableName() . " "; + $sql .= " WHERE id = ?"; + $global['lastQuery'] = $sql; + //_error_log("Delete Query: ".$sql); + return sqlDAL::writeSql($sql, "i", [$this->id]); + } + _error_log("Id for table " . static::getTableName() . " not defined for deletion ". json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)), AVideoLog::$ERROR); + return false; + } + + public static function shouldUseDatabase($content) + { + global $advancedCustom, $global; + if (!empty($global['doNotUseCacheDatabase'])) { + return false; + } + $maxLen = 60000; + + if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); + } + if (empty($advancedCustom->doNotSaveCacheOnFilesystem) && class_exists('Cache') && self::isTableInstalled('CachesInDB')) { + $json = _json_encode($content); + $len = strlen($json); + if ($len>$maxLen/2) { + return false; + } + if (class_exists('CachesInDB')) { + $content = CachesInDB::encodeContent($json); + } else { + $content = base64_encode($json); + } + + $len = strlen($content); + if (!empty($len) && $len<$maxLen) { + return $content; + } elseif (!empty($len)) { + //_error_log('Object::setCache '.$len); + } + } + return false; + } + + public static function setCache($name, $value) + { + if ($content = self::shouldUseDatabase($value)) { + return Cache::_setCache($name, $content); + } + + $content = _json_encode($value); + if (empty($content)) { + $content = $value; + } + + if (empty($content)) { + return false; + } + + $cachefile = self::getCacheFileName($name); + //make_path($cachefile); + + $bytes = @file_put_contents($cachefile, $content); + self::setSessionCache($name, $value); + return ['bytes' => $bytes, 'cachefile' => $cachefile]; + } + + public static function cleanCacheName($name) + { + $name = str_replace(['/', '\\'], [DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $name); + $name = preg_replace('/[!#$&\'()*+,:;=?@[\\]% -]+/', '_', trim(strtolower(cleanString($name)))); + $name = preg_replace('/\/{2,}/', '/', trim(strtolower(cleanString($name)))); + if (function_exists('mb_ereg_replace')) { + $name = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).\\/\\\])", '', $name); + // Remove any runs of periods (thanks falstro!) + $name = mb_ereg_replace("([\.]{2,})", '', $name); + } + return preg_replace('/[\x00-\x1F\x7F]/u', '', $name); + } + + /** + * + * @param type $name + * @param type $lifetime, if is = 0 it is unlimited + * @return type + */ + public static function getCache($name, $lifetime = 60, $ignoreSessionCache = false) + { + global $global; + if (!empty($global['ignoreAllCache'])) { + return null; + } + self::setLastUsedCacheMode("No cache detected $name, $lifetime, " . intval($ignoreSessionCache)); + if (isCommandLineInterface()) { + return null; + } + if (isBot()) { + $lifetime = 0; + } + global $getCachesProcessed, $_getCache; + + if (empty($_getCache)) { + $_getCache = []; + } + + if (empty($getCachesProcessed)) { + $getCachesProcessed = []; + } + $cachefile = self::getCacheFileName($name, false); + //var_dump($cachefile);//exit; + self::setLastUsedCacheFile($cachefile); + //_error_log('getCache: cachefile '.$cachefile); + if (!empty($_getCache[$name])) { + //_error_log('getCache: '.__LINE__); + self::setLastUsedCacheMode("Global Variable \$_getCache[$name]"); + return $_getCache[$name]; + } + + if (empty($getCachesProcessed[$name])) { + $getCachesProcessed[$name] = 0; + } + $getCachesProcessed[$name]++; + + if (!empty($_GET['lifetime'])) { + $lifetime = intval($_GET['lifetime']); + } + + if (empty($ignoreSessionCache)) { + $session = self::getSessionCache($name, $lifetime); + if (!empty($session)) { + $_getCache[$name] = $session; + //_error_log('getCache: '.__LINE__); + return $session; + } + } + + if (self::shouldUseDatabase('')) { + $cache = Cache::getCache($name, $lifetime); + if (!empty($cache)) { + return $cache; + } + } + + /* + if (preg_match('/firstpage/i', $cachefile)) { + echo var_dump($cachefile) . PHP_EOL; + $trace = debug_backtrace(); + $backtrace_lite = array(); + foreach ($trace as $call) { + echo $call['function'] . " " . $call['file'] . " line " . $call['line'] . PHP_EOL; + }exit; + } + /** + */ + if (file_exists($cachefile) && (empty($lifetime) || time() - $lifetime <= filemtime($cachefile))) { + //if(preg_match('/getStats/', $cachefile)){echo $cachefile,'
';} + self::setLastUsedCacheMode("Local File $cachefile"); + $c = @url_get_contents($cachefile); + $json = _json_decode($c); + + if (empty($json) && !is_object($json) && !is_array($json)) { + $json = $c; + } + + self::setSessionCache($name, $json); + $_getCache[$name] = $json; + //_error_log('getCache: '.__LINE__); + return $json; + } elseif (file_exists($cachefile)) { + self::deleteCache($name); + @unlink($cachefile); + } + //if(preg_match('/getChannelsWithMoreViews30/i', $name)){var_dump($name, $cachefile, file_exists($cachefile) , $lifetime, time() - $lifetime, filemtime($cachefile));exit;} + //_error_log("YPTObject::getCache log error [{$name}] $cachefile filemtime = ".filemtime($cachefile)); + return null; + } + + private static function setLastUsedCacheMode($mode) + { + global $_lastCacheMode; + $_lastCacheMode = $mode; + } + + private static function setLastUsedCacheFile($cachefile) + { + global $_lastCacheFile; + $_lastCacheFile = $cachefile; + } + + public static function getLastUsedCacheInfo() + { + global $_lastCacheFile, $_lastCacheMode; + return ['file' => $_lastCacheFile, 'mode' => $_lastCacheMode]; + } + + public static function deleteCache($name) + { + if (empty($name) || !class_exists('Cache')) { + return false; + } + + Cache::deleteCache($name); + + global $__getAVideoCache; + unset($__getAVideoCache); + //_error_log('deleteCache: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $cachefile = self::getCacheFileName($name, false); + @unlink($cachefile); + self::deleteSessionCache($name); + ObjectYPT::deleteCacheFromPattern($name); + } + + public static function deleteCachePattern($pattern) + { + global $__getAVideoCache; + unset($__getAVideoCache); + $tmpDir = self::getCacheDir(); + $array = _glob($tmpDir, $pattern); + _error_log('deleteCachePattern: ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + foreach ($array as $value) { + _error_log("Object::deleteCachePattern file [{$value}]"); + @unlink($value); + } + _session_start(); + foreach ($_SESSION['user']['sessionCache'] as $key => $value) { + if (preg_match($pattern, $key)) { + _error_log("Object::deleteCachePattern session [{$key}]"); + $_SESSION['user']['sessionCache'][$key] = null; + unset($_SESSION['user']['sessionCache'][$key]); + } + } + } + + public static function deleteALLCache() + { + if (class_exists('Cache')) { + Cache::deleteAllCache(); + } + self::deleteAllSessionCache(); + $lockFile = getVideosDir() . '.deleteALLCache.lock'; + if (file_exists($lockFile) && filectime($lockFile) > strtotime('-5 minutes')) { + _error_log('clearCache is in progress ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + return false; + } + $start = microtime(true); + _error_log('deleteALLCache starts '); + global $__getAVideoCache; + unset($__getAVideoCache); + //_error_log('deleteALLCache: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $tmpDir = self::getCacheDir('', false); + + $newtmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . uniqid(); + _error_log("deleteALLCache rename($tmpDir, $newtmpDir) "); + rename($tmpDir, $newtmpDir); + if (is_dir($tmpDir)) { + _error_log('deleteALLCache 1 rmdir ' . $tmpDir); + rrmdir($tmpDir); + } elseif (preg_match('/videos.cache/', $newtmpDir)) { + // only delete if it is on the videos dir. otherwise it is on the /tmp dit and the system will delete it + _error_log('deleteALLCache 2 rmdir ' . $newtmpDir); + rrmdirCommandLine($newtmpDir, true); + } + self::setLastDeleteALLCacheTime(); + unlink($lockFile); + $end = microtime(true) - $start; + _error_log("deleteALLCache end in {$end} seconds"); + return true; + } + + public static function getCacheDir($filename = '', $createDir=true) + { + global $_getCacheDir, $global; + + if (!isset($_getCacheDir)) { + $_getCacheDir = []; + } + + if (!empty($_getCacheDir[$filename])) { + return $_getCacheDir[$filename]; + } + + $tmpDir = getTmpDir(); + $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $tmpDir .= "YPTObjectCache" . DIRECTORY_SEPARATOR; + + $filename = self::cleanCacheName($filename); + if (!empty($filename)) { + $tmpDir .= $filename . DIRECTORY_SEPARATOR; + + $domain = getDomain(); + // make sure you separete http and https cache + $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http'; + + $tmpDir .= "{$protocol}_{$domain}" . DIRECTORY_SEPARATOR; + + if (class_exists("User_Location")) { + $loc = User_Location::getThisUserLocation(); + if (!empty($loc) && !empty($loc['country_code']) && $loc['country_code']!='-') { + $tmpDir .= $loc['country_code'] . DIRECTORY_SEPARATOR; + } + } + + if (User::isLogged()) { + if (User::isAdmin()) { + $tmpDir .= 'admin_' . md5("admin" . $global['salt']) . DIRECTORY_SEPARATOR; + } else { + $tmpDir .= 'user_' . md5("user" . $global['salt']) . DIRECTORY_SEPARATOR; + } + } else { + $tmpDir .= 'notlogged_' . md5("notlogged" . $global['salt']) . DIRECTORY_SEPARATOR; + } + } + $tmpDir = fixPath($tmpDir); + if ($createDir) { + make_path($tmpDir); + } + if (!file_exists($tmpDir . "index.html") && is_writable($tmpDir)) {// to avoid search into the directory + _file_put_contents($tmpDir . "index.html", time()); + } + + $_getCacheDir[$filename] = $tmpDir; + return $tmpDir; + } + + public static function getCacheFileName($name, $createDir=true) + { + global $global; + $tmpDir = self::getCacheDir($name, $createDir); + $uniqueHash = md5($name . $global['salt']); // add salt for security reasons + return $tmpDir . $uniqueHash . '.cache'; + } + + public static function deleteCacheFromPattern($name) + { + if (empty($name)) { + return false; + } + $tmpDir = getTmpDir(); + //_error_log('deleteCacheFromPattern: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $name = self::cleanCacheName($name); + $ignoreLocationDirectoryName = (strpos($name, DIRECTORY_SEPARATOR) !== false); + $filePattern = $tmpDir . DIRECTORY_SEPARATOR . $name; + foreach (glob("{$filePattern}*") as $filename) { + unlink($filename); + } + self::deleteSessionCache($name); + } + + /** + * Make sure you start the session before any output + * @param type $name + * @param type $value + */ + public static function setSessionCache($name, $value) + { + $name = self::cleanCacheName($name); + _session_start(); + $_SESSION['user']['sessionCache'][$name]['value'] = json_encode($value); + $_SESSION['user']['sessionCache'][$name]['time'] = time(); + if (empty($_SESSION['user']['sessionCache']['time'])) { + $_SESSION['user']['sessionCache']['time'] = time(); + } + } + + /** + * + * @param type $name + * @param type $lifetime, if is = 0 it is unlimited + * @return type + */ + public static function getSessionCache($name, $lifetime = 60) + { + $name = self::cleanCacheName($name); + if (!empty($_GET['lifetime'])) { + $lifetime = intval($_GET['lifetime']); + } + if (!empty($_SESSION['user']['sessionCache'][$name])) { + if ((empty($lifetime) || time() - $lifetime <= $_SESSION['user']['sessionCache'][$name]['time'])) { + $c = $_SESSION['user']['sessionCache'][$name]['value']; + self::setLastUsedCacheMode("Session cache \$_SESSION['user']['sessionCache'][$name]"); + $json = _json_decode($c); + if (is_string($json) && strtolower($json) === 'false') { + $json = false; + } + return $json; + } + _session_start(); + unset($_SESSION['user']['sessionCache'][$name]); + } + return null; + } + + public static function clearSessionCache() + { + unset($_SESSION['user']['sessionCache']); + } + + private static function getLastDeleteALLCacheTimeFile() + { + $tmpDir = getTmpDir(); + $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/"; + $tmpDir .= "lastDeleteALLCacheTime.cache"; + return $tmpDir; + } + + public static function setLastDeleteALLCacheTime() + { + $file = self::getLastDeleteALLCacheTimeFile(); + //_error_log("ObjectYPT::setLastDeleteALLCacheTime {$file}"); + return file_put_contents($file, time()); + } + + public static function getLastDeleteALLCacheTime() + { + global $getLastDeleteALLCacheTime; + if (empty($getLastDeleteALLCacheTime)) { + $getLastDeleteALLCacheTime = (int) @file_get_contents(self::getLastDeleteALLCacheTimeFile(), time()); + } + return $getLastDeleteALLCacheTime; + } + + public static function checkSessionCacheBasedOnLastDeleteALLCacheTime() + { + /* + var_dump( + $session_var['time'], + self::getLastDeleteALLCacheTime(), + humanTiming($session_var['time']), + humanTiming(self::getLastDeleteALLCacheTime()), + $session_var['time'] <= self::getLastDeleteALLCacheTime()); + * + */ + if (empty($_SESSION['user']['sessionCache']['time']) || $_SESSION['user']['sessionCache']['time'] <= self::getLastDeleteALLCacheTime()) { + self::deleteAllSessionCache(); + return false; + } + return true; + } + + public static function deleteSessionCache($name) + { + $name = self::cleanCacheName($name); + _session_start(); + $_SESSION['user']['sessionCache'][$name] = null; + unset($_SESSION['user']['sessionCache'][$name]); + } + + public static function deleteAllSessionCache() + { + _session_start(); + unset($_SESSION['user']['sessionCache']); + return empty($_SESSION['user']['sessionCache']); + } + + public function tableExists() + { + return self::isTableInstalled(); + } + + public static function isTableInstalled($tableName = "") + { + global $global, $tableExists; + if (empty($tableName)) { + $tableName = static::getTableName(); + } + if (empty($tableName)) { + return false; + } + if (!isset($tableExists[$tableName])) { + $sql = "SHOW TABLES LIKE '" . $tableName . "'"; + //_error_log("isTableInstalled: ({$sql})"); + $res = sqlDAL::readSql($sql); + $result = sqlDal::num_rows($res); + sqlDAL::close($res); + $tableExists[$tableName] = !empty($result); + } + return $tableExists[$tableName]; + } + + public static function clientTimezoneToDatabaseTimezone($clientDate) + { + if (!preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/', $clientDate)) { + return $clientDate; + } + + global $timezoneOriginal; + $currentTimezone = date_default_timezone_get(); + $time = strtotime($clientDate); + date_default_timezone_set($timezoneOriginal); + + $dbDate = date('Y-m-d H:i:s', $time); + + date_default_timezone_set($currentTimezone); + return $dbDate; + } +} + +//abstract class Object extends ObjectYPT{}; diff --git a/objects/aVideoEncoder.json.php b/objects/aVideoEncoder.json.php index f9bf0cd081..b6df5e83a3 100644 --- a/objects/aVideoEncoder.json.php +++ b/objects/aVideoEncoder.json.php @@ -1,223 +1,224 @@ -error = true; - -global $global, $config; -if (!isset($global['systemRootPath'])) { - require_once '../videos/configuration.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(); -} -if(!isset($_REQUEST['encodedPass'])){ - $_REQUEST['encodedPass'] = 1; -} -useVideoHashOrLogin(); -if (!User::canUpload()) { - _error_log("aVideoEncoder.json: Permission denied to receive a file: " . json_encode($_REQUEST)); - $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)) { - $paths = Video::getNewVideoFilename(); - $filename = $paths['filename']; - $videoFileName = $video->setFilename($videoFileName); -} - -$paths = Video::getPaths($videoFileName, true); -$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)); - $destinationFile = 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()); -if(!empty($destinationFile)){ - if(file_exists($destinationFile)){ - _error_log("aVideoEncoder.json: Success $destinationFile "); - }else{ - _error_log("aVideoEncoder.json: ERROR $destinationFile "); - } -} -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']); - $strlen = strlen($file); - if ($strlen<20000) { - //it is not a video - return false; - } - _error_log("aVideoEncoder.json: Got the download " . $downloadURL . ' '. humanFileSize($strlen)); - if ($file) { - $_FILES['video']['name'] = basename($downloadURL); - - $temp = Video::getStoragePath()."cache/tmpFile/" . $_FILES['video']['name']; - make_path($temp); - $bytesSaved = file_put_contents($temp, $file); - if($bytesSaved){ - _error_log("aVideoEncoder.json: saved " . $temp . ' '. humanFileSize($bytesSaved)); - return $temp; - }else{ - _error_log("aVideoEncoder.json: ERROR on save file " . $temp ); - } - } - return false; -} +error = true; + +global $global, $config; +if (!isset($global['systemRootPath'])) { + require_once '../videos/configuration.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(); +} +if (!isset($_REQUEST['encodedPass'])) { + $_REQUEST['encodedPass'] = 1; +} +useVideoHashOrLogin(); +if (!User::canUpload()) { + _error_log("aVideoEncoder.json: Permission denied to receive a file: " . json_encode($_REQUEST)); + $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)) { + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; + $videoFileName = $video->setFilename($videoFileName); +} + +$paths = Video::getPaths($videoFileName, true); +$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 = [ + 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)); + $destinationFile = 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'] = [$_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()); +if (!empty($destinationFile)) { + if (file_exists($destinationFile)) { + _error_log("aVideoEncoder.json: Success $destinationFile "); + } else { + _error_log("aVideoEncoder.json: ERROR $destinationFile "); + } +} +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']); + $strlen = strlen($file); + if ($strlen<20000) { + //it is not a video + return false; + } + _error_log("aVideoEncoder.json: Got the download " . $downloadURL . ' '. humanFileSize($strlen)); + if ($file) { + $_FILES['video']['name'] = basename($downloadURL); + + $temp = Video::getStoragePath()."cache/tmpFile/" . $_FILES['video']['name']; + make_path($temp); + $bytesSaved = file_put_contents($temp, $file); + if ($bytesSaved) { + _error_log("aVideoEncoder.json: saved " . $temp . ' '. humanFileSize($bytesSaved)); + return $temp; + } else { + _error_log("aVideoEncoder.json: ERROR on save file " . $temp); + } + } + return false; +} diff --git a/objects/aVideoEncoderChunk.json.php b/objects/aVideoEncoderChunk.json.php index 1fdfc12988..0a2f1a3911 100644 --- a/objects/aVideoEncoderChunk.json.php +++ b/objects/aVideoEncoderChunk.json.php @@ -1,25 +1,25 @@ -file = tempnam(sys_get_temp_dir(), 'YTPChunk_'); - -$putdata = fopen("php://input", "r"); -$fp = fopen($obj->file, "w"); - -error_log("aVideoEncoderChunk.json.php: start {$obj->file} "); - -while ($data = fread($putdata, 1024 * 1024)) - fwrite($fp, $data); - -fclose($fp); -fclose($putdata); -sleep(1); -$obj->filesize = filesize($obj->file); - -$json = json_encode($obj); - -error_log("aVideoEncoderChunk.json.php: {$json} "); - -die($json); +file = tempnam(sys_get_temp_dir(), 'YTPChunk_'); + +$putdata = fopen("php://input", "r"); +$fp = fopen($obj->file, "w"); + +error_log("aVideoEncoderChunk.json.php: start {$obj->file} "); + +while ($data = fread($putdata, 1024 * 1024)) { + fwrite($fp, $data); +} + +fclose($fp); +fclose($putdata); +sleep(1); +$obj->filesize = filesize($obj->file); + +$json = json_encode($obj); + +error_log("aVideoEncoderChunk.json.php: {$json} "); + +die($json); diff --git a/objects/aVideoEncoderNotifyIsDone.json.php b/objects/aVideoEncoderNotifyIsDone.json.php index 647707e54f..39b84a8a1d 100644 --- a/objects/aVideoEncoderNotifyIsDone.json.php +++ b/objects/aVideoEncoderNotifyIsDone.json.php @@ -1,72 +1,71 @@ -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)); -} - -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->getType() == 'audio' && AVideoPlugin::isEnabledByName('MP4ThumbsAndGif')){ - $videoFileName = $video->getFilename(); - MP4ThumbsAndGif::getImage($videoFileName, 'jpg', $video_id); - Video::deleteThumbs($videoFileName); - Video::deleteGifAndWebp($videoFileName); -} - -$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); -AVideoPlugin::onEncoderNotifyIsDone($video_id); -AVideoPlugin::afterNewVideo($video_id); -die(json_encode($obj)); - -/* -_error_log(print_r($_POST, true)); -_error_log(print_r($_FILES, true)); -var_dump($_POST, $_FILES); -*/ +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)); +} + +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->getType() == 'audio' && AVideoPlugin::isEnabledByName('MP4ThumbsAndGif')) { + $videoFileName = $video->getFilename(); + MP4ThumbsAndGif::getImage($videoFileName, 'jpg', $video_id); + Video::deleteThumbs($videoFileName); + Video::deleteGifAndWebp($videoFileName); +} + +$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); +AVideoPlugin::onEncoderNotifyIsDone($video_id); +AVideoPlugin::afterNewVideo($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 f3e0421b1b..4c0084c267 100644 --- a/objects/aVideoEncoderReceiveImage.json.php +++ b/objects/aVideoEncoderReceiveImage.json.php @@ -1,180 +1,179 @@ -error = true; - -global $global, $config; -if (!isset($global['systemRootPath'])) { - require_once '../videos/configuration.php'; -} -/* -ini_set('display_errors', 1); -ini_set('display_startup_errors', 1); -error_reporting(E_ALL); - */ - -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)); -} - -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)); -// 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']; - -$videoFileName = $video->getFilename(); -$paths = Video::getPaths($videoFileName, true); -$destination_local = "{$paths['path']}{$videoFileName}"; - -_error_log("ReceiveImage: videoFilename = [$videoFileName] destination_local = {$destination_local} Encoder receiving post " . json_encode($_FILES)); - -$obj->jpgDest = "{$destination_local}.jpg"; -if(!empty($_REQUEST['downloadURL_image']) ){ - $content = url_get_contents($_REQUEST['downloadURL_image']); - $obj->jpgDestSize = _file_put_contents($obj->jpgDest, $content); - _error_log("ReceiveImage: download {$_REQUEST['downloadURL_image']} to {$obj->jpgDest} ". humanFileSize($obj->jpgDestSize)); -} else 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)) { - if(!rename($_FILES['image']['tmp_name'], $obj->jpgDest)){ - if(!copy($_FILES['image']['tmp_name'], $obj->jpgDest)){ - if(!file_exists($_FILES['image']['tmp_name'])){ - $obj->msg = print_r(sprintf(__("Could not move image file because it does not exits %s => [%s]"), $_FILES['image']['tmp_name'], $obj->jpgDest), true); - }else{ - $obj->msg = print_r(sprintf(__("Could not move image file %s => [%s]"), $_FILES['image']['tmp_name'], $obj->jpgDest), 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($_REQUEST['downloadURL_spectrumimage']) ){ - $content = url_get_contents($_REQUEST['downloadURL_spectrumimage']); - $obj->jpgSpectrumDestSize = _file_put_contents($obj->jpgSpectrumDest, $content); - _error_log("ReceiveImage: download {$_REQUEST['downloadURL_spectrumimage']} {$obj->jpgDestSize}"); -} else 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->jpgSpectrumDestSize = 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->jpgSpectrumDestSize) !== 42342) { - _error_log("ReceiveImage: file is not an error image " . filesize($obj->jpgDest)); - } - } - } -} - -$obj->gifDest = "{$destination_local}.gif"; -if(!empty($_REQUEST['downloadURL_gifimage']) ){ - $content = url_get_contents($_REQUEST['downloadURL_gifimage']); - $obj->gifDestSize = file_put_contents($obj->gifDest, $content); - _error_log("ReceiveImage: download {$_REQUEST['downloadURL_gifimage']} {$obj->gifDestSize}"); -} else 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($_REQUEST['downloadURL_webpimage']) ){ - $content = url_get_contents($_REQUEST['downloadURL_webpimage']); - $obj->webpDestSize = file_put_contents($obj->webpDest, $content); - _error_log("ReceiveImage: download {$_REQUEST['downloadURL_webpimage']} {$obj->webpDestSize}"); -} else 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); -AVideoPlugin::onEncoderReceiveImage($videos_id); - -$obj->error = false; -$obj->video_id = $videos_id; -$v = new Video('', '', $videos_id); -$obj->video_id_hash = $v->getVideoIdHash(); - -$json = json_encode($obj); -_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); -*/ +error = true; + +global $global, $config; +if (!isset($global['systemRootPath'])) { + require_once '../videos/configuration.php'; +} +/* +ini_set('display_errors', 1); +ini_set('display_startup_errors', 1); +error_reporting(E_ALL); + */ + +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)); +} + +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)); +// 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']; + +$videoFileName = $video->getFilename(); +$paths = Video::getPaths($videoFileName, true); +$destination_local = "{$paths['path']}{$videoFileName}"; + +_error_log("ReceiveImage: videoFilename = [$videoFileName] destination_local = {$destination_local} Encoder receiving post " . json_encode($_FILES)); + +$obj->jpgDest = "{$destination_local}.jpg"; +if (!empty($_REQUEST['downloadURL_image'])) { + $content = url_get_contents($_REQUEST['downloadURL_image']); + $obj->jpgDestSize = _file_put_contents($obj->jpgDest, $content); + _error_log("ReceiveImage: download {$_REQUEST['downloadURL_image']} to {$obj->jpgDest} ". humanFileSize($obj->jpgDestSize)); +} elseif (!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)) { + if (!rename($_FILES['image']['tmp_name'], $obj->jpgDest)) { + if (!copy($_FILES['image']['tmp_name'], $obj->jpgDest)) { + if (!file_exists($_FILES['image']['tmp_name'])) { + $obj->msg = print_r(sprintf(__("Could not move image file because it does not exits %s => [%s]"), $_FILES['image']['tmp_name'], $obj->jpgDest), true); + } else { + $obj->msg = print_r(sprintf(__("Could not move image file %s => [%s]"), $_FILES['image']['tmp_name'], $obj->jpgDest), 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($_REQUEST['downloadURL_spectrumimage'])) { + $content = url_get_contents($_REQUEST['downloadURL_spectrumimage']); + $obj->jpgSpectrumDestSize = _file_put_contents($obj->jpgSpectrumDest, $content); + _error_log("ReceiveImage: download {$_REQUEST['downloadURL_spectrumimage']} {$obj->jpgDestSize}"); +} elseif (!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->jpgSpectrumDestSize = 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->jpgSpectrumDestSize) !== 42342) { + _error_log("ReceiveImage: file is not an error image " . filesize($obj->jpgDest)); + } + } + } +} + +$obj->gifDest = "{$destination_local}.gif"; +if (!empty($_REQUEST['downloadURL_gifimage'])) { + $content = url_get_contents($_REQUEST['downloadURL_gifimage']); + $obj->gifDestSize = file_put_contents($obj->gifDest, $content); + _error_log("ReceiveImage: download {$_REQUEST['downloadURL_gifimage']} {$obj->gifDestSize}"); +} elseif (!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($_REQUEST['downloadURL_webpimage'])) { + $content = url_get_contents($_REQUEST['downloadURL_webpimage']); + $obj->webpDestSize = file_put_contents($obj->webpDest, $content); + _error_log("ReceiveImage: download {$_REQUEST['downloadURL_webpimage']} {$obj->webpDestSize}"); +} elseif (!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); +AVideoPlugin::onEncoderReceiveImage($videos_id); + +$obj->error = false; +$obj->video_id = $videos_id; +$v = new Video('', '', $videos_id); +$obj->video_id_hash = $v->getVideoIdHash(); + +$json = json_encode($obj); +_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 59fc078307..f99350db49 100644 --- a/objects/aVideoQueueEncoder.json.php +++ b/objects/aVideoQueueEncoder.json.php @@ -1,183 +1,179 @@ -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'])); - $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['inputAutoHLS'] = 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; -} +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 = ['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'])); + $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 = []; + $postFields = []; + if ($video->getType() == 'video') { + if (AVideoPlugin::isEnabledByName("VideoHLS")) { + $postFields['inputAutoHLS'] = 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/ajaxErrorCatcher.php b/objects/ajaxErrorCatcher.php index 22bfc876ef..3ca516646b 100644 --- a/objects/ajaxErrorCatcher.php +++ b/objects/ajaxErrorCatcher.php @@ -1,7 +1,5 @@ - +'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_US','label'=>'English (United States)', 'flag'=>'us'), - array('value'=>'en_GB','label'=>'English (United Kingdom)', 'flag'=>'gb'), - 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_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['flag2Lang'][$value['flag']] = $value['value']; - $global['langs_codes_values'][] = $value['value']; - $global['langs_codes_values_withdot'][] = '.'.$value['value']; -} -$global['flag2Lang']['en'] = 'en_US'; -$global['flag2Lang']['us'] = 'en_US'; - -$global['js_availableLangs'] = 'var availableLangs = ' . json_encode($global['langs_codes']) . ';'; + 'af_NA','label' => 'Afrikaans (Namibia)', 'flag' => 'na'], + ['value' => 'af_ZA','label' => 'Afrikaans (South Africa)', 'flag' => 'za'], + ['value' => 'af','label' => 'Afrikaans', 'flag' => 'af'], + ['value' => 'ak_GH','label' => 'Akan (Ghana)', 'flag' => 'gh'], + ['value' => 'ak','label' => 'Akan', 'flag' => 'ak'], + ['value' => 'sq_AL','label' => 'Albanian (Albania)', 'flag' => 'al'], + ['value' => 'sq','label' => 'Albanian', 'flag' => 'sq'], + ['value' => 'am_ET','label' => 'Amharic (Ethiopia)', 'flag' => 'et'], + ['value' => 'am','label' => 'Amharic', 'flag' => 'am'], + ['value' => 'ar_DZ','label' => 'Arabic (Algeria)', 'flag' => 'dz'], + ['value' => 'ar_BH','label' => 'Arabic (Bahrain)', 'flag' => 'bh'], + ['value' => 'ar_EG','label' => 'Arabic (Egypt)', 'flag' => 'eg'], + ['value' => 'ar_IQ','label' => 'Arabic (Iraq)', 'flag' => 'iq'], + ['value' => 'ar_JO','label' => 'Arabic (Jordan)', 'flag' => 'jo'], + ['value' => 'ar_KW','label' => 'Arabic (Kuwait)', 'flag' => 'kw'], + ['value' => 'ar_LB','label' => 'Arabic (Lebanon)', 'flag' => 'lb'], + ['value' => 'ar_LY','label' => 'Arabic (Libya)', 'flag' => 'ly'], + ['value' => 'ar_MA','label' => 'Arabic (Morocco)', 'flag' => 'ma'], + ['value' => 'ar_OM','label' => 'Arabic (Oman)', 'flag' => 'om'], + ['value' => 'ar_QA','label' => 'Arabic (Qatar)', 'flag' => 'qa'], + ['value' => 'ar_SA','label' => 'Arabic (Saudi Arabia)', 'flag' => 'sa'], + ['value' => 'ar_SD','label' => 'Arabic (Sudan)', 'flag' => 'sd'], + ['value' => 'ar_SY','label' => 'Arabic (Syria)', 'flag' => 'sy'], + ['value' => 'ar_TN','label' => 'Arabic (Tunisia)', 'flag' => 'tn'], + ['value' => 'ar_AE','label' => 'Arabic (United Arab Emirates)', 'flag' => 'ae'], + ['value' => 'ar_YE','label' => 'Arabic (Yemen)', 'flag' => 'ye'], + ['value' => 'ar','label' => 'Arabic', 'flag' => 'ar'], + ['value' => 'hy_AM','label' => 'Armenian (Armenia)', 'flag' => 'am'], + ['value' => 'hy','label' => 'Armenian', 'flag' => 'hy'], + ['value' => 'as_IN','label' => 'Assamese (India)', 'flag' => 'in'], + ['value' => 'as','label' => 'Assamese', 'flag' => 'as'], + ['value' => 'asa_TZ','label' => 'Asu (Tanzania)', 'flag' => 'tz'], + ['value' => 'asa','label' => 'Asu', 'flag' => 'asa'], + ['value' => 'az_Cyrl','label' => 'Azerbaijani (Cyrillic)', 'flag' => 'cyrl'], + ['value' => 'az_Cyrl_AZ','label' => 'Azerbaijani (Cyrillic, Azerbaijan)', 'flag' => 'az'], + ['value' => 'az_Latn','label' => 'Azerbaijani (Latin)', 'flag' => 'latn'], + ['value' => 'az_Latn_AZ','label' => 'Azerbaijani (Latin, Azerbaijan)', 'flag' => 'az'], + ['value' => 'az','label' => 'Azerbaijani', 'flag' => 'az'], + ['value' => 'bm_ML','label' => 'Bambara (Mali)', 'flag' => 'ml'], + ['value' => 'bm','label' => 'Bambara', 'flag' => 'bm'], + ['value' => 'eu_ES','label' => 'Basque (Spain)', 'flag' => 'es'], + ['value' => 'eu','label' => 'Basque', 'flag' => 'eu'], + ['value' => 'be_BY','label' => 'Belarusian (Belarus)', 'flag' => 'by'], + ['value' => 'be','label' => 'Belarusian', 'flag' => 'be'], + ['value' => 'bem_ZM','label' => 'Bemba (Zambia)', 'flag' => 'zm'], + ['value' => 'bem','label' => 'Bemba', 'flag' => 'bem'], + ['value' => 'bez_TZ','label' => 'Bena (Tanzania)', 'flag' => 'tz'], + ['value' => 'bez','label' => 'Bena', 'flag' => 'bez'], + ['value' => 'bn_BD','label' => 'Bengali (Bangladesh)', 'flag' => 'bd'], + ['value' => 'bn_IN','label' => 'Bengali (India)', 'flag' => 'in'], + ['value' => 'bn','label' => 'Bengali', 'flag' => 'bn'], + ['value' => 'bs_BA','label' => 'Bosnian (Bosnia and Herzegovina)', 'flag' => 'ba'], + ['value' => 'bs','label' => 'Bosnian', 'flag' => 'bs'], + ['value' => 'bg_BG','label' => 'Bulgarian (Bulgaria)', 'flag' => 'bg'], + ['value' => 'bg','label' => 'Bulgarian', 'flag' => 'bg'], + ['value' => 'my_MM','label' => 'Burmese (Myanmar [Burma])', 'flag' => 'mm'], + ['value' => 'my','label' => 'Burmese', 'flag' => 'my'], + ['value' => 'yue_Hant_HK','label' => 'Cantonese (Traditional, Hong Kong SAR China)', 'flag' => 'hk'], + ['value' => 'ca_ES','label' => 'Catalan (Spain)', 'flag' => 'es'], + ['value' => 'ca','label' => 'Catalan', 'flag' => 'ca'], + ['value' => 'tzm_Latn','label' => 'Central Morocco Tamazight (Latin)', 'flag' => 'latn'], + ['value' => 'tzm_Latn_MA','label' => 'Central Morocco Tamazight (Latin, Morocco)', 'flag' => 'ma'], + ['value' => 'tzm','label' => 'Central Morocco Tamazight', 'flag' => 'tzm'], + ['value' => 'chr_US','label' => 'Cherokee (United States)', 'flag' => 'us'], + ['value' => 'chr','label' => 'Cherokee', 'flag' => 'chr'], + ['value' => 'cgg_UG','label' => 'Chiga (Uganda)', 'flag' => 'ug'], + ['value' => 'cgg','label' => 'Chiga', 'flag' => 'cgg'], + ['value' => 'zh_Hans','label' => 'Chinese (Simplified Han)', 'flag' => 'hans'], + ['value' => 'zh_Hans_CN','label' => 'Chinese (Simplified Han, China)', 'flag' => 'cn'], + ['value' => 'zh_Hans_HK','label' => 'Chinese (Simplified Han, Hong Kong SAR China)', 'flag' => 'hk'], + ['value' => 'zh_Hans_MO','label' => 'Chinese (Simplified Han, Macau SAR China)', 'flag' => 'mo'], + ['value' => 'zh_Hans_SG','label' => 'Chinese (Simplified Han, Singapore)', 'flag' => 'sg'], + ['value' => 'zh_Hant','label' => 'Chinese (Traditional Han)', 'flag' => 'hant'], + ['value' => 'zh_Hant_HK','label' => 'Chinese (Traditional Han, Hong Kong SAR China)', 'flag' => 'hk'], + ['value' => 'zh_Hant_MO','label' => 'Chinese (Traditional Han, Macau SAR China)', 'flag' => 'mo'], + ['value' => 'zh_Hant_TW','label' => 'Chinese (Traditional Han, Taiwan)', 'flag' => 'tw'], + ['value' => 'zh','label' => 'Chinese', 'flag' => 'cn'], + ['value' => 'kw_GB','label' => 'Cornish (United Kingdom)', 'flag' => 'gb'], + ['value' => 'kw','label' => 'Cornish', 'flag' => 'kw'], + ['value' => 'hr_HR','label' => 'Croatian (Croatia)', 'flag' => 'hr'], + ['value' => 'hr','label' => 'Croatian', 'flag' => 'hr'], + ['value' => 'cs_CZ','label' => 'Czech (Czech Republic)', 'flag' => 'cz'], + ['value' => 'cs','label' => 'Czech', 'flag' => 'cz'], + ['value' => 'da_DK','label' => 'Danish (Denmark)', 'flag' => 'dk'], + ['value' => 'da','label' => 'Danish', 'flag' => 'da'], + ['value' => 'nl_BE','label' => 'Dutch (Belgium)', 'flag' => 'be'], + ['value' => 'nl_NL','label' => 'Dutch (Netherlands)', 'flag' => 'nl'], + ['value' => 'nl','label' => 'Dutch', 'flag' => 'nl'], + ['value' => 'ebu_KE','label' => 'Embu (Kenya)', 'flag' => 'ke'], + ['value' => 'ebu','label' => 'Embu', 'flag' => 'ebu'], + ['value' => 'en_US','label' => 'English (United States)', 'flag' => 'us'], + ['value' => 'en_GB','label' => 'English (United Kingdom)', 'flag' => 'gb'], + ['value' => 'en_AS','label' => 'English (American Samoa)', 'flag' => 'as'], + ['value' => 'en_AU','label' => 'English (Australia)', 'flag' => 'au'], + ['value' => 'en_BE','label' => 'English (Belgium)', 'flag' => 'be'], + ['value' => 'en_BZ','label' => 'English (Belize)', 'flag' => 'bz'], + ['value' => 'en_BW','label' => 'English (Botswana)', 'flag' => 'bw'], + ['value' => 'en_CA','label' => 'English (Canada)', 'flag' => 'ca'], + ['value' => 'en_GU','label' => 'English (Guam)', 'flag' => 'gu'], + ['value' => 'en_HK','label' => 'English (Hong Kong SAR China)', 'flag' => 'hk'], + ['value' => 'en_IN','label' => 'English (India)', 'flag' => 'in'], + ['value' => 'en_IE','label' => 'English (Ireland)', 'flag' => 'ie'], + ['value' => 'en_IL','label' => 'English (Israel)', 'flag' => 'il'], + ['value' => 'en_JM','label' => 'English (Jamaica)', 'flag' => 'jm'], + ['value' => 'en_MT','label' => 'English (Malta)', 'flag' => 'mt'], + ['value' => 'en_MH','label' => 'English (Marshall Islands)', 'flag' => 'mh'], + ['value' => 'en_MU','label' => 'English (Mauritius)', 'flag' => 'mu'], + ['value' => 'en_NA','label' => 'English (Namibia)', 'flag' => 'na'], + ['value' => 'en_NZ','label' => 'English (New Zealand)', 'flag' => 'nz'], + ['value' => 'en_MP','label' => 'English (Northern Mariana Islands)', 'flag' => 'mp'], + ['value' => 'en_PK','label' => 'English (Pakistan)', 'flag' => 'pk'], + ['value' => 'en_PH','label' => 'English (Philippines)', 'flag' => 'ph'], + ['value' => 'en_SG','label' => 'English (Singapore)', 'flag' => 'sg'], + ['value' => 'en_ZA','label' => 'English (South Africa)', 'flag' => 'za'], + ['value' => 'en_TT','label' => 'English (Trinidad and Tobago)', 'flag' => 'tt'], + ['value' => 'en_UM','label' => 'English (U.S. Minor Outlying Islands)', 'flag' => 'um'], + ['value' => 'en_VI','label' => 'English (U.S. Virgin Islands)', 'flag' => 'vi'], + ['value' => 'en_ZW','label' => 'English (Zimbabwe)', 'flag' => 'zw'], + ['value' => 'en','label' => 'English', 'flag' => 'us'], + ['value' => 'eo','label' => 'Esperanto', 'flag' => 'eo'], + ['value' => 'et_EE','label' => 'Estonian (Estonia)', 'flag' => 'ee'], + ['value' => 'et','label' => 'Estonian', 'flag' => 'et'], + ['value' => 'ee_GH','label' => 'Ewe (Ghana)', 'flag' => 'gh'], + ['value' => 'ee_TG','label' => 'Ewe (Togo)', 'flag' => 'tg'], + ['value' => 'ee','label' => 'Ewe', 'flag' => 'ee'], + ['value' => 'fo_FO','label' => 'Faroese (Faroe Islands)', 'flag' => 'fo'], + ['value' => 'fo','label' => 'Faroese', 'flag' => 'fo'], + ['value' => 'fil_PH','label' => 'Filipino (Philippines)', 'flag' => 'ph'], + ['value' => 'fil','label' => 'Filipino', 'flag' => 'fil'], + ['value' => 'fi_FI','label' => 'Finnish (Finland)', 'flag' => 'fi'], + ['value' => 'fi','label' => 'Finnish', 'flag' => 'fi'], + ['value' => 'fr_BE','label' => 'French (Belgium)', 'flag' => 'be'], + ['value' => 'fr_BJ','label' => 'French (Benin)', 'flag' => 'bj'], + ['value' => 'fr_BF','label' => 'French (Burkina Faso)', 'flag' => 'bf'], + ['value' => 'fr_BI','label' => 'French (Burundi)', 'flag' => 'bi'], + ['value' => 'fr_CM','label' => 'French (Cameroon)', 'flag' => 'cm'], + ['value' => 'fr_CA','label' => 'French (Canada)', 'flag' => 'ca'], + ['value' => 'fr_CF','label' => 'French (Central African Republic)', 'flag' => 'cf'], + ['value' => 'fr_TD','label' => 'French (Chad)', 'flag' => 'td'], + ['value' => 'fr_KM','label' => 'French (Comoros)', 'flag' => 'km'], + ['value' => 'fr_CG','label' => 'French (Congo - Brazzaville)', 'flag' => 'cg'], + ['value' => 'fr_CD','label' => 'French (Congo - Kinshasa)', 'flag' => 'cd'], + ['value' => 'fr_CI','label' => 'French (Côte d’Ivoire)', 'flag' => 'ci'], + ['value' => 'fr_DJ','label' => 'French (Djibouti)', 'flag' => 'dj'], + ['value' => 'fr_GQ','label' => 'French (Equatorial Guinea)', 'flag' => 'gq'], + ['value' => 'fr_FR','label' => 'French (France)', 'flag' => 'fr'], + ['value' => 'fr_GA','label' => 'French (Gabon)', 'flag' => 'ga'], + ['value' => 'fr_GP','label' => 'French (Guadeloupe)', 'flag' => 'gp'], + ['value' => 'fr_GN','label' => 'French (Guinea)', 'flag' => 'gn'], + ['value' => 'fr_LU','label' => 'French (Luxembourg)', 'flag' => 'lu'], + ['value' => 'fr_MG','label' => 'French (Madagascar)', 'flag' => 'mg'], + ['value' => 'fr_ML','label' => 'French (Mali)', 'flag' => 'ml'], + ['value' => 'fr_MQ','label' => 'French (Martinique)', 'flag' => 'mq'], + ['value' => 'fr_MC','label' => 'French (Monaco)', 'flag' => 'mc'], + ['value' => 'fr_NE','label' => 'French (Niger)', 'flag' => 'ne'], + ['value' => 'fr_RW','label' => 'French (Rwanda)', 'flag' => 'rw'], + ['value' => 'fr_RE','label' => 'French (Réunion)', 'flag' => 're'], + ['value' => 'fr_BL','label' => 'French (Saint Barthélemy)', 'flag' => 'bl'], + ['value' => 'fr_MF','label' => 'French (Saint Martin)', 'flag' => 'mf'], + ['value' => 'fr_SN','label' => 'French (Senegal)', 'flag' => 'sn'], + ['value' => 'fr_CH','label' => 'French (Switzerland)', 'flag' => 'ch'], + ['value' => 'fr_TG','label' => 'French (Togo)', 'flag' => 'tg'], + ['value' => 'fr','label' => 'French', 'flag' => 'fr'], + ['value' => 'ff_SN','label' => 'Fulah (Senegal)', 'flag' => 'sn'], + ['value' => 'ff','label' => 'Fulah', 'flag' => 'ff'], + ['value' => 'gl_ES','label' => 'Galician (Spain)', 'flag' => 'es'], + ['value' => 'gl','label' => 'Galician', 'flag' => 'gl'], + ['value' => 'lg_UG','label' => 'Ganda (Uganda)', 'flag' => 'ug'], + ['value' => 'lg','label' => 'Ganda', 'flag' => 'lg'], + ['value' => 'ka_GE','label' => 'Georgian (Georgia)', 'flag' => 'ge'], + ['value' => 'ka','label' => 'Georgian', 'flag' => 'ka'], + ['value' => 'de_AT','label' => 'German (Austria)', 'flag' => 'at'], + ['value' => 'de_BE','label' => 'German (Belgium)', 'flag' => 'be'], + ['value' => 'de_DE','label' => 'German (Germany)', 'flag' => 'de'], + ['value' => 'de_LI','label' => 'German (Liechtenstein)', 'flag' => 'li'], + ['value' => 'de_LU','label' => 'German (Luxembourg)', 'flag' => 'lu'], + ['value' => 'de_CH','label' => 'German (Switzerland)', 'flag' => 'ch'], + ['value' => 'de','label' => 'German', 'flag' => 'de'], + ['value' => 'el_CY','label' => 'Greek (Cyprus)', 'flag' => 'cy'], + ['value' => 'el_GR','label' => 'Greek (Greece)', 'flag' => 'gr'], + ['value' => 'el','label' => 'Greek', 'flag' => 'gr'], + ['value' => 'gu_IN','label' => 'Gujarati (India)', 'flag' => 'in'], + ['value' => 'gu','label' => 'Gujarati', 'flag' => 'gu'], + ['value' => 'guz_KE','label' => 'Gusii (Kenya)', 'flag' => 'ke'], + ['value' => 'guz','label' => 'Gusii', 'flag' => 'guz'], + ['value' => 'ha_Latn','label' => 'Hausa (Latin)', 'flag' => 'latn'], + ['value' => 'ha_Latn_GH','label' => 'Hausa (Latin, Ghana)', 'flag' => 'gh'], + ['value' => 'ha_Latn_NE','label' => 'Hausa (Latin, Niger)', 'flag' => 'ne'], + ['value' => 'ha_Latn_NG','label' => 'Hausa (Latin, Nigeria)', 'flag' => 'ng'], + ['value' => 'ha','label' => 'Hausa', 'flag' => 'ha'], + ['value' => 'haw_US','label' => 'Hawaiian (United States)', 'flag' => 'us'], + ['value' => 'haw','label' => 'Hawaiian', 'flag' => 'haw'], + ['value' => 'he_IL','label' => 'Hebrew (Israel)', 'flag' => 'il'], + ['value' => 'he','label' => 'Hebrew', 'flag' => 'il'], + ['value' => 'hi_IN','label' => 'Hindi (India)', 'flag' => 'in'], + ['value' => 'hi','label' => 'Hindi', 'flag' => 'hi'], + ['value' => 'hu_HU','label' => 'Hungarian (Hungary)', 'flag' => 'hu'], + ['value' => 'hu','label' => 'Hungarian', 'flag' => 'hu'], + ['value' => 'is_IS','label' => 'Icelandic (Iceland)', 'flag' => 'is'], + ['value' => 'is','label' => 'Icelandic', 'flag' => 'is'], + ['value' => 'ig_NG','label' => 'Igbo (Nigeria)', 'flag' => 'ng'], + ['value' => 'ig','label' => 'Igbo', 'flag' => 'ig'], + ['value' => 'id_ID','label' => 'Indonesian (Indonesia)', 'flag' => 'id'], + ['value' => 'id','label' => 'Indonesian', 'flag' => 'id'], + ['value' => 'ga_IE','label' => 'Irish (Ireland)', 'flag' => 'ie'], + ['value' => 'ga','label' => 'Irish', 'flag' => 'ga'], + ['value' => 'it_IT','label' => 'Italian (Italy)', 'flag' => 'it'], + ['value' => 'it_CH','label' => 'Italian (Switzerland)', 'flag' => 'ch'], + ['value' => 'it','label' => 'Italian', 'flag' => 'it'], + ['value' => 'ja_JP','label' => 'Japanese (Japan)', 'flag' => 'jp'], + ['value' => 'ja','label' => 'Japanese', 'flag' => 'ja'], + ['value' => 'kea_CV','label' => 'Kabuverdianu (Cape Verde)', 'flag' => 'cv'], + ['value' => 'kea','label' => 'Kabuverdianu', 'flag' => 'kea'], + ['value' => 'kab_DZ','label' => 'Kabyle (Algeria)', 'flag' => 'dz'], + ['value' => 'kab','label' => 'Kabyle', 'flag' => 'kab'], + ['value' => 'kl_GL','label' => 'Kalaallisut (Greenland)', 'flag' => 'gl'], + ['value' => 'kl','label' => 'Kalaallisut', 'flag' => 'kl'], + ['value' => 'kln_KE','label' => 'Kalenjin (Kenya)', 'flag' => 'ke'], + ['value' => 'kln','label' => 'Kalenjin', 'flag' => 'kln'], + ['value' => 'kam_KE','label' => 'Kamba (Kenya)', 'flag' => 'ke'], + ['value' => 'kam','label' => 'Kamba', 'flag' => 'kam'], + ['value' => 'kn_IN','label' => 'Kannada (India)', 'flag' => 'in'], + ['value' => 'kn','label' => 'Kannada', 'flag' => 'kn'], + ['value' => 'kk_Cyrl','label' => 'Kazakh (Cyrillic)', 'flag' => 'cyrl'], + ['value' => 'kk_Cyrl_KZ','label' => 'Kazakh (Cyrillic, Kazakhstan)', 'flag' => 'kz'], + ['value' => 'kk','label' => 'Kazakh', 'flag' => 'kk'], + ['value' => 'km_KH','label' => 'Khmer (Cambodia)', 'flag' => 'kh'], + ['value' => 'km','label' => 'Khmer', 'flag' => 'km'], + ['value' => 'ki_KE','label' => 'Kikuyu (Kenya)', 'flag' => 'ke'], + ['value' => 'ki','label' => 'Kikuyu', 'flag' => 'ki'], + ['value' => 'rw_RW','label' => 'Kinyarwanda (Rwanda)', 'flag' => 'rw'], + ['value' => 'rw','label' => 'Kinyarwanda', 'flag' => 'rw'], + ['value' => 'kok_IN','label' => 'Konkani (India)', 'flag' => 'in'], + ['value' => 'kok','label' => 'Konkani', 'flag' => 'kok'], + ['value' => 'ko_KR','label' => 'Korean (South Korea)', 'flag' => 'kr'], + ['value' => 'ko','label' => 'Korean', 'flag' => 'ko'], + ['value' => 'khq_ML','label' => 'Koyra Chiini (Mali)', 'flag' => 'ml'], + ['value' => 'khq','label' => 'Koyra Chiini', 'flag' => 'khq'], + ['value' => 'ses_ML','label' => 'Koyraboro Senni (Mali)', 'flag' => 'ml'], + ['value' => 'ses','label' => 'Koyraboro Senni', 'flag' => 'ses'], + ['value' => 'lag_TZ','label' => 'Langi (Tanzania)', 'flag' => 'tz'], + ['value' => 'lag','label' => 'Langi', 'flag' => 'lag'], + ['value' => 'lv_LV','label' => 'Latvian (Latvia)', 'flag' => 'lv'], + ['value' => 'lv','label' => 'Latvian', 'flag' => 'lv'], + ['value' => 'lt_LT','label' => 'Lithuanian (Lithuania)', 'flag' => 'lt'], + ['value' => 'lt','label' => 'Lithuanian', 'flag' => 'lt'], + ['value' => 'luo_KE','label' => 'Luo (Kenya)', 'flag' => 'ke'], + ['value' => 'luo','label' => 'Luo', 'flag' => 'luo'], + ['value' => 'luy_KE','label' => 'Luyia (Kenya)', 'flag' => 'ke'], + ['value' => 'luy','label' => 'Luyia', 'flag' => 'luy'], + ['value' => 'mk_MK','label' => 'Macedonian (Macedonia)', 'flag' => 'mk'], + ['value' => 'mk','label' => 'Macedonian', 'flag' => 'mk'], + ['value' => 'jmc_TZ','label' => 'Machame (Tanzania)', 'flag' => 'tz'], + ['value' => 'jmc','label' => 'Machame', 'flag' => 'jmc'], + ['value' => 'kde_TZ','label' => 'Makonde (Tanzania)', 'flag' => 'tz'], + ['value' => 'kde','label' => 'Makonde', 'flag' => 'kde'], + ['value' => 'mg_MG','label' => 'Malagasy (Madagascar)', 'flag' => 'mg'], + ['value' => 'mg','label' => 'Malagasy', 'flag' => 'mg'], + ['value' => 'ms_BN','label' => 'Malay (Brunei)', 'flag' => 'bn'], + ['value' => 'ms_MY','label' => 'Malay (Malaysia)', 'flag' => 'my'], + ['value' => 'ms','label' => 'Malay', 'flag' => 'ms'], + ['value' => 'ml_IN','label' => 'Malayalam (India)', 'flag' => 'in'], + ['value' => 'ml','label' => 'Malayalam', 'flag' => 'ml'], + ['value' => 'mt_MT','label' => 'Maltese (Malta)', 'flag' => 'mt'], + ['value' => 'mt','label' => 'Maltese', 'flag' => 'mt'], + ['value' => 'gv_GB','label' => 'Manx (United Kingdom)', 'flag' => 'gb'], + ['value' => 'gv','label' => 'Manx', 'flag' => 'gv'], + ['value' => 'mr_IN','label' => 'Marathi (India)', 'flag' => 'in'], + ['value' => 'mr','label' => 'Marathi', 'flag' => 'mr'], + ['value' => 'mas_KE','label' => 'Masai (Kenya)', 'flag' => 'ke'], + ['value' => 'mas_TZ','label' => 'Masai (Tanzania)', 'flag' => 'tz'], + ['value' => 'mas','label' => 'Masai', 'flag' => 'mas'], + ['value' => 'mer_KE','label' => 'Meru (Kenya)', 'flag' => 'ke'], + ['value' => 'mer','label' => 'Meru', 'flag' => 'mer'], + ['value' => 'mfe_MU','label' => 'Morisyen (Mauritius)', 'flag' => 'mu'], + ['value' => 'mfe','label' => 'Morisyen', 'flag' => 'mfe'], + ['value' => 'naq_NA','label' => 'Nama (Namibia)', 'flag' => 'na'], + ['value' => 'naq','label' => 'Nama', 'flag' => 'naq'], + ['value' => 'ne_IN','label' => 'Nepali (India)', 'flag' => 'in'], + ['value' => 'ne_NP','label' => 'Nepali (Nepal)', 'flag' => 'np'], + ['value' => 'ne','label' => 'Nepali', 'flag' => 'ne'], + ['value' => 'nd_ZW','label' => 'North Ndebele (Zimbabwe)', 'flag' => 'zw'], + ['value' => 'nd','label' => 'North Ndebele', 'flag' => 'nd'], + ['value' => 'nb_NO','label' => 'Norwegian Bokmål (Norway)', 'flag' => 'no'], + ['value' => 'nb','label' => 'Norwegian Bokmål', 'flag' => 'nb'], + ['value' => 'nn_NO','label' => 'Norwegian Nynorsk (Norway)', 'flag' => 'no'], + ['value' => 'nn','label' => 'Norwegian Nynorsk', 'flag' => 'nn'], + ['value' => 'nyn_UG','label' => 'Nyankole (Uganda)', 'flag' => 'ug'], + ['value' => 'nyn','label' => 'Nyankole', 'flag' => 'nyn'], + ['value' => 'or_IN','label' => 'Oriya (India)', 'flag' => 'in'], + ['value' => 'or','label' => 'Oriya', 'flag' => 'or'], + ['value' => 'om_ET','label' => 'Oromo (Ethiopia)', 'flag' => 'et'], + ['value' => 'om_KE','label' => 'Oromo (Kenya)', 'flag' => 'ke'], + ['value' => 'om','label' => 'Oromo', 'flag' => 'om'], + ['value' => 'ps_AF','label' => 'Pashto (Afghanistan)', 'flag' => 'af'], + ['value' => 'ps','label' => 'Pashto', 'flag' => 'ps'], + ['value' => 'fa_AF','label' => 'Persian (Afghanistan)', 'flag' => 'af'], + ['value' => 'fa_IR','label' => 'Persian (Iran)', 'flag' => 'ir'], + ['value' => 'fa','label' => 'Persian', 'flag' => 'fa'], + ['value' => 'pl_PL','label' => 'Polish (Poland)', 'flag' => 'pl'], + ['value' => 'pl','label' => 'Polish', 'flag' => 'pl'], + ['value' => 'pt_BR','label' => 'Portuguese (Brazil)', 'flag' => 'br'], + ['value' => 'pt_GW','label' => 'Portuguese (Guinea-Bissau)', 'flag' => 'gw'], + ['value' => 'pt_MZ','label' => 'Portuguese (Mozambique)', 'flag' => 'mz'], + ['value' => 'pt_PT','label' => 'Portuguese (Portugal)', 'flag' => 'pt'], + ['value' => 'pt','label' => 'Portuguese', 'flag' => 'pt'], + ['value' => 'pa_Arab','label' => 'Punjabi (Arabic)', 'flag' => 'arab'], + ['value' => 'pa_Arab_PK','label' => 'Punjabi (Arabic, Pakistan)', 'flag' => 'pk'], + ['value' => 'pa_Guru','label' => 'Punjabi (Gurmukhi)', 'flag' => 'guru'], + ['value' => 'pa_Guru_IN','label' => 'Punjabi (Gurmukhi, India)', 'flag' => 'in'], + ['value' => 'pa','label' => 'Punjabi', 'flag' => 'pa'], + ['value' => 'ro_MD','label' => 'Romanian (Moldova)', 'flag' => 'md'], + ['value' => 'ro_RO','label' => 'Romanian (Romania)', 'flag' => 'ro'], + ['value' => 'ro','label' => 'Romanian', 'flag' => 'ro'], + ['value' => 'rm_CH','label' => 'Romansh (Switzerland)', 'flag' => 'ch'], + ['value' => 'rm','label' => 'Romansh', 'flag' => 'rm'], + ['value' => 'rof_TZ','label' => 'Rombo (Tanzania)', 'flag' => 'tz'], + ['value' => 'rof','label' => 'Rombo', 'flag' => 'rof'], + ['value' => 'ru_MD','label' => 'Russian (Moldova)', 'flag' => 'md'], + ['value' => 'ru_RU','label' => 'Russian (Russia)', 'flag' => 'ru'], + ['value' => 'ru_UA','label' => 'Russian (Ukraine)', 'flag' => 'ua'], + ['value' => 'ru','label' => 'Russian', 'flag' => 'ru'], + ['value' => 'rwk_TZ','label' => 'Rwa (Tanzania)', 'flag' => 'tz'], + ['value' => 'rwk','label' => 'Rwa', 'flag' => 'rwk'], + ['value' => 'saq_KE','label' => 'Samburu (Kenya)', 'flag' => 'ke'], + ['value' => 'saq','label' => 'Samburu', 'flag' => 'saq'], + ['value' => 'sg_CF','label' => 'Sango (Central African Republic)', 'flag' => 'cf'], + ['value' => 'sg','label' => 'Sango', 'flag' => 'sg'], + ['value' => 'seh_MZ','label' => 'Sena (Mozambique)', 'flag' => 'mz'], + ['value' => 'seh','label' => 'Sena', 'flag' => 'seh'], + ['value' => 'sr_Cyrl','label' => 'Serbian (Cyrillic)', 'flag' => 'cyrl'], + ['value' => 'sr_Cyrl_BA','label' => 'Serbian (Cyrillic, Bosnia and Herzegovina)', 'flag' => 'ba'], + ['value' => 'sr_Cyrl_ME','label' => 'Serbian (Cyrillic, Montenegro)', 'flag' => 'me'], + ['value' => 'sr_Cyrl_RS','label' => 'Serbian (Cyrillic, Serbia)', 'flag' => 'rs'], + ['value' => 'sr_Latn','label' => 'Serbian (Latin)', 'flag' => 'latn'], + ['value' => 'sr_Latn_BA','label' => 'Serbian (Latin, Bosnia and Herzegovina)', 'flag' => 'ba'], + ['value' => 'sr_Latn_ME','label' => 'Serbian (Latin, Montenegro)', 'flag' => 'me'], + ['value' => 'sr_Latn_RS','label' => 'Serbian (Latin, Serbia)', 'flag' => 'rs'], + ['value' => 'sr','label' => 'Serbian', 'flag' => 'sr'], + ['value' => 'sn_ZW','label' => 'Shona (Zimbabwe)', 'flag' => 'zw'], + ['value' => 'sn','label' => 'Shona', 'flag' => 'sn'], + ['value' => 'ii_CN','label' => 'Sichuan Yi (China)', 'flag' => 'cn'], + ['value' => 'ii','label' => 'Sichuan Yi', 'flag' => 'ii'], + ['value' => 'si_LK','label' => 'Sinhala (Sri Lanka)', 'flag' => 'lk'], + ['value' => 'si','label' => 'Sinhala', 'flag' => 'si'], + ['value' => 'sk_SK','label' => 'Slovak (Slovakia)', 'flag' => 'sk'], + ['value' => 'sk','label' => 'Slovak', 'flag' => 'sk'], + ['value' => 'sl_SI','label' => 'Slovenian (Slovenia)', 'flag' => 'si'], + ['value' => 'sl','label' => 'Slovenian', 'flag' => 'sl'], + ['value' => 'xog_UG','label' => 'Soga (Uganda)', 'flag' => 'ug'], + ['value' => 'xog','label' => 'Soga', 'flag' => 'xog'], + ['value' => 'so_DJ','label' => 'Somali (Djibouti)', 'flag' => 'dj'], + ['value' => 'so_ET','label' => 'Somali (Ethiopia)', 'flag' => 'et'], + ['value' => 'so_KE','label' => 'Somali (Kenya)', 'flag' => 'ke'], + ['value' => 'so_SO','label' => 'Somali (Somalia)', 'flag' => 'so'], + ['value' => 'so','label' => 'Somali', 'flag' => 'so'], + ['value' => 'es_AR','label' => 'Spanish (Argentina)', 'flag' => 'ar'], + ['value' => 'es_BO','label' => 'Spanish (Bolivia)', 'flag' => 'bo'], + ['value' => 'es_CL','label' => 'Spanish (Chile)', 'flag' => 'cl'], + ['value' => 'es_CO','label' => 'Spanish (Colombia)', 'flag' => 'co'], + ['value' => 'es_CR','label' => 'Spanish (Costa Rica)', 'flag' => 'cr'], + ['value' => 'es_DO','label' => 'Spanish (Dominican Republic)', 'flag' => 'do'], + ['value' => 'es_EC','label' => 'Spanish (Ecuador)', 'flag' => 'ec'], + ['value' => 'es_SV','label' => 'Spanish (El Salvador)', 'flag' => 'sv'], + ['value' => 'es_GQ','label' => 'Spanish (Equatorial Guinea)', 'flag' => 'gq'], + ['value' => 'es_GT','label' => 'Spanish (Guatemala)', 'flag' => 'gt'], + ['value' => 'es_HN','label' => 'Spanish (Honduras)', 'flag' => 'hn'], + ['value' => 'es_419','label' => 'Spanish (Latin America)', 'flag' => '419'], + ['value' => 'es_MX','label' => 'Spanish (Mexico)', 'flag' => 'mx'], + ['value' => 'es_NI','label' => 'Spanish (Nicaragua)', 'flag' => 'ni'], + ['value' => 'es_PA','label' => 'Spanish (Panama)', 'flag' => 'pa'], + ['value' => 'es_PY','label' => 'Spanish (Paraguay)', 'flag' => 'py'], + ['value' => 'es_PE','label' => 'Spanish (Peru)', 'flag' => 'pe'], + ['value' => 'es_PR','label' => 'Spanish (Puerto Rico)', 'flag' => 'pr'], + ['value' => 'es_ES','label' => 'Spanish (Spain)', 'flag' => 'es'], + //array('value' => 'es_US','label' => 'Spanish (United States)', 'flag' => 'us'), + ['value' => 'es_UY','label' => 'Spanish (Uruguay)', 'flag' => 'uy'], + ['value' => 'es_VE','label' => 'Spanish (Venezuela)', 'flag' => 've'], + ['value' => 'es','label' => 'Spanish', 'flag' => 'es'], + ['value' => 'sw_KE','label' => 'Swahili (Kenya)', 'flag' => 'ke'], + ['value' => 'sw_TZ','label' => 'Swahili (Tanzania)', 'flag' => 'tz'], + ['value' => 'sw','label' => 'Swahili', 'flag' => 'sw'], + ['value' => 'sv_FI','label' => 'Swedish (Finland)', 'flag' => 'fi'], + ['value' => 'sv_SE','label' => 'Swedish (Sweden)', 'flag' => 'se'], + ['value' => 'sv','label' => 'Swedish', 'flag' => 'sv'], + ['value' => 'gsw_CH','label' => 'Swiss German (Switzerland)', 'flag' => 'ch'], + ['value' => 'gsw','label' => 'Swiss German', 'flag' => 'gsw'], + ['value' => 'shi_Latn','label' => 'Tachelhit (Latin)', 'flag' => 'latn'], + ['value' => 'shi_Latn_MA','label' => 'Tachelhit (Latin, Morocco)', 'flag' => 'ma'], + ['value' => 'shi_Tfng','label' => 'Tachelhit (Tifinagh)', 'flag' => 'tfng'], + ['value' => 'shi_Tfng_MA','label' => 'Tachelhit (Tifinagh, Morocco)', 'flag' => 'ma'], + ['value' => 'shi','label' => 'Tachelhit', 'flag' => 'shi'], + ['value' => 'dav_KE','label' => 'Taita (Kenya)', 'flag' => 'ke'], + ['value' => 'dav','label' => 'Taita', 'flag' => 'dav'], + ['value' => 'ta_IN','label' => 'Tamil (India)', 'flag' => 'in'], + ['value' => 'ta_LK','label' => 'Tamil (Sri Lanka)', 'flag' => 'lk'], + ['value' => 'ta','label' => 'Tamil', 'flag' => 'ta'], + ['value' => 'te_IN','label' => 'Telugu (India)', 'flag' => 'in'], + ['value' => 'te','label' => 'Telugu', 'flag' => 'te'], + ['value' => 'teo_KE','label' => 'Teso (Kenya)', 'flag' => 'ke'], + ['value' => 'teo_UG','label' => 'Teso (Uganda)', 'flag' => 'ug'], + ['value' => 'teo','label' => 'Teso', 'flag' => 'teo'], + ['value' => 'th_TH','label' => 'Thai (Thailand)', 'flag' => 'th'], + ['value' => 'th','label' => 'Thai', 'flag' => 'th'], + ['value' => 'bo_CN','label' => 'Tibetan (China)', 'flag' => 'cn'], + ['value' => 'bo_IN','label' => 'Tibetan (India)', 'flag' => 'in'], + ['value' => 'bo','label' => 'Tibetan', 'flag' => 'bo'], + ['value' => 'ti_ER','label' => 'Tigrinya (Eritrea)', 'flag' => 'er'], + ['value' => 'ti_ET','label' => 'Tigrinya (Ethiopia)', 'flag' => 'et'], + ['value' => 'ti','label' => 'Tigrinya', 'flag' => 'ti'], + ['value' => 'to_TO','label' => 'Tonga (Tonga)', 'flag' => 'to'], + ['value' => 'to','label' => 'Tonga', 'flag' => 'to'], + ['value' => 'tr_TR','label' => 'Turkish (Turkey)', 'flag' => 'tr'], + ['value' => 'tr','label' => 'Turkish', 'flag' => 'tr'], + ['value' => 'uk_UA','label' => 'Ukrainian (Ukraine)', 'flag' => 'ua'], + ['value' => 'uk','label' => 'Ukrainian', 'flag' => 'uk'], + ['value' => 'ur_IN','label' => 'Urdu (India)', 'flag' => 'in'], + ['value' => 'ur_PK','label' => 'Urdu (Pakistan)', 'flag' => 'pk'], + ['value' => 'ur','label' => 'Urdu', 'flag' => 'ur'], + ['value' => 'uz_Arab','label' => 'Uzbek (Arabic)', 'flag' => 'arab'], + ['value' => 'uz_Arab_AF','label' => 'Uzbek (Arabic, Afghanistan)', 'flag' => 'af'], + ['value' => 'uz_Cyrl','label' => 'Uzbek (Cyrillic)', 'flag' => 'cyrl'], + ['value' => 'uz_Cyrl_UZ','label' => 'Uzbek (Cyrillic, Uzbekistan)', 'flag' => 'uz'], + ['value' => 'uz_Latn','label' => 'Uzbek (Latin)', 'flag' => 'latn'], + ['value' => 'uz_Latn_UZ','label' => 'Uzbek (Latin, Uzbekistan)', 'flag' => 'uz'], + ['value' => 'uz','label' => 'Uzbek', 'flag' => 'uz'], + ['value' => 'vi_VN','label' => 'Vietnamese (Vietnam)', 'flag' => 'vn'], + ['value' => 'vi','label' => 'Vietnamese', 'flag' => 'vi'], + ['value' => 'vun_TZ','label' => 'Vunjo (Tanzania)', 'flag' => 'tz'], + ['value' => 'vun','label' => 'Vunjo', 'flag' => 'vun'], + ['value' => 'cy_GB','label' => 'Welsh (United Kingdom)', 'flag' => 'gb'], + ['value' => 'cy','label' => 'Welsh', 'flag' => 'cy'], + ['value' => 'yo_NG','label' => 'Yoruba (Nigeria)', 'flag' => 'ng'], + ['value' => 'yo','label' => 'Yoruba', 'flag' => 'yo'], + ['value' => 'zu_ZA','label' => 'Zulu (South Africa)', 'flag' => 'za'], + ['value' => 'zu','label' => 'Zulu', 'flag' => 'zu'] +]; + +$global['bcp47'] = []; +$global['langs_codes_values'] = []; +$global['langs_codes_values_withdot'] = []; + +foreach ($global['langs_codes'] as $value) { + $global['bcp47'][$value['value']] = $value; + $global['flag2Lang'][$value['flag']] = $value['value']; + $global['langs_codes_values'][] = $value['value']; + $global['langs_codes_values_withdot'][] = '.' . $value['value']; +} +$global['flag2Lang']['en'] = 'en_US'; +$global['flag2Lang']['us'] = 'en_US'; + +$global['js_availableLangs'] = 'var availableLangs = ' . json_encode($global['langs_codes']) . ';'; diff --git a/objects/bootGrid.php b/objects/bootGrid.php index eb0ee03389..f634b77eae 100644 --- a/objects/bootGrid.php +++ b/objects/bootGrid.php @@ -1,88 +1,89 @@ - $value) { - $direction = "ASC"; - if(strtoupper($value)==="DESC"){ - $direction = "DESC"; - } - $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); - if($key=='order'){ - $key = '`order`'; - } - $orderBy[] = " {$keyPrefix}{$key} {$direction} "; - } - $sql .= " ORDER BY ".implode(",", $orderBy); - } else { - $sql .= $alternativeOrderBy; - } - - $rowCount = getRowCount(); - $current = getCurrentPage(); - $currentP = ($current-1)*$rowCount; - - if($rowCount>0){ - $sql .= " LIMIT $currentP, {$rowCount} "; - } - return $sql; - } - - static function getSqlSearchFromPost($searchFieldsNames = array(), $connection = "AND") { - $sql = ""; - if (!empty($_GET['searchPhrase'])) { - $_POST['searchPhrase'] = $_GET['searchPhrase']; - } else if (!empty($_GET['search']['value'])) { - $_POST['searchPhrase'] = $_GET['search']['value']; - }else if (!empty($_GET['q'])) { - $_POST['searchPhrase'] = $_GET['q']; - } - - if(!empty($_POST['searchPhrase'])){ - global $global; - $search = $global['mysqli']->real_escape_string(xss_esc($_POST['searchPhrase'])); - $search = str_replace('"', '"', $search); - $like = array(); - foreach ($searchFieldsNames as $value) { - if(preg_match('/description/', $value)){ - //$like[] = " {$value} regexp '\\b{$search}\\b' ";// not sure why was using regexp - $like[] = " {$value} LIKE '%{$search}%' "; - }else{ - $like[] = " {$value} LIKE '%{$search}%' "; - } - // for accent insensitive - if(preg_match('/description/', $value)){ - $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) regexp '\\b{$search}\\b' "; - //$like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; - }else{ - $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; - } - } - if(!empty($like)){ - $sql .= " {$connection} (". implode(" OR ", $like).")"; - }else{ - $sql .= " {$connection} 1=1 "; - } - } - - return $sql; - } - -} + $value) { + $direction = "ASC"; + if (strtoupper($value)==="DESC") { + $direction = "DESC"; + } + $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); + if ($key=='order') { + $key = '`order`'; + } + $orderBy[] = " {$keyPrefix}{$key} {$direction} "; + } + $sql .= " ORDER BY ".implode(",", $orderBy); + } else { + $sql .= $alternativeOrderBy; + } + + $rowCount = getRowCount(); + $current = getCurrentPage(); + $currentP = ($current-1)*$rowCount; + + if ($rowCount>0) { + $sql .= " LIMIT $currentP, {$rowCount} "; + } + return $sql; + } + + public static function getSqlSearchFromPost($searchFieldsNames = [], $connection = "AND") + { + $sql = ''; + if (!empty($_GET['searchPhrase'])) { + $_POST['searchPhrase'] = $_GET['searchPhrase']; + } elseif (!empty($_GET['search']['value'])) { + $_POST['searchPhrase'] = $_GET['search']['value']; + } elseif (!empty($_GET['q'])) { + $_POST['searchPhrase'] = $_GET['q']; + } + + if (!empty($_POST['searchPhrase'])) { + global $global; + $search = $global['mysqli']->real_escape_string(xss_esc($_POST['searchPhrase'])); + $search = str_replace('"', '"', $search); + $like = []; + foreach ($searchFieldsNames as $value) { + if (preg_match('/description/', $value)) { + //$like[] = " {$value} regexp '\\b{$search}\\b' ";// not sure why was using regexp + $like[] = " {$value} LIKE '%{$search}%' "; + } else { + $like[] = " {$value} LIKE '%{$search}%' "; + } + // for accent insensitive + if (preg_match('/description/', $value)) { + $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) regexp '\\b{$search}\\b' "; + //$like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; + } else { + $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; + } + } + if (!empty($like)) { + $sql .= " {$connection} (". implode(" OR ", $like).")"; + } else { + $sql .= " {$connection} 1=1 "; + } + } + + return $sql; + } +} diff --git a/objects/captcha.php b/objects/captcha.php index 08750d26c1..eb47c29dbb 100644 --- a/objects/captcha.php +++ b/objects/captcha.php @@ -1,68 +1,74 @@ -largura = $largura; - $this->altura = $altura; - $this->tamanho_fonte = $tamanho_fonte; - $this->quantidade_letras = $quantidade_letras; - } - - - public function getCaptchaImage() { - global $global; - header('Content-type: image/jpeg'); - $imagem = imagecreate($this->largura,$this->altura); // define a largura e a altura da imagem - $fonte = $global['systemRootPath'] . 'objects/monof55.ttf'; //voce deve ter essa ou outra fonte de sua preferencia em sua pasta - $preto = imagecolorallocate($imagem, 0, 0, 0); // define a cor preta - $branco = imagecolorallocate($imagem, 255, 255, 255); // define a cor branca - - // define a palavra conforme a quantidade de letras definidas no parametro $quantidade_letras - //$letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnPpQqRrSsTtUuVvYyXxWwZz23456789'; - $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnPpQqRrSsTtUuVvYyXxWwZz23456789'; - $palavra = substr(str_shuffle($letters), 0, ($this->quantidade_letras)); - if(User::isAdmin()){ - $palavra = "admin"; - } - _session_start(); - $_SESSION["palavra"] = $palavra; // atribui para a sessao a palavra gerada - //_error_log("getCaptchaImage: ".$palavra." - session_name ". session_name()." session_id: ". session_id()); - for ($i = 1; $i <= $this->quantidade_letras; $i++) { - imagettftext( - $imagem, - $this->tamanho_fonte, - rand(-10, 10), - ($this->tamanho_fonte*$i), - ($this->tamanho_fonte + 10), - $branco, - $fonte, - substr($palavra, ($i - 1), 1) - ); // atribui as letras a imagem - } - imagejpeg($imagem); // gera a imagem - imagedestroy($imagem); // limpa a imagem da memoria - //_error_log("getCaptchaImage _SESSION[palavra] = ($_SESSION[palavra]) - session_name ". session_name()." session_id: ". session_id()); - } - - static public function validation($word) { - if(User::isAdmin()){ - return true; - } - _session_start(); - if(empty($_SESSION["palavra"])){ - _error_log("Captcha validation Error: you type ({$word}) and session is empty - session_name ". session_name()." session_id: ". session_id()); - return false; - } - $validation = (strcasecmp($word, $_SESSION["palavra"]) == 0); - if(!$validation){ - _error_log("Captcha validation Error: you type ({$word}) and session is ({$_SESSION["palavra"]})- session_name ". session_name()." session_id: ". session_id()); - } - return $validation; - } - -} +largura = $largura; + $this->altura = $altura; + $this->tamanho_fonte = $tamanho_fonte; + $this->quantidade_letras = $quantidade_letras; + } + + + public function getCaptchaImage() + { + global $global; + header('Content-type: image/jpeg'); + $imagem = imagecreate($this->largura, $this->altura); // define a largura e a altura da imagem + $fonte = $global['systemRootPath'] . 'objects/monof55.ttf'; //voce deve ter essa ou outra fonte de sua preferencia em sua pasta + $preto = imagecolorallocate($imagem, 0, 0, 0); // define a cor preta + $branco = imagecolorallocate($imagem, 255, 255, 255); // define a cor branca + + // define a palavra conforme a quantidade de letras definidas no parametro $quantidade_letras + //$letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnPpQqRrSsTtUuVvYyXxWwZz23456789'; + $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnPpQqRrSsTtUuVvYyXxWwZz23456789'; + $palavra = substr(str_shuffle($letters), 0, ($this->quantidade_letras)); + if (User::isAdmin()) { + $palavra = "admin"; + } + _session_start(); + $_SESSION["palavra"] = $palavra; // atribui para a sessao a palavra gerada + //_error_log("getCaptchaImage: ".$palavra." - session_name ". session_name()." session_id: ". session_id()); + for ($i = 1; $i <= $this->quantidade_letras; $i++) { + imagettftext( + $imagem, + $this->tamanho_fonte, + rand(-10, 10), + ($this->tamanho_fonte*$i), + ($this->tamanho_fonte + 10), + $branco, + $fonte, + substr($palavra, ($i - 1), 1) + ); // atribui as letras a imagem + } + imagejpeg($imagem); // gera a imagem + imagedestroy($imagem); // limpa a imagem da memoria + //_error_log("getCaptchaImage _SESSION[palavra] = ($_SESSION[palavra]) - session_name ". session_name()." session_id: ". session_id()); + } + + public static function validation($word) + { + if (User::isAdmin()) { + return true; + } + _session_start(); + if (empty($_SESSION["palavra"])) { + _error_log("Captcha validation Error: you type ({$word}) and session is empty - session_name ". session_name()." session_id: ". session_id()); + return false; + } + $validation = (strcasecmp($word, $_SESSION["palavra"]) == 0); + if (!$validation) { + _error_log("Captcha validation Error: you type ({$word}) and session is ({$_SESSION["palavra"]})- session_name ". session_name()." session_id: ". session_id()); + } + return $validation; + } +} diff --git a/objects/categories.json.php b/objects/categories.json.php index 5c6704f5d0..f6cbfafb31 100644 --- a/objects/categories.json.php +++ b/objects/categories.json.php @@ -1,42 +1,42 @@ -', '
', '
'); -foreach ($categories as $key => $value) { - $categories[$key]['iconHtml'] = ""; - //$categories[$key]['description'] = str_ireplace($breaks, "\r\n", $value['description']); - /* - $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; - $res = sqlDAL::readSql($sql,"i",array($value['id'])); - $catTypeCache = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if($catTypeCache!=false){ - if($catTypeCache['manualSet']=="0"){ - $categories[$key]['type'] = "3"; - } else { - $categories[$key]['type'] = $catTypeCache['type']; - } - } else { - $categories[$key]['type'] = "3"; - } - * - */ -} -if (empty($_POST['sort']) && empty($_GET['sort'])) { - array_multisort(array_column($categories, 'hierarchyAndName'), SORT_ASC, $categories); -} -echo '{ "current": '.getCurrentPage().',"rowCount": '.getRowCount().', "total": '.$total.', "rows":'. _json_encode($categories).'}'; +', '
', '
'); +foreach ($categories as $key => $value) { + $categories[$key]['iconHtml'] = ""; + //$categories[$key]['description'] = str_ireplace($breaks, "\r\n", $value['description']); + /* + $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; + $res = sqlDAL::readSql($sql,"i",array($value['id'])); + $catTypeCache = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if($catTypeCache!=false){ + if($catTypeCache['manualSet']=="0"){ + $categories[$key]['type'] = "3"; + } else { + $categories[$key]['type'] = $catTypeCache['type']; + } + } else { + $categories[$key]['type'] = "3"; + } + * + */ +} +if (empty($_POST['sort']) && empty($_GET['sort'])) { + array_multisort(array_column($categories, 'hierarchyAndName'), SORT_ASC, $categories); +} +echo '{ "current": '.getCurrentPage().',"rowCount": '.getRowCount().', "total": '.$total.', "rows":'. _json_encode($categories).'}'; diff --git a/objects/category.php b/objects/category.php index 7f5e7c0394..1f47c6cd80 100644 --- a/objects/category.php +++ b/objects/category.php @@ -1,942 +1,1000 @@ -suggested) ? 0 : 1; - } - - function setSuggested($suggested) { - $this->suggested = empty($suggested) ? 0 : 1; - } - - function getOrder() { - return intval($this->order); - } - - function setOrder($order) { - $this->order = intval($order); - } - - function getUsers_id() { - if (empty($this->users_id)) { - $this->users_id = User::getId(); - } - return $this->users_id; - } - - function getPrivate() { - return $this->private; - } - - function setUsers_id($users_id) { - // only admin can change owner - if (!empty($this->users_id) && !User::isAdmin()) { - return false; - } - - $this->users_id = intval($users_id); - } - - function setPrivate($private) { - $this->private = empty($private) ? 0 : 1; - } - - function setName($name) { - $this->name = _substr($name, 0, 45); - } - - function setClean_name($clean_name) { - $clean_name = preg_replace('/\W+/', '-', strtolower(cleanString($clean_name))); - $this->clean_name = _substr($clean_name, 0, 45);; - } - - function setNextVideoOrder($nextVideoOrder) { - $this->nextVideoOrder = $nextVideoOrder; - } - - function setParentId($parentId) { - $this->parentId = $parentId; - } - - function setDescription($description) { - $this->description = $description; - } - - function __construct($id, $name = '') { - if (empty($id)) { - // get the category data from category and pass - $this->name = $name; - } else { - $this->id = $id; - // get data from id - $this->load($id); - } - } - - private function load($id) { - $row = self::getCategory($id); - if (empty($row)) - return false; - foreach ($row as $key => $value) { - $this->$key = $value; - } - return true; - } - - function loadSelfCategory() { - $this->load($this->getId()); - } - - function save($allowOfflineUser = false) { - global $global; - - if (!$allowOfflineUser && !self::canCreateCategory()) { - return false; - } - - if (!$allowOfflineUser && !empty($this->id) && !self::userCanEditCategory($this->id)) { - return false; - } - - if (empty($this->users_id)) { - $this->users_id = User::getId(); - } - - $this->clean_name = self::fixCleanTitle($this->clean_name, 1, $this->id); - - // check if clean name exists - $exists = $this->getCategoryByName($this->clean_name); - if (!empty($exists) && $exists['id'] != $this->id) { - $this->clean_name .= uniqid(); - } - - $this->nextVideoOrder = intval($this->nextVideoOrder); - $this->parentId = intval($this->parentId); - if (!empty($this->id)) { - $sql = "UPDATE categories SET " - . "name = ?," - . "clean_name = ?," - . "description = ?," - . "nextVideoOrder = ?," - . "parentId = ?," - . "iconClass = ?," - . "users_id = ?," - . "suggested = ?," - . "`private` = ?, allow_download = ?, `order` = ?, modified = now() WHERE id = ?"; - $format = "sssiisiiiiii"; - $values = array($this->name, $this->clean_name, $this->description, intval($this->nextVideoOrder), $this->parentId, $this->getIconClass(), $this->getUsers_id(), $this->getSuggested(), $this->getPrivate(), $this->getAllow_download(), $this->getOrder(), $this->id); - } else { - $sql = "INSERT INTO categories ( " - . "name," - . "clean_name," - . "description," - . "nextVideoOrder," - . "parentId," - . "iconClass, " - . "users_id, " - . "suggested, " - . "`private`, allow_download, `order`, created, modified) VALUES (?, ?,?,?,?,?,?,?,?,?,?,now(), now())"; - $format = "sssiisiiiii"; - $values = array($this->name, $this->clean_name, $this->description, intval($this->nextVideoOrder), $this->parentId, $this->getIconClass(), $this->getUsers_id(), $this->getSuggested(), $this->getPrivate(), $this->getAllow_download(), $this->getOrder()); - } - $insert_row = sqlDAL::writeSql($sql, $format, $values); - if ($insert_row) { - self::deleteOGImage($this->id); - self::deleteCategoryCache(); - if (empty($this->id)) { - $id = $insert_row; - } else { - $id = $this->id; - } - return $id; - } else { - die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - } - - static function fixCleanTitle($clean_title, $count, $id, $original_title = "") { - global $global; - - if (empty($original_title)) { - $original_title = $clean_title; - } - - $sql = "SELECT * FROM categories WHERE clean_name = '{$clean_title}' "; - if (!empty($id)) { - $sql .= " AND id != {$id} "; - } - $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, $id, $original_title); - } - return $clean_title; - } - - function delete() { - if (!self::canCreateCategory()) { - return false; - } - - if (!self::userCanEditCategory($this->id)) { - return false; - } - - // cannot delete default category - if ($this->id == 1) { - return false; - } - - global $global; - if (!empty($this->id)) { - $_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; - $categories_id = self::getSiteCategoryDefaultID(); - if ($categories_id) { - $sql = "UPDATE videos SET categories_id = ? WHERE categories_id = ?"; - sqlDAL::writeSql($sql, "ii", array($categories_id, $this->id)); - } - $sql = "DELETE FROM categories WHERE id = ?"; - } else { - return false; - } - self::deleteCategoryCache(); - self::deleteAssets($this->id); - return sqlDAL::writeSql($sql, "i", array($this->id)); - } - - static function deleteAssets($categories_id) { - $dirPaths = self::getCategoryDirPath($categories_id); - return rrmdir($dirPaths['path']); - } - - /* - static function getCategoryType($categoryId) { - global $global; - $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?;"; - $res = sqlDAL::readSql($sql, "i", array($categoryId)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - if (!empty($data)) { - return $data; - } else { - return array("categoryId" => "-1", "type" => "0", "manualSet" => "0"); - } - } else { - return array("categoryId" => "-1", "type" => "0", "manualSet" => "0"); - } - } - * - */ - - static function getCategory($id) { - global $global; - $id = intval($id); - $sql = "SELECT * FROM categories WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "i", array($id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($result) { - $result['name'] = xss_esc_back($result['name']); - } - return ($res) ? $result : false; - } - - static function getCategoryLink($id) { - $cat = new Category($id); - return self::getCategoryLinkFromName($cat->getClean_name()); - } - - static function getCategoryLinkFromName($clean_name) { - global $global; - return "{$global['webSiteRootURL']}cat/{$clean_name}"; - } - - function getLink() { - return self::getCategoryLinkFromName($this->getClean_name()); - } - - static function getCategoryByName($name) { - global $global; - $sql = "SELECT * FROM categories WHERE clean_name = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "s", array($name)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($result) { - $result['name'] = xss_esc_back($result['name']); - $result['description_html'] = textToLink(htmlentities($result['description'])); - } - return ($res) ? $result : false; - } - - static function getOrCreateCategoryByName($name) { - $cat = self::getCategoryByName($name); - if (empty($cat)) { - $obj = new Category(0); - $obj->setName($name); - $obj->setClean_name($name); - $obj->setDescription(""); - $obj->setIconClass(""); - $obj->setNextVideoOrder(0); - $obj->setParentId(0); - - $id = $obj->save(); - return self::getCategoryByName($name); - } - return $cat; - } - - static function getCategoryDefault() { - global $global; - $sql = "SELECT * FROM categories ORDER BY id ASC LIMIT 1"; - $res = sqlDAL::readSql($sql); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($result) { - $result['name'] = xss_esc_back($result['name']); - } - return ($res) ? $result : false; - } - - static function getSiteCategoryDefaultID() { - $obj = AVideoPlugin::getObjectDataIfEnabled("PredefinedCategory"); - $id = false; - if ($obj) { - $id = $obj->defaultCategory; - } else { - $row = self::getCategoryDefault(); - if ($row) { - $id = $row['id']; - } - } - return $id; - } - - static function deleteCategoryCache() { - _session_start(); - ObjectYPT::deleteAllSessionCache(); - clearFirstPageCache(); - unset($_SESSION['user']['sessionCache']); - $_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; - $cacheDir = ObjectYPT::getCacheDir() . 'category/'; - $rrmdir = rrmdir($cacheDir); - _error_log("deleteCategoryCache: {$cacheDir} = ". json_encode($rrmdir)); - } - - static function getAllCategories($filterCanAddVideoOnly = false, $onlyWithVideos = false, $onlySuggested = false) { - global $global, $config; - if ($config->currentVersionLowerThen('8.4')) { - return false; - } - $sql = "SELECT * FROM categories c WHERE 1=1 "; - if (!empty($_GET['parentsOnly'])) { - $sql .= "AND parentId = 0 "; - } - if ($onlySuggested) { - $sql .= "AND suggested = 1 "; - } - if ($filterCanAddVideoOnly && !User::isAdmin()) { - if (is_int($filterCanAddVideoOnly)) { - $users_id = $filterCanAddVideoOnly; - } else { - $users_id = User::getId(); - } - - if ($config->currentVersionGreaterThen('6.1')) { - $sql .= " AND (private=0 OR users_id = '{$users_id}') "; - } - } - if ($onlyWithVideos) { - $sql .= " AND ((SELECT count(*) FROM videos v where v.categories_id = c.id OR categories_id IN (SELECT id from categories where parentId = c.id)) > 0 "; - if (AVideoPlugin::isEnabledByName("Live")) { - $sql .= " OR " - . " (" - . " SELECT count(*) FROM live_transmitions lt where " - . " (lt.categories_id = c.id OR lt.categories_id IN (SELECT id from categories where parentId = c.id))" - //. " AND lt.id = (select id FROM live_transmitions lt2 WHERE lt.users_id = lt2.users_id ORDER BY CREATED DESC LIMIT 1 )" - . " ) > 0 "; - } - if (AVideoPlugin::isEnabledByName("LiveLinks")) { - $sql .= " OR " - . " (" - . " SELECT count(*) FROM LiveLinks ll where " - . " (ll.categories_id = c.id OR ll.categories_id IN (SELECT id from categories where parentId = c.id))" - . " ) > 0 "; - } - $sql .= ")"; - } - - $sortWhitelist = array('id', 'name', 'clean_name', 'description', 'iconClass', 'nextVideoOrder', 'parentId', 'type', 'users_id', 'private', 'allow_download', 'order', 'suggested'); - - if (!empty($_POST['sort']) && is_array($_POST['sort'])) { - foreach ($_POST['sort'] as $key => $value) { - if (!in_array($key, $sortWhitelist)) { - unset($_POST['sort'][$key]); - } - } - } - $sql .= BootGrid::getSqlFromPost(array('name'), "", " ORDER BY `order`, name ASC "); - //echo $sql;exit; - $cacheName = 'category/' . md5($sql); - if (empty($_SESSION['user']['sessionCache']['getAllCategoriesClearCache'])) { - $category = object_to_array(ObjectYPT::getCache($cacheName, 36000)); - //var_dump($cacheName, ObjectYPT::getLastUsedCacheInfo(), fixPath(ObjectYPT::getCacheDir() . 'category/'));exit; - } else { - _session_start(); - unset($_SESSION['user']['sessionCache']['getAllCategoriesClearCache']); - } - if (empty($category)) { - $res = sqlDAL::readSql($sql); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $category = array(); - if ($res) { - foreach ($fullResult as $row) { - - $totals = self::getTotalFromCategory($row['id']); - $fullTotals = self::getTotalFromCategory($row['id'], false, true, true); - - $row['name'] = $row['name']; - $row['total'] = $totals['total']; - $row['fullTotal'] = $fullTotals['total']; - $row['fullTotal_videos'] = $fullTotals['videos']; - $row['fullTotal_lives'] = $fullTotals['lives']; - $row['fullTotal_livelinks'] = $fullTotals['livelinks']; - $row['owner'] = User::getNameIdentificationById(@$row['users_id']); - $row['canEdit'] = self::userCanEditCategory($row['id']); - $row['canAddVideo'] = self::userCanAddInCategory($row['id']); - $row['hierarchy'] = self::getHierarchyString($row['parentId']); - $row['hierarchyAndName'] = $row['hierarchy'] . $row['name']; - $row['description_html'] = textToLink(htmlentities($row['description'])); - $category[] = $row; - } - //$category = $res->fetch_all(MYSQLI_ASSOC); - ObjectYPT::setCache($cacheName, $category); - } else { - $category = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - } - return $category; - } - - static function getHierarchyArray($categories_id, $hierarchyArray = array()) { - if (empty($categories_id)) { - return $hierarchyArray; - } - $sql = "SELECT * FROM categories WHERE id=? "; - $res = sqlDAL::readSql($sql, "i", array($categories_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($result) { - $hierarchyArray[] = $result; - return self::getHierarchyArray($result['parentId'], $hierarchyArray); - } - return $hierarchyArray; - } - - static function getHierarchyString($categories_id) { - if (empty($categories_id)) { - return "/"; - } - $array = array_reverse(self::getHierarchyArray($categories_id)); - //$array = (self::getHierarchyArray($categories_id)); - //var_dump($array);exit; - if (empty($array)) { - return "/"; - } - $str = "/"; - foreach ($array as $value) { - $str .= xss_esc_back($value['name']) . "/"; - } - return $str; - } - - static function userCanAddInCategory($categories_id, $users_id = 0) { - if (empty($categories_id)) { - return false; - } - if (empty($users_id)) { - $users_id = User::getId(); - } - if (empty($users_id)) { - return false; - } - $cat = new Category($categories_id); - if (empty($cat->getPrivate()) || $users_id == $cat->getUsers_id()) { - return true; - } - return false; - } - - static function userCanEditCategory($categories_id, $users_id = 0) { - if (empty($categories_id)) { - return false; - } - if (empty($users_id)) { - $users_id = User::getId(); - } - if (empty($users_id)) { - return false; - } - - if (User::isAdmin()) { - return true; - } - - $cat = new Category($categories_id); - if ($users_id == $cat->getUsers_id()) { - return true; - } - return false; - } - - static function canCreateCategory() { - global $advancedCustomUser; - if (User::isAdmin()) { - return true; - } - if ($advancedCustomUser && $advancedCustomUser->usersCanCreateNewCategories && User::canUpload()) { - return true; - } - return false; - } - - static function getChildCategories($parentId, $filterCanAddVideoOnly = false) { - global $global, $config; - if ($config->currentVersionLowerThen('8.4')) { - return false; - } - $sql = "SELECT * FROM categories WHERE parentId=? AND id!=? "; - if ($filterCanAddVideoOnly && !User::isAdmin()) { - if (is_int($filterCanAddVideoOnly)) { - $users_id = $filterCanAddVideoOnly; - } else { - $users_id = User::getId(); - } - - if ($config->currentVersionGreaterThen('6.1')) { - $sql .= " AND (private=0 OR users_id = '{$users_id}') "; - } - } - $sql .= BootGrid::getSqlFromPost(array('name'), "", " ORDER BY `order`, name ASC "); - $res = sqlDAL::readSql($sql, "ii", array($parentId, $parentId)); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $category = array(); - if ($res) { - foreach ($fullResult as $row) { - $totals = self::getTotalFromCategory($row['id']); - $row['name'] = xss_esc_back($row['name']); - $row['total'] = $totals['total']; - $row['total_array'] = $totals; - $category[] = $row; - } - } else { - $category = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $category; - } - - static function getChildCategoriesFromTitle($clean_title) { - $row = self::getCategoryByName($clean_title); - return self::getChildCategories($row['id']); - } - - static function getTotalFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) { - $videos = self::getTotalVideosFromCategory($categories_id, $showUnlisted, $getAllVideos, $renew); - $lives = self::getTotalLivesFromCategory($categories_id, $showUnlisted, $renew); - $livelinkss = self::getTotalLiveLinksFromCategory($categories_id, $showUnlisted, $renew); - $total = $videos + $lives + $livelinkss; - return array('videos' => $videos, 'lives' => $lives, 'livelinks' => $livelinkss, 'total' => $total); - } - - static function getTotalFromChildCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) { - - $categories = self::getChildCategories($categories_id); - $array = array('videos' => 0, 'lives' => 0, 'livelinks' => 0, 'total' => 0); - foreach ($categories as $value) { - $totals = self::getTotalFromCategory($categories_id, $showUnlisted, $getAllVideos, $renew); - $array = array( - 'videos' => $array['videos'] + $totals['videos'], - 'lives' => $array['lives'] + $totals['lives'], - 'livelinks' => $array['livelinks'] + $totals['livelinks'], - 'total' => $array['total'] + $totals['total']); - $totals = self::getTotalFromChildCategory($value['id'], $showUnlisted, $getAllVideos, $renew); - $array = array( - 'videos' => $array['videos'] + $totals['videos'], - 'lives' => $array['lives'] + $totals['lives'], - 'livelinks' => $array['livelinks'] + $totals['livelinks'], - 'total' => $array['total'] + $totals['total']); - } - - return $array; - } - - static function getTotalVideosFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) { - global $global, $config; - if ($renew || empty($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]['videos'])) { - $sql = "SELECT count(id) as total FROM videos v WHERE 1=1 AND categories_id = ? "; - - 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)) . "')"; - } - if (!$getAllVideos) { - $sql .= Video::getUserGroupsCanSeeSQL(); - } - //echo $categories_id, $sql;exit; - $res = sqlDAL::readSql($sql, "i", array($categories_id)); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); - $rows = self::getChildCategories($categories_id); - foreach ($rows as $value) { - $total += self::getTotalVideosFromCategory($value['id'], $showUnlisted, $getAllVideos, $renew); - } - _session_start(); - $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]['videos'] = $total; - } - return $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]['videos']; - } - - static function getLatestVideoFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false) { - global $global, $config; - $sql = "SELECT * FROM videos v WHERE 1=1 AND (categories_id = ? OR categories_id IN (SELECT id from categories where parentId = ?))"; - - 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)) . "')"; - } - if (!$getAllVideos) { - $sql .= Video::getUserGroupsCanSeeSQL(); - } - $sql .= "ORDER BY created DESC LIMIT 1"; - //var_dump($sql, $categories_id); - $res = sqlDAL::readSql($sql, "ii", array($categories_id, $categories_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return $result; - } - - static function getLatestLiveFromCategory($categories_id) { - if (!AVideoPlugin::isEnabledByName("Live")) { - return array(); - } - global $global, $config; - $sql = "SELECT * FROM live_transmitions lt LEFT JOIN live_transmitions_history lth ON lt.users_id = lth.users_id " - . " WHERE 1=1 AND (categories_id = ? OR categories_id IN (SELECT id from categories where parentId = ?))"; - - $sql .= "ORDER BY lth.created DESC LIMIT 1"; - //var_dump($sql, $categories_id); - $res = sqlDAL::readSql($sql, "ii", array($categories_id, $categories_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return $result; - } - - static function getLatestLiveLinksFromCategory($categories_id) { - if (AVideoPlugin::isEnabledByName("LiveLinks")) { - return array(); - } - global $global, $config; - $sql = "SELECT * FROM livelinks WHERE 1=1 AND (categories_id = ? OR categories_id IN (SELECT id from categories where parentId = ?))"; - - $sql .= "ORDER BY created DESC LIMIT 1"; - //var_dump($sql, $categories_id); - $res = sqlDAL::readSql($sql, "ii", array($categories_id, $categories_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return $result; - } - - static function getTotalLiveLinksFromCategory($categories_id, $showUnlisted = false, $renew = false) { - global $global; - - if (!AVideoPlugin::isEnabledByName("LiveLinks")) { - return 0; - } - - if ($renew || empty($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['livelinks'])) { - $sql = "SELECT count(id) as total FROM LiveLinks v WHERE 1=1 AND categories_id = ? "; - - if (empty($showUnlisted)) { - $sql .= " AND `type` = 'public' "; - } - - //echo $categories_id, $sql;exit; - $res = sqlDAL::readSql($sql, "i", array($categories_id)); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); - $rows = self::getChildCategories($categories_id); - foreach ($rows as $value) { - $total += self::getTotalLivesFromCategory($value['id'], $showUnlisted, $renew); - } - _session_start(); - $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['livelinks'] = $total; - } - return $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['livelinks']; - } - - static function getTotalLivesFromCategory($categories_id, $showUnlisted = false, $renew = false) { - - - if (!AVideoPlugin::isEnabledByName("Live")) { - return 0; - } - - global $global; - if ($renew || empty($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['live'])) { - $sql = "SELECT count(id) as total FROM live_transmitions v WHERE 1=1 AND categories_id = ? "; - - if (empty($showUnlisted)) { - $sql .= " AND public = 1 "; - } - - //echo $categories_id, $sql;exit; - $res = sqlDAL::readSql($sql, "i", array($categories_id)); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); - $rows = self::getChildCategories($categories_id); - foreach ($rows as $value) { - $total += self::getTotalLivesFromCategory($value['id'], $showUnlisted, $renew); - } - _session_start(); - $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['live'] = $total; - } - return $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['live']; - } - - static function clearCacheCount($categories_id = 0) { - // clear category count cache - _session_start(); - if (empty($categories_id)) { - unset($_SESSION['user']['sessionCache']['categoryTotal']); - $_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; - } else { - unset($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id]); - } - //session_write_close(); - } - - static function getTotalCategories($filterCanAddVideoOnly = false, $onlyWithVideos = false, $onlySuggested = false) { - global $global, $config; - - if ($config->currentVersionLowerThen('5.01')) { - return false; - } - $sql = "SELECT id, parentId FROM categories c WHERE 1=1 "; - if ($onlySuggested) { - $sql .= "AND suggested = 1 "; - } - if ($filterCanAddVideoOnly && !User::isAdmin()) { - if (is_int($filterCanAddVideoOnly)) { - $users_id = $filterCanAddVideoOnly; - } else { - $users_id = User::getId(); - } - - if ($config->currentVersionGreaterThen('6.1')) { - $sql .= " AND (private=0 OR users_id = '{$users_id}') "; - } - } - if (!empty($_GET['parentsOnly'])) { - $sql .= "AND parentId = 0 OR parentId = -1 "; - } - if ($onlyWithVideos) { - $sql .= " AND ((SELECT count(*) FROM videos v where v.categories_id = c.id OR categories_id IN (SELECT id from categories where parentId = c.id)) > 0 "; - if (AVideoPlugin::isEnabledByName("Live")) { - $sql .= " OR " - . " (" - . " SELECT count(*) FROM live_transmitions lt where " - . " (lt.categories_id = c.id OR lt.categories_id IN (SELECT id from categories where parentId = c.id))" - //. " AND lt.id = (select id FROM live_transmitions lt2 WHERE lt.users_id = lt2.users_id ORDER BY CREATED DESC LIMIT 1 )" - . " ) > 0 "; - } - if (AVideoPlugin::isEnabledByName("LiveLinks")) { - $sql .= " OR " - . " (" - . " SELECT count(*) FROM LiveLinks ll where " - . " (ll.categories_id = c.id OR ll.categories_id IN (SELECT id from categories where parentId = c.id))" - . " ) > 0 "; - } - $sql .= ")"; - } - $sql .= BootGrid::getSqlSearchFromPost(array('name')); - //echo $sql;exit; - $res = sqlDAL::readSql($sql); - $numRows = sqlDal::num_rows($res); - sqlDAL::close($res); - return $numRows; - } - - function getIconClass() { - if (empty($this->iconClass)) { - return "fa fa-folder"; - } - return $this->iconClass; - } - - function setIconClass($iconClass) { - $this->iconClass = $iconClass; - } - - function getName() { - return $this->name; - } - - function getClean_name() { - return $this->clean_name; - } - - function getDescription() { - return $this->description; - } - - function getAllow_download() { - return $this->allow_download; - } - - function setAllow_download($allow_download) { - $this->allow_download = intval($allow_download); - } - - static function getCategoryDirPath($categories_id = "") { - global $global; - - $dir = "videos/categories/assets/"; - if (!empty($categories_id)) { - $dir .= $categories_id . "/"; - } - - $path = array(); - $path['dir'] = "{$global['systemRootPath']}{$dir}"; - make_path($path['dir']); - $path['path'] = "{$global['systemRootPath']}{$dir}"; - $path['url'] = getCDN() . "{$dir}"; - return $path; - } - - static function isAssetsValids($categories_id) { - $photo = Category::getCategoryPhotoPath($categories_id); - $background = Category::getCategoryBackgroundPath($categories_id); - //var_dump(filesize($background['path']), $background['path'], filesize($photo['path']), $photo['path'] ); - if (!file_exists($photo['path']) || !file_exists($background['path'])) { - return false; - } - if (filesize($photo['path']) <= 190) { // transparent image - return false; - } - if (filesize($background['path']) <= 980 || filesize($background['path']) == 4480) { // transparent image - return false; - } - return true; - } - - public static function getOGImagePaths($categories_id) { - $name = "og_200X200.jpg"; - $dirPaths = self::getCategoryDirPath($categories_id); - $path = array(); - $path['dir'] = $dirPaths['url']; - $path['path'] = "{$dirPaths['path']}{$name}"; - $path['url'] = "{$dirPaths['url']}{$name}"; - if (file_exists($path['path'])) { - $path['url+timestamp'] = "{$path['url']}?" . filectime($path['path']); - } else { - $path['url+timestamp'] = $path['url']; - } - return $path; - } - - public static function deleteOGImage($categories_id) { - $ogPaths = self::getOGImagePaths($categories_id); - $destination = $ogPaths['path']; - if (file_exists($destination)) { - unlink($destination); - } - } - - public static function getOGImage($categories_id) { - global $global; - $isAssetsValids = self::isAssetsValids($categories_id); - if ($isAssetsValids) { - $ogPaths = self::getOGImagePaths($categories_id); - $destination = $ogPaths['path']; - if (!file_exists($destination)) { - $photo = self::getCategoryPhotoPath($categories_id); - $source = $photo['path']; - convertImageToOG($source, $destination); - } - - return $ogPaths['url+timestamp']; - } else { - return Configuration::getOGImage(); - } - } - - static function getCategoryPhotoPath($categories_id) { - $path = self::getCategoryAssetPath("photo.png", $categories_id); - return $path; - } - - static function getCategoryBackgroundPath($categories_id) { - $path = self::getCategoryAssetPath("background.png", $categories_id); - return $path; - } - - private static function getCategoryAssetPath($name, $categories_id) { - if (empty($categories_id)) { - return false; - } - if (empty($name)) { - return false; - } - - $dirPaths = self::getCategoryDirPath($categories_id); - - global $global; - - $path = array(); - $path['dir'] = $dirPaths['url']; - $path['path'] = "{$dirPaths['path']}{$name}"; - $path['url'] = "{$dirPaths['url']}{$name}"; - if (file_exists($path['path'])) { - $path['url+timestamp'] = "{$path['url']}?" . filectime($path['path']); - } else { - $path['url+timestamp'] = $path['url']; - } - return $path; - } - -} +suggested) ? 0 : 1; + } + + public function setSuggested($suggested) + { + $this->suggested = empty($suggested) ? 0 : 1; + } + + public function getOrder() + { + return intval($this->order); + } + + public function setOrder($order) + { + $this->order = intval($order); + } + + public function getUsers_id() + { + if (empty($this->users_id)) { + $this->users_id = User::getId(); + } + return $this->users_id; + } + + public function getPrivate() + { + return $this->private; + } + + public function setUsers_id($users_id) + { + // only admin can change owner + if (!empty($this->users_id) && !User::isAdmin()) { + return false; + } + + $this->users_id = intval($users_id); + } + + public function setPrivate($private) + { + $this->private = empty($private) ? 0 : 1; + } + + public function setName($name) + { + $this->name = _substr($name, 0, 45); + } + + public function setClean_name($clean_name) + { + $clean_name = preg_replace('/\W+/', '-', strtolower(cleanString($clean_name))); + $this->clean_name = _substr($clean_name, 0, 45); + ; + } + + public function setNextVideoOrder($nextVideoOrder) + { + $this->nextVideoOrder = $nextVideoOrder; + } + + public function setParentId($parentId) + { + $this->parentId = $parentId; + } + + public function setDescription($description) + { + $this->description = $description; + } + + public function __construct($id, $name = '') + { + if (empty($id)) { + // get the category data from category and pass + $this->name = $name; + } else { + $this->id = $id; + // get data from id + $this->load($id); + } + } + + private function load($id) + { + $row = self::getCategory($id); + if (empty($row)) { + return false; + } + foreach ($row as $key => $value) { + $this->$key = $value; + } + return true; + } + + public function loadSelfCategory() + { + $this->load($this->getId()); + } + + public function save($allowOfflineUser = false) + { + global $global; + + if (!$allowOfflineUser && !self::canCreateCategory()) { + return false; + } + + if (!$allowOfflineUser && !empty($this->id) && !self::userCanEditCategory($this->id)) { + return false; + } + + if (empty($this->users_id)) { + $this->users_id = User::getId(); + } + + $this->clean_name = self::fixCleanTitle($this->clean_name, 1, $this->id); + + // check if clean name exists + $exists = $this->getCategoryByName($this->clean_name); + if (!empty($exists) && $exists['id'] != $this->id) { + $this->clean_name .= uniqid(); + } + + $this->nextVideoOrder = intval($this->nextVideoOrder); + $this->parentId = intval($this->parentId); + if (!empty($this->id)) { + $sql = "UPDATE categories SET " + . "name = ?," + . "clean_name = ?," + . "description = ?," + . "nextVideoOrder = ?," + . "parentId = ?," + . "iconClass = ?," + . "users_id = ?," + . "suggested = ?," + . "`private` = ?, allow_download = ?, `order` = ?, modified = now() WHERE id = ?"; + $format = "sssiisiiiiii"; + $values = [$this->name, $this->clean_name, $this->description, intval($this->nextVideoOrder), $this->parentId, $this->getIconClass(), $this->getUsers_id(), $this->getSuggested(), $this->getPrivate(), $this->getAllow_download(), $this->getOrder(), $this->id]; + } else { + $sql = "INSERT INTO categories ( " + . "name," + . "clean_name," + . "description," + . "nextVideoOrder," + . "parentId," + . "iconClass, " + . "users_id, " + . "suggested, " + . "`private`, allow_download, `order`, created, modified) VALUES (?, ?,?,?,?,?,?,?,?,?,?,now(), now())"; + $format = "sssiisiiiii"; + $values = [$this->name, $this->clean_name, $this->description, intval($this->nextVideoOrder), $this->parentId, $this->getIconClass(), $this->getUsers_id(), $this->getSuggested(), $this->getPrivate(), $this->getAllow_download(), $this->getOrder()]; + } + $insert_row = sqlDAL::writeSql($sql, $format, $values); + if ($insert_row) { + self::deleteOGImage($this->id); + self::deleteCategoryCache(); + if (empty($this->id)) { + $id = $insert_row; + } else { + $id = $this->id; + } + return $id; + } else { + die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + } + + public static function fixCleanTitle($clean_title, $count, $id, $original_title = "") + { + global $global; + + if (empty($original_title)) { + $original_title = $clean_title; + } + + $sql = "SELECT * FROM categories WHERE clean_name = '{$clean_title}' "; + if (!empty($id)) { + $sql .= " AND id != {$id} "; + } + $sql .= " LIMIT 1"; + $res = sqlDAL::readSql($sql, "", [], true); + $cleanTitleExists = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($cleanTitleExists != false) { + return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $id, $original_title); + } + return $clean_title; + } + + public function delete() + { + if (!self::canCreateCategory()) { + return false; + } + + if (!self::userCanEditCategory($this->id)) { + return false; + } + + // cannot delete default category + if ($this->id == 1) { + return false; + } + + global $global; + if (!empty($this->id)) { + $_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; + $categories_id = self::getSiteCategoryDefaultID(); + if ($categories_id) { + $sql = "UPDATE videos SET categories_id = ? WHERE categories_id = ?"; + sqlDAL::writeSql($sql, "ii", [$categories_id, $this->id]); + } + $sql = "DELETE FROM categories WHERE id = ?"; + } else { + return false; + } + self::deleteCategoryCache(); + self::deleteAssets($this->id); + return sqlDAL::writeSql($sql, "i", [$this->id]); + } + + public static function deleteAssets($categories_id) + { + $dirPaths = self::getCategoryDirPath($categories_id); + return rrmdir($dirPaths['path']); + } + + /* + static function getCategoryType($categoryId) { + global $global; + $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?;"; + $res = sqlDAL::readSql($sql, "i", array($categoryId)); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + if (!empty($data)) { + return $data; + } else { + return array("categoryId" => "-1", "type" => "0", "manualSet" => "0"); + } + } else { + return array("categoryId" => "-1", "type" => "0", "manualSet" => "0"); + } + } + * + */ + + public static function getCategory($id) + { + global $global; + $id = intval($id); + $sql = "SELECT * FROM categories WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($result) { + $result['name'] = xss_esc_back($result['name']); + } + return ($res) ? $result : false; + } + + public static function getCategoryLink($id) + { + $cat = new Category($id); + return self::getCategoryLinkFromName($cat->getClean_name()); + } + + public static function getCategoryLinkFromName($clean_name) + { + global $global; + return "{$global['webSiteRootURL']}cat/{$clean_name}"; + } + + public function getLink() + { + return self::getCategoryLinkFromName($this->getClean_name()); + } + + public static function getCategoryByName($name) + { + global $global; + $sql = "SELECT * FROM categories WHERE clean_name = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "s", [$name]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($result) { + $result['name'] = xss_esc_back($result['name']); + $result['description_html'] = textToLink(htmlentities($result['description'])); + } + return ($res) ? $result : false; + } + + public static function getOrCreateCategoryByName($name) + { + $cat = self::getCategoryByName($name); + if (empty($cat)) { + $obj = new Category(0); + $obj->setName($name); + $obj->setClean_name($name); + $obj->setDescription(""); + $obj->setIconClass(""); + $obj->setNextVideoOrder(0); + $obj->setParentId(0); + + $id = $obj->save(); + return self::getCategoryByName($name); + } + return $cat; + } + + public static function getCategoryDefault() + { + global $global; + $sql = "SELECT * FROM categories ORDER BY id ASC LIMIT 1"; + $res = sqlDAL::readSql($sql); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($result) { + $result['name'] = xss_esc_back($result['name']); + } + return ($res) ? $result : false; + } + + public static function getSiteCategoryDefaultID() + { + $obj = AVideoPlugin::getObjectDataIfEnabled("PredefinedCategory"); + $id = false; + if ($obj) { + $id = $obj->defaultCategory; + } else { + $row = self::getCategoryDefault(); + if ($row) { + $id = $row['id']; + } + } + return $id; + } + + public static function deleteCategoryCache() + { + _session_start(); + ObjectYPT::deleteAllSessionCache(); + clearFirstPageCache(); + unset($_SESSION['user']['sessionCache']); + $_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; + $cacheDir = ObjectYPT::getCacheDir() . 'category/'; + $rrmdir = rrmdir($cacheDir); + _error_log("deleteCategoryCache: {$cacheDir} = ". json_encode($rrmdir)); + } + + public static function getAllCategories($filterCanAddVideoOnly = false, $onlyWithVideos = false, $onlySuggested = false) + { + global $global, $config; + if ($config->currentVersionLowerThen('8.4')) { + return false; + } + $sql = "SELECT * FROM categories c WHERE 1=1 "; + if (!empty($_GET['parentsOnly'])) { + $sql .= "AND parentId = 0 "; + } + if ($onlySuggested) { + $sql .= "AND suggested = 1 "; + } + if ($filterCanAddVideoOnly && !User::isAdmin()) { + if (is_int($filterCanAddVideoOnly)) { + $users_id = $filterCanAddVideoOnly; + } else { + $users_id = User::getId(); + } + + if ($config->currentVersionGreaterThen('6.1')) { + $sql .= " AND (private=0 OR users_id = '{$users_id}') "; + } + } + if ($onlyWithVideos) { + $sql .= " AND ((SELECT count(*) FROM videos v where v.categories_id = c.id OR categories_id IN (SELECT id from categories where parentId = c.id)) > 0 "; + if (AVideoPlugin::isEnabledByName("Live")) { + $sql .= " OR " + . " (" + . " SELECT count(*) FROM live_transmitions lt where " + . " (lt.categories_id = c.id OR lt.categories_id IN (SELECT id from categories where parentId = c.id))" + //. " AND lt.id = (select id FROM live_transmitions lt2 WHERE lt.users_id = lt2.users_id ORDER BY CREATED DESC LIMIT 1 )" + . " ) > 0 "; + } + if (AVideoPlugin::isEnabledByName("LiveLinks")) { + $sql .= " OR " + . " (" + . " SELECT count(*) FROM LiveLinks ll where " + . " (ll.categories_id = c.id OR ll.categories_id IN (SELECT id from categories where parentId = c.id))" + . " ) > 0 "; + } + $sql .= ")"; + } + + $sortWhitelist = ['id', 'name', 'clean_name', 'description', 'iconClass', 'nextVideoOrder', 'parentId', 'type', 'users_id', 'private', 'allow_download', 'order', 'suggested']; + + if (!empty($_POST['sort']) && is_array($_POST['sort'])) { + foreach ($_POST['sort'] as $key => $value) { + if (!in_array($key, $sortWhitelist)) { + unset($_POST['sort'][$key]); + } + } + } + $sql .= BootGrid::getSqlFromPost(['name'], "", " ORDER BY `order`, name ASC "); + //echo $sql;exit; + $cacheName = 'category/' . md5($sql); + if (empty($_SESSION['user']['sessionCache']['getAllCategoriesClearCache'])) { + $category = object_to_array(ObjectYPT::getCache($cacheName, 36000)); + //var_dump($cacheName, ObjectYPT::getLastUsedCacheInfo(), fixPath(ObjectYPT::getCacheDir() . 'category/'));exit; + } else { + _session_start(); + unset($_SESSION['user']['sessionCache']['getAllCategoriesClearCache']); + } + if (empty($category)) { + $res = sqlDAL::readSql($sql); + $fullResult = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $category = []; + if ($res) { + foreach ($fullResult as $row) { + $totals = self::getTotalFromCategory($row['id']); + $fullTotals = self::getTotalFromCategory($row['id'], false, true, true); + + $row['name'] = $row['name']; + $row['total'] = $totals['total']; + $row['fullTotal'] = $fullTotals['total']; + $row['fullTotal_videos'] = $fullTotals['videos']; + $row['fullTotal_lives'] = $fullTotals['lives']; + $row['fullTotal_livelinks'] = $fullTotals['livelinks']; + $row['owner'] = User::getNameIdentificationById(@$row['users_id']); + $row['canEdit'] = self::userCanEditCategory($row['id']); + $row['canAddVideo'] = self::userCanAddInCategory($row['id']); + $row['hierarchy'] = self::getHierarchyString($row['parentId']); + $row['hierarchyAndName'] = $row['hierarchy'] . $row['name']; + $row['description_html'] = textToLink(htmlentities($row['description'])); + $category[] = $row; + } + //$category = $res->fetch_all(MYSQLI_ASSOC); + ObjectYPT::setCache($cacheName, $category); + } else { + $category = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + } + return $category; + } + + public static function getHierarchyArray($categories_id, $hierarchyArray = []) + { + if (empty($categories_id)) { + return $hierarchyArray; + } + $sql = "SELECT * FROM categories WHERE id=? "; + $res = sqlDAL::readSql($sql, "i", [$categories_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($result) { + $hierarchyArray[] = $result; + return self::getHierarchyArray($result['parentId'], $hierarchyArray); + } + return $hierarchyArray; + } + + public static function getHierarchyString($categories_id) + { + if (empty($categories_id)) { + return "/"; + } + $array = array_reverse(self::getHierarchyArray($categories_id)); + //$array = (self::getHierarchyArray($categories_id)); + //var_dump($array);exit; + if (empty($array)) { + return "/"; + } + $str = "/"; + foreach ($array as $value) { + $str .= xss_esc_back($value['name']) . "/"; + } + return $str; + } + + public static function userCanAddInCategory($categories_id, $users_id = 0) + { + if (empty($categories_id)) { + return false; + } + if (empty($users_id)) { + $users_id = User::getId(); + } + if (empty($users_id)) { + return false; + } + $cat = new Category($categories_id); + if (empty($cat->getPrivate()) || $users_id == $cat->getUsers_id()) { + return true; + } + return false; + } + + public static function userCanEditCategory($categories_id, $users_id = 0) + { + if (empty($categories_id)) { + return false; + } + if (empty($users_id)) { + $users_id = User::getId(); + } + if (empty($users_id)) { + return false; + } + + if (User::isAdmin()) { + return true; + } + + $cat = new Category($categories_id); + if ($users_id == $cat->getUsers_id()) { + return true; + } + return false; + } + + public static function canCreateCategory() + { + global $advancedCustomUser; + if (User::isAdmin()) { + return true; + } + if ($advancedCustomUser && $advancedCustomUser->usersCanCreateNewCategories && User::canUpload()) { + return true; + } + return false; + } + + public static function getChildCategories($parentId, $filterCanAddVideoOnly = false) + { + global $global, $config; + if ($config->currentVersionLowerThen('8.4')) { + return false; + } + $sql = "SELECT * FROM categories WHERE parentId=? AND id!=? "; + if ($filterCanAddVideoOnly && !User::isAdmin()) { + if (is_int($filterCanAddVideoOnly)) { + $users_id = $filterCanAddVideoOnly; + } else { + $users_id = User::getId(); + } + + if ($config->currentVersionGreaterThen('6.1')) { + $sql .= " AND (private=0 OR users_id = '{$users_id}') "; + } + } + $sql .= BootGrid::getSqlFromPost(['name'], "", " ORDER BY `order`, name ASC "); + $res = sqlDAL::readSql($sql, "ii", [$parentId, $parentId]); + $fullResult = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $category = []; + if ($res) { + foreach ($fullResult as $row) { + $totals = self::getTotalFromCategory($row['id']); + $row['name'] = xss_esc_back($row['name']); + $row['total'] = $totals['total']; + $row['total_array'] = $totals; + $category[] = $row; + } + } else { + $category = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $category; + } + + public static function getChildCategoriesFromTitle($clean_title) + { + $row = self::getCategoryByName($clean_title); + return self::getChildCategories($row['id']); + } + + public static function getTotalFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) + { + $videos = self::getTotalVideosFromCategory($categories_id, $showUnlisted, $getAllVideos, $renew); + $lives = self::getTotalLivesFromCategory($categories_id, $showUnlisted, $renew); + $livelinkss = self::getTotalLiveLinksFromCategory($categories_id, $showUnlisted, $renew); + $total = $videos + $lives + $livelinkss; + return ['videos' => $videos, 'lives' => $lives, 'livelinks' => $livelinkss, 'total' => $total]; + } + + public static function getTotalFromChildCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) + { + $categories = self::getChildCategories($categories_id); + $array = ['videos' => 0, 'lives' => 0, 'livelinks' => 0, 'total' => 0]; + foreach ($categories as $value) { + $totals = self::getTotalFromCategory($categories_id, $showUnlisted, $getAllVideos, $renew); + $array = [ + 'videos' => $array['videos'] + $totals['videos'], + 'lives' => $array['lives'] + $totals['lives'], + 'livelinks' => $array['livelinks'] + $totals['livelinks'], + 'total' => $array['total'] + $totals['total'], ]; + $totals = self::getTotalFromChildCategory($value['id'], $showUnlisted, $getAllVideos, $renew); + $array = [ + 'videos' => $array['videos'] + $totals['videos'], + 'lives' => $array['lives'] + $totals['lives'], + 'livelinks' => $array['livelinks'] + $totals['livelinks'], + 'total' => $array['total'] + $totals['total'], ]; + } + + return $array; + } + + public static function getTotalVideosFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false, $renew = false) + { + global $global, $config; + if ($renew || empty($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]['videos'])) { + $sql = "SELECT count(id) as total FROM videos v WHERE 1=1 AND categories_id = ? "; + + 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)) . "')"; + } + if (!$getAllVideos) { + $sql .= Video::getUserGroupsCanSeeSQL(); + } + //echo $categories_id, $sql;exit; + $res = sqlDAL::readSql($sql, "i", [$categories_id]); + $fullResult = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); + $rows = self::getChildCategories($categories_id); + foreach ($rows as $value) { + $total += self::getTotalVideosFromCategory($value['id'], $showUnlisted, $getAllVideos, $renew); + } + _session_start(); + $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]['videos'] = $total; + } + return $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][intval($getAllVideos)]['videos']; + } + + public static function getLatestVideoFromCategory($categories_id, $showUnlisted = false, $getAllVideos = false) + { + global $global, $config; + $sql = "SELECT * FROM videos v WHERE 1=1 AND (categories_id = ? OR categories_id IN (SELECT id from categories where parentId = ?))"; + + 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)) . "')"; + } + if (!$getAllVideos) { + $sql .= Video::getUserGroupsCanSeeSQL(); + } + $sql .= "ORDER BY created DESC LIMIT 1"; + //var_dump($sql, $categories_id); + $res = sqlDAL::readSql($sql, "ii", [$categories_id, $categories_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return $result; + } + + public static function getLatestLiveFromCategory($categories_id) + { + if (!AVideoPlugin::isEnabledByName("Live")) { + return []; + } + global $global, $config; + $sql = "SELECT * FROM live_transmitions lt LEFT JOIN live_transmitions_history lth ON lt.users_id = lth.users_id " + . " WHERE 1=1 AND (categories_id = ? OR categories_id IN (SELECT id from categories where parentId = ?))"; + + $sql .= "ORDER BY lth.created DESC LIMIT 1"; + //var_dump($sql, $categories_id); + $res = sqlDAL::readSql($sql, "ii", [$categories_id, $categories_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return $result; + } + + public static function getLatestLiveLinksFromCategory($categories_id) + { + if (AVideoPlugin::isEnabledByName("LiveLinks")) { + return []; + } + global $global, $config; + $sql = "SELECT * FROM livelinks WHERE 1=1 AND (categories_id = ? OR categories_id IN (SELECT id from categories where parentId = ?))"; + + $sql .= "ORDER BY created DESC LIMIT 1"; + //var_dump($sql, $categories_id); + $res = sqlDAL::readSql($sql, "ii", [$categories_id, $categories_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return $result; + } + + public static function getTotalLiveLinksFromCategory($categories_id, $showUnlisted = false, $renew = false) + { + global $global; + + if (!AVideoPlugin::isEnabledByName("LiveLinks")) { + return 0; + } + + if ($renew || empty($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['livelinks'])) { + $sql = "SELECT count(id) as total FROM LiveLinks v WHERE 1=1 AND categories_id = ? "; + + if (empty($showUnlisted)) { + $sql .= " AND `type` = 'public' "; + } + + //echo $categories_id, $sql;exit; + $res = sqlDAL::readSql($sql, "i", [$categories_id]); + $fullResult = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); + $rows = self::getChildCategories($categories_id); + foreach ($rows as $value) { + $total += self::getTotalLivesFromCategory($value['id'], $showUnlisted, $renew); + } + _session_start(); + $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['livelinks'] = $total; + } + return $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['livelinks']; + } + + public static function getTotalLivesFromCategory($categories_id, $showUnlisted = false, $renew = false) + { + if (!AVideoPlugin::isEnabledByName("Live")) { + return 0; + } + + global $global; + if ($renew || empty($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['live'])) { + $sql = "SELECT count(id) as total FROM live_transmitions v WHERE 1=1 AND categories_id = ? "; + + if (empty($showUnlisted)) { + $sql .= " AND public = 1 "; + } + + //echo $categories_id, $sql;exit; + $res = sqlDAL::readSql($sql, "i", [$categories_id]); + $fullResult = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $total = empty($fullResult[0]['total']) ? 0 : intval($fullResult[0]['total']); + $rows = self::getChildCategories($categories_id); + foreach ($rows as $value) { + $total += self::getTotalLivesFromCategory($value['id'], $showUnlisted, $renew); + } + _session_start(); + $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['live'] = $total; + } + return $_SESSION['user']['sessionCache']['categoryTotal'][$categories_id][intval($showUnlisted)][0]['live']; + } + + public static function clearCacheCount($categories_id = 0) + { + // clear category count cache + _session_start(); + if (empty($categories_id)) { + unset($_SESSION['user']['sessionCache']['categoryTotal']); + $_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; + } else { + unset($_SESSION['user']['sessionCache']['categoryTotal'][$categories_id]); + } + //session_write_close(); + } + + public static function getTotalCategories($filterCanAddVideoOnly = false, $onlyWithVideos = false, $onlySuggested = false) + { + global $global, $config; + + if ($config->currentVersionLowerThen('5.01')) { + return false; + } + $sql = "SELECT id, parentId FROM categories c WHERE 1=1 "; + if ($onlySuggested) { + $sql .= "AND suggested = 1 "; + } + if ($filterCanAddVideoOnly && !User::isAdmin()) { + if (is_int($filterCanAddVideoOnly)) { + $users_id = $filterCanAddVideoOnly; + } else { + $users_id = User::getId(); + } + + if ($config->currentVersionGreaterThen('6.1')) { + $sql .= " AND (private=0 OR users_id = '{$users_id}') "; + } + } + if (!empty($_GET['parentsOnly'])) { + $sql .= "AND parentId = 0 OR parentId = -1 "; + } + if ($onlyWithVideos) { + $sql .= " AND ((SELECT count(*) FROM videos v where v.categories_id = c.id OR categories_id IN (SELECT id from categories where parentId = c.id)) > 0 "; + if (AVideoPlugin::isEnabledByName("Live")) { + $sql .= " OR " + . " (" + . " SELECT count(*) FROM live_transmitions lt where " + . " (lt.categories_id = c.id OR lt.categories_id IN (SELECT id from categories where parentId = c.id))" + //. " AND lt.id = (select id FROM live_transmitions lt2 WHERE lt.users_id = lt2.users_id ORDER BY CREATED DESC LIMIT 1 )" + . " ) > 0 "; + } + if (AVideoPlugin::isEnabledByName("LiveLinks")) { + $sql .= " OR " + . " (" + . " SELECT count(*) FROM LiveLinks ll where " + . " (ll.categories_id = c.id OR ll.categories_id IN (SELECT id from categories where parentId = c.id))" + . " ) > 0 "; + } + $sql .= ")"; + } + $sql .= BootGrid::getSqlSearchFromPost(['name']); + //echo $sql;exit; + $res = sqlDAL::readSql($sql); + $numRows = sqlDal::num_rows($res); + sqlDAL::close($res); + return $numRows; + } + + public function getIconClass() + { + if (empty($this->iconClass)) { + return "fa fa-folder"; + } + return $this->iconClass; + } + + public function setIconClass($iconClass) + { + $this->iconClass = $iconClass; + } + + public function getName() + { + return $this->name; + } + + public function getClean_name() + { + return $this->clean_name; + } + + public function getDescription() + { + return $this->description; + } + + public function getAllow_download() + { + return $this->allow_download; + } + + public function setAllow_download($allow_download) + { + $this->allow_download = intval($allow_download); + } + + public static function getCategoryDirPath($categories_id = "") + { + global $global; + + $dir = "videos/categories/assets/"; + if (!empty($categories_id)) { + $dir .= $categories_id . "/"; + } + + $path = []; + $path['dir'] = "{$global['systemRootPath']}{$dir}"; + make_path($path['dir']); + $path['path'] = "{$global['systemRootPath']}{$dir}"; + $path['url'] = getCDN() . "{$dir}"; + return $path; + } + + public static function isAssetsValids($categories_id) + { + $photo = Category::getCategoryPhotoPath($categories_id); + $background = Category::getCategoryBackgroundPath($categories_id); + //var_dump(filesize($background['path']), $background['path'], filesize($photo['path']), $photo['path'] ); + if (!file_exists($photo['path']) || !file_exists($background['path'])) { + return false; + } + if (filesize($photo['path']) <= 190) { // transparent image + return false; + } + if (filesize($background['path']) <= 980 || filesize($background['path']) == 4480) { // transparent image + return false; + } + return true; + } + + public static function getOGImagePaths($categories_id) + { + $name = "og_200X200.jpg"; + $dirPaths = self::getCategoryDirPath($categories_id); + $path = []; + $path['dir'] = $dirPaths['url']; + $path['path'] = "{$dirPaths['path']}{$name}"; + $path['url'] = "{$dirPaths['url']}{$name}"; + if (file_exists($path['path'])) { + $path['url+timestamp'] = "{$path['url']}?" . filectime($path['path']); + } else { + $path['url+timestamp'] = $path['url']; + } + return $path; + } + + public static function deleteOGImage($categories_id) + { + $ogPaths = self::getOGImagePaths($categories_id); + $destination = $ogPaths['path']; + if (file_exists($destination)) { + unlink($destination); + } + } + + public static function getOGImage($categories_id) + { + global $global; + $isAssetsValids = self::isAssetsValids($categories_id); + if ($isAssetsValids) { + $ogPaths = self::getOGImagePaths($categories_id); + $destination = $ogPaths['path']; + if (!file_exists($destination)) { + $photo = self::getCategoryPhotoPath($categories_id); + $source = $photo['path']; + convertImageToOG($source, $destination); + } + + return $ogPaths['url+timestamp']; + } else { + return Configuration::getOGImage(); + } + } + + public static function getCategoryPhotoPath($categories_id) + { + $path = self::getCategoryAssetPath("photo.png", $categories_id); + return $path; + } + + public static function getCategoryBackgroundPath($categories_id) + { + $path = self::getCategoryAssetPath("background.png", $categories_id); + return $path; + } + + private static function getCategoryAssetPath($name, $categories_id) + { + if (empty($categories_id)) { + return false; + } + if (empty($name)) { + return false; + } + + $dirPaths = self::getCategoryDirPath($categories_id); + + global $global; + + $path = []; + $path['dir'] = $dirPaths['url']; + $path['path'] = "{$dirPaths['path']}{$name}"; + $path['url'] = "{$dirPaths['url']}{$name}"; + if (file_exists($path['path'])) { + $path['url+timestamp'] = "{$path['url']}?" . filectime($path['path']); + } else { + $path['url+timestamp'] = $path['url']; + } + return $path; + } +} diff --git a/objects/categoryAddNew.json.php b/objects/categoryAddNew.json.php index 3aed1e77b1..5d7f55beea 100644 --- a/objects/categoryAddNew.json.php +++ b/objects/categoryAddNew.json.php @@ -1,48 +1,48 @@ -error = true; -$obj->msg = true; -$obj->categories_id = 0; -$obj->image1 = 0; -$obj->image2 = 0; - -if(!Category::canCreateCategory()){ - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -$objCat = new Category(intval(@$_POST['id'])); -$objCat->setName($_POST['name']); -$objCat->setClean_name($_POST['clean_name']); -$objCat->setDescription($_POST['description']); -$objCat->setIconClass($_POST['iconClass']); -//$objCat->setNextVideoOrder($_POST['nextVideoOrder']); -$objCat->setSuggested($_POST['suggested']); -$objCat->setParentId($_POST['parentId']); -$objCat->setPrivate($_POST['private']); -$objCat->setAllow_download($_POST['allow_download']); -$objCat->setOrder($_POST['order']); - -$obj->categories_id = $objCat->save(); -//$objCat->setType($_POST['type'],$id); - -if(!empty($obj->categories_id)){ - $obj->error = false; - $path = Category::getCategoryPhotoPath($obj->categories_id); - $obj->image1 = saveCroppieImage($path['path'], "image1"); - $obj->image1P = $path['path']; - $path = Category::getCategoryBackgroundPath($obj->categories_id); - $obj->image2 = saveCroppieImage($path['path'], "image2"); - $obj->image2P = $path['path']; -} - -die(json_encode($obj)); +error = true; +$obj->msg = true; +$obj->categories_id = 0; +$obj->image1 = 0; +$obj->image2 = 0; + +if (!Category::canCreateCategory()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +$objCat = new Category(intval(@$_POST['id'])); +$objCat->setName($_POST['name']); +$objCat->setClean_name($_POST['clean_name']); +$objCat->setDescription($_POST['description']); +$objCat->setIconClass($_POST['iconClass']); +//$objCat->setNextVideoOrder($_POST['nextVideoOrder']); +$objCat->setSuggested($_POST['suggested']); +$objCat->setParentId($_POST['parentId']); +$objCat->setPrivate($_POST['private']); +$objCat->setAllow_download($_POST['allow_download']); +$objCat->setOrder($_POST['order']); + +$obj->categories_id = $objCat->save(); +//$objCat->setType($_POST['type'],$id); + +if (!empty($obj->categories_id)) { + $obj->error = false; + $path = Category::getCategoryPhotoPath($obj->categories_id); + $obj->image1 = saveCroppieImage($path['path'], "image1"); + $obj->image1P = $path['path']; + $path = Category::getCategoryBackgroundPath($obj->categories_id); + $obj->image2 = saveCroppieImage($path['path'], "image2"); + $obj->image2P = $path['path']; +} + +die(json_encode($obj)); diff --git a/objects/categoryDelete.json.php b/objects/categoryDelete.json.php index 4fac5fa306..610c29b25c 100644 --- a/objects/categoryDelete.json.php +++ b/objects/categoryDelete.json.php @@ -1,14 +1,14 @@ -delete().'"}'; +delete().'"}'; diff --git a/objects/comment.php b/objects/comment.php index 7fc3fc37ab..743a297d82 100644 --- a/objects/comment.php +++ b/objects/comment.php @@ -1,359 +1,359 @@ -comment = xss_esc($comment); - $this->videos_id = $videos_id; - $this->users_id = User::getId(); - } else { - // get data from id - $this->load($id); - } - } - - public function getId() - { - return $this->id; - } - - - public function setComments_id_pai($comments_id_pai) - { - $this->comments_id_pai = $comments_id_pai; - } - - public function getComments_id_pai() - { - return $this->comments_id_pai; - } - - public function getUsers_id() - { - return $this->users_id; - } - - public function setComment($comment) - { - $this->comment = xss_esc($comment); - } - - public function getVideos_id() - { - return $this->videos_id; - } - - private function load($id) - { - $row = $this->getComment($id); - if (empty($row)) { - return false; - } - foreach ($row as $key => $value) { - $this->$key = $value; - } - return true; - } - - public function save() - { - global $global; - if (!User::isLogged()) { - header('Content-Type: application/json'); - die('{"error":"'.__("Permission denied").'"}'); - } - //$this->comment = htmlentities($this->comment); - $this->comment = $global['mysqli']->real_escape_string($this->comment); - - if (empty($this->comment)) { - return false; - } - - if (empty($this->comments_id_pai)) { - $this->comments_id_pai = 'NULL'; - } - - if (empty($this->videos_id) && !empty($this->comments_id_pai)) { - $comment = new Comment("", 0, $this->comments_id_pai); - $this->videos_id = $comment->getVideos_id(); - } - - if (!empty($this->id)) { - if (!self::userCanAdminComment($this->id)) { - return false; - } - $sql = "UPDATE comments SET " - . " comment = ?, modified = now() WHERE id = ?"; - $resp = sqlDAL::writeSql($sql, "si", array(xss_esc($this->comment),$this->id)); - } else { - $id = User::getId(); - $sql = "INSERT INTO comments ( comment,users_id, videos_id, comments_id_pai, created, modified) VALUES " - . " (?, ?, ?, {$this->comments_id_pai}, now(), now())"; - $resp = sqlDAL::writeSql($sql, "sii", array(xss_esc($this->comment),$id,$this->videos_id)); - } - if ((empty($resp))&&($global['mysqli']->errno!=0)) { - die('Error (comment save) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - if (empty($this->id)) { - // log_error("note: insert_id works? ".$global['mysqli']->insert_id); // success! - $id = $global['mysqli']->insert_id; - $this->id = $id; - } else { - $id = $this->id; - } - if (empty($this->comments_id_pai) || $this->comments_id_pai== 'NULL') { - AVideoPlugin::afterNewComment($this->id); - } else { - AVideoPlugin::afterNewResponse($this->id); - } - return $resp; - } - - public function delete() - { - if (!self::userCanAdminComment($this->id)) { - return false; - } - - global $global; - if (!empty($this->id)) { - $sql = "DELETE FROM comments WHERE id = ?"; - } else { - return false; - } - return sqlDAL::writeSql($sql, "i", array($this->id)); - } - - private function getComment($id) - { - global $global; - $id = intval($id); - $sql = "SELECT * FROM comments WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "i", array($id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return ($res!=false) ? $result : false; - } - - public static function getAllComments($videoId = 0, $comments_id_pai = 'NULL') - { - global $global; - $format = ""; - $values = array(); - $sql = "SELECT c.*, u.name as name, u.user as user, " - . " (SELECT count(id) FROM comments_likes as l where l.comments_id = c.id AND `like` = 1 ) as likes, " - . " (SELECT count(id) FROM comments_likes as l where l.comments_id = c.id AND `like` = -1 ) as dislikes "; - - if (User::isLogged()) { - $sql .= ", (SELECT `like` FROM comments_likes as l where l.comments_id = c.id AND users_id = ? ) as myVote "; - $format .= "i"; - $values[]=User::getId(); - } else { - $sql .= ", 0 as myVote "; - } - - $sql .= " FROM comments c LEFT JOIN users as u ON u.id = users_id LEFT JOIN videos as v ON v.id = videos_id WHERE 1=1 "; - - if (!empty($videoId)) { - $sql .= " AND videos_id = ? "; - $format .= "i"; - $values[] = $videoId; - } elseif (!Permissions::canAdminComment() && empty($comments_id_pai)) { - if (!User::isLogged()) { - die("can not see comments"); - } - $users_id = User::getId(); - $sql .= " AND (v.users_id = ? OR c.users_id = ?) "; - $format .= "ii"; - $values[]=$users_id; - $values[]=$users_id; - } - - if ($comments_id_pai==='NULL' || empty($comments_id_pai)) { - $sql .= " AND (comments_id_pai IS NULL "; - if (empty($videoId) && User::isLogged()) { - $users_id = User::getId(); - $sql .= " OR c.users_id = ? "; - $format .= "i"; - $values[]=$users_id; - } - $sql .= ") "; - } else { - $sql .= " AND comments_id_pai = ? "; - $format .= "s"; - $values[]=$comments_id_pai; - } - - $sql .= BootGrid::getSqlFromPost(array('name')); - $res = sqlDAL::readSql($sql, $format, $values); - $allData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $comment = array(); - if ($res!=false) { - foreach ($allData as $row) { - $row = cleanUpRowFromDatabase($row); - $row['comment'] = str_replace('\n', "\n", $row['comment']); - $row['commentPlain'] = xss_esc_back($row['comment']); - $row['commentHTML'] = nl2br($row['commentPlain']); - $comment[] = $row; - } - //$comment = $res->fetch_all(MYSQLI_ASSOC); - } else { - $comment = false; - die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $comment; - } - - public static function getTotalComments($videoId = 0, $comments_id_pai = 'NULL', $video_owner_users_id=0) - { - global $global; - $format = ""; - $values = array(); - $sql = "SELECT c.id FROM comments c LEFT JOIN users as u ON u.id = users_id LEFT JOIN videos as v ON v.id = videos_id WHERE 1=1 "; - - if (!empty($videoId)) { - $sql .= " AND videos_id = ? "; - $format .= "i"; - $values[] = $videoId; - } elseif (!Permissions::canAdminComment() && empty($comments_id_pai)) { - if (!User::isLogged()) { - die("can not see comments"); - } - $users_id = User::getId(); - $sql .= " AND (v.users_id = ? OR c.users_id = ?) "; - $format .= "ii"; - $values[] = $users_id; - $values[] = $users_id; - } - - if ($comments_id_pai==='NULL' || empty($comments_id_pai)) { - $sql .= " AND (comments_id_pai IS NULL "; - if (empty($videoId) && User::isLogged()) { - $users_id = User::getId(); - $sql .= " OR c.users_id = ? "; - $format .= "i"; - $values[] = $users_id; - } - $sql .= ") "; - } else { - $sql .= " AND comments_id_pai = ? "; - $format .= "s"; - $values[] = $comments_id_pai; - } - - if (!empty($video_owner_users_id)) { - $sql .= " AND v.users_id = ? "; - $format .= "i"; - $values[] = $video_owner_users_id; - } - - $sql .= BootGrid::getSqlSearchFromPost(array('name')); - - $res = sqlDAL::readSql($sql, $format, $values); - $countRow = sqlDAL::num_rows($res); - sqlDAL::close($res); - - return $countRow; - } - - public static function userCanAdminComment($comments_id) - { - if (!User::isLogged()) { - return false; - } - if (Permissions::canAdminComment()) { - return true; - } - $obj = new Comment("", 0, $comments_id); - if ($obj->users_id == User::getId()) { - return true; - } - $video = new Video("", "", $obj->videos_id); - if ($video->getUsers_id() == User::getId()) { - return true; - } - return false; - } - - public static function userCanEditComment($comments_id) - { - if (!User::isLogged()) { - return false; - } - if (Permissions::canAdminComment()) { - return true; - } - $obj = new Comment("", 0, $comments_id); - if ($obj->users_id == User::getId()) { - return true; - } - return false; - } - - public static function getTotalCommentsThumbsUpFromUser($users_id, $startDate, $endDate) - { - global $global; - $sql = "SELECT id from comments WHERE users_id = ?"; - $res = sqlDAL::readSql($sql, "i", array($users_id)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $r = array('thumbsUp'=>0, 'thumbsDown'=>0 ); - if ($res!=false) { - foreach ($fullData as $row) { - $format = "i"; - $values = array($row['id']); - $sql = "SELECT id from comments_likes WHERE comments_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 = "i"; - $values = array($row['id']); - $sql = "SELECT id from comments_likes WHERE comments_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; - } -} +comment = xss_esc($comment); + $this->videos_id = $videos_id; + $this->users_id = User::getId(); + } else { + // get data from id + $this->load($id); + } + } + + public function getId() + { + return $this->id; + } + + + public function setComments_id_pai($comments_id_pai) + { + $this->comments_id_pai = $comments_id_pai; + } + + public function getComments_id_pai() + { + return $this->comments_id_pai; + } + + public function getUsers_id() + { + return $this->users_id; + } + + public function setComment($comment) + { + $this->comment = xss_esc($comment); + } + + public function getVideos_id() + { + return $this->videos_id; + } + + private function load($id) + { + $row = $this->getComment($id); + if (empty($row)) { + return false; + } + foreach ($row as $key => $value) { + $this->$key = $value; + } + return true; + } + + public function save() + { + global $global; + if (!User::isLogged()) { + header('Content-Type: application/json'); + die('{"error":"'.__("Permission denied").'"}'); + } + //$this->comment = htmlentities($this->comment); + $this->comment = $global['mysqli']->real_escape_string($this->comment); + + if (empty($this->comment)) { + return false; + } + + if (empty($this->comments_id_pai)) { + $this->comments_id_pai = 'NULL'; + } + + if (empty($this->videos_id) && !empty($this->comments_id_pai)) { + $comment = new Comment("", 0, $this->comments_id_pai); + $this->videos_id = $comment->getVideos_id(); + } + + if (!empty($this->id)) { + if (!self::userCanAdminComment($this->id)) { + return false; + } + $sql = "UPDATE comments SET " + . " comment = ?, modified = now() WHERE id = ?"; + $resp = sqlDAL::writeSql($sql, "si", [xss_esc($this->comment),$this->id]); + } else { + $id = User::getId(); + $sql = "INSERT INTO comments ( comment,users_id, videos_id, comments_id_pai, created, modified) VALUES " + . " (?, ?, ?, {$this->comments_id_pai}, now(), now())"; + $resp = sqlDAL::writeSql($sql, "sii", [xss_esc($this->comment),$id,$this->videos_id]); + } + if ((empty($resp))&&($global['mysqli']->errno!=0)) { + die('Error (comment save) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + if (empty($this->id)) { + // log_error("note: insert_id works? ".$global['mysqli']->insert_id); // success! + $id = $global['mysqli']->insert_id; + $this->id = $id; + } else { + $id = $this->id; + } + if (empty($this->comments_id_pai) || $this->comments_id_pai== 'NULL') { + AVideoPlugin::afterNewComment($this->id); + } else { + AVideoPlugin::afterNewResponse($this->id); + } + return $resp; + } + + public function delete() + { + if (!self::userCanAdminComment($this->id)) { + return false; + } + + global $global; + if (!empty($this->id)) { + $sql = "DELETE FROM comments WHERE id = ?"; + } else { + return false; + } + return sqlDAL::writeSql($sql, "i", [$this->id]); + } + + private function getComment($id) + { + global $global; + $id = intval($id); + $sql = "SELECT * FROM comments WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return ($res!=false) ? $result : false; + } + + public static function getAllComments($videoId = 0, $comments_id_pai = 'NULL') + { + global $global; + $format = ''; + $values = []; + $sql = "SELECT c.*, u.name as name, u.user as user, " + . " (SELECT count(id) FROM comments_likes as l where l.comments_id = c.id AND `like` = 1 ) as likes, " + . " (SELECT count(id) FROM comments_likes as l where l.comments_id = c.id AND `like` = -1 ) as dislikes "; + + if (User::isLogged()) { + $sql .= ", (SELECT `like` FROM comments_likes as l where l.comments_id = c.id AND users_id = ? ) as myVote "; + $format .= "i"; + $values[]=User::getId(); + } else { + $sql .= ", 0 as myVote "; + } + + $sql .= " FROM comments c LEFT JOIN users as u ON u.id = users_id LEFT JOIN videos as v ON v.id = videos_id WHERE 1=1 "; + + if (!empty($videoId)) { + $sql .= " AND videos_id = ? "; + $format .= "i"; + $values[] = $videoId; + } elseif (!Permissions::canAdminComment() && empty($comments_id_pai)) { + if (!User::isLogged()) { + die("can not see comments"); + } + $users_id = User::getId(); + $sql .= " AND (v.users_id = ? OR c.users_id = ?) "; + $format .= "ii"; + $values[]=$users_id; + $values[]=$users_id; + } + + if ($comments_id_pai==='NULL' || empty($comments_id_pai)) { + $sql .= " AND (comments_id_pai IS NULL "; + if (empty($videoId) && User::isLogged()) { + $users_id = User::getId(); + $sql .= " OR c.users_id = ? "; + $format .= "i"; + $values[]=$users_id; + } + $sql .= ") "; + } else { + $sql .= " AND comments_id_pai = ? "; + $format .= "s"; + $values[]=$comments_id_pai; + } + + $sql .= BootGrid::getSqlFromPost(['name']); + $res = sqlDAL::readSql($sql, $format, $values); + $allData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $comment = []; + if ($res!=false) { + foreach ($allData as $row) { + $row = cleanUpRowFromDatabase($row); + $row['comment'] = str_replace('\n', "\n", $row['comment']); + $row['commentPlain'] = xss_esc_back($row['comment']); + $row['commentHTML'] = nl2br($row['commentPlain']); + $comment[] = $row; + } + //$comment = $res->fetch_all(MYSQLI_ASSOC); + } else { + $comment = false; + die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $comment; + } + + public static function getTotalComments($videoId = 0, $comments_id_pai = 'NULL', $video_owner_users_id=0) + { + global $global; + $format = ''; + $values = []; + $sql = "SELECT c.id FROM comments c LEFT JOIN users as u ON u.id = users_id LEFT JOIN videos as v ON v.id = videos_id WHERE 1=1 "; + + if (!empty($videoId)) { + $sql .= " AND videos_id = ? "; + $format .= "i"; + $values[] = $videoId; + } elseif (!Permissions::canAdminComment() && empty($comments_id_pai)) { + if (!User::isLogged()) { + die("can not see comments"); + } + $users_id = User::getId(); + $sql .= " AND (v.users_id = ? OR c.users_id = ?) "; + $format .= "ii"; + $values[] = $users_id; + $values[] = $users_id; + } + + if ($comments_id_pai==='NULL' || empty($comments_id_pai)) { + $sql .= " AND (comments_id_pai IS NULL "; + if (empty($videoId) && User::isLogged()) { + $users_id = User::getId(); + $sql .= " OR c.users_id = ? "; + $format .= "i"; + $values[] = $users_id; + } + $sql .= ") "; + } else { + $sql .= " AND comments_id_pai = ? "; + $format .= "s"; + $values[] = $comments_id_pai; + } + + if (!empty($video_owner_users_id)) { + $sql .= " AND v.users_id = ? "; + $format .= "i"; + $values[] = $video_owner_users_id; + } + + $sql .= BootGrid::getSqlSearchFromPost(['name']); + + $res = sqlDAL::readSql($sql, $format, $values); + $countRow = sqlDAL::num_rows($res); + sqlDAL::close($res); + + return $countRow; + } + + public static function userCanAdminComment($comments_id) + { + if (!User::isLogged()) { + return false; + } + if (Permissions::canAdminComment()) { + return true; + } + $obj = new Comment("", 0, $comments_id); + if ($obj->users_id == User::getId()) { + return true; + } + $video = new Video("", "", $obj->videos_id); + if ($video->getUsers_id() == User::getId()) { + return true; + } + return false; + } + + public static function userCanEditComment($comments_id) + { + if (!User::isLogged()) { + return false; + } + if (Permissions::canAdminComment()) { + return true; + } + $obj = new Comment("", 0, $comments_id); + if ($obj->users_id == User::getId()) { + return true; + } + return false; + } + + public static function getTotalCommentsThumbsUpFromUser($users_id, $startDate, $endDate) + { + global $global; + $sql = "SELECT id from comments WHERE users_id = ?"; + $res = sqlDAL::readSql($sql, "i", [$users_id]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $r = ['thumbsUp'=>0, 'thumbsDown'=>0 ]; + if ($res!=false) { + foreach ($fullData as $row) { + $format = "i"; + $values = [$row['id']]; + $sql = "SELECT id from comments_likes WHERE comments_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 = "i"; + $values = [$row['id']]; + $sql = "SELECT id from comments_likes WHERE comments_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; + } +} diff --git a/objects/commentAddNew.json.php b/objects/commentAddNew.json.php index 8f289da64f..bdf4c5afb4 100644 --- a/objects/commentAddNew.json.php +++ b/objects/commentAddNew.json.php @@ -1,128 +1,129 @@ - $value) { - $_REQUEST[$key]=$value; - } -} - -if(!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])){ - $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); - $user->login(false, true); -} - -$obj = new stdClass(); -$obj->error = true; -$obj->msg = ''; - -if (!User::canComment()) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -function isCommentASpam($comment, $videos_id){ - $comment = trim($comment); - $obj = new stdClass(); - $obj->error = true; - $obj->msg = ''; - $obj->time = time(); - if(empty($comment)){ - $obj->msg = __('Comment is empty'); - return $obj; - } - if(empty($videos_id)){ - $obj->msg = __('Video is empty'); - return $obj; - } - _session_start(); - if(!isset($_SESSION['comments'])){ - $_SESSION['comments'] = array(); - } - - // you can only comment each 5 seconds - $rest = $_SESSION['comments']['_avideo_last_comment'] - ($obj->time-5); - if($rest>0){ - $obj->msg = __('You just comment something, please wait to comment again').', '.$rest.' '.__('Seconds'); - return $obj; - } - - // if you already comment 3 times or more on the same video you must wait 30 seconds - if($_SESSION['comments']['_avideo_count_comments_'.$videos_id]>3){ - $rest = $_SESSION['comments']['_avideo_last_comment'] - ($obj->time-30); - if($rest>0){ - $obj->msg = __('You just comment something, please wait to comment again').', '.$rest.' '.__('Seconds'); - return $obj; - } - } - - $index = preg_replace('/[^0-9a-z]/i', '', $comment); - $obj->index = $index; - // you can only repeat the comment (equal or similar) each 60 seconds - if(!empty($_SESSION['comments'][$index])){ - $rest = $_SESSION['comments'][$index]->time - ($obj->time-60); - if($rest>0){ - $obj->msg = __('You just comment something similar, please wait to comment again').', '.$rest.' '.__('Seconds'); - return $obj; - } - } - - if(empty($_SESSION['comments']['_avideo_count_comments_'.$videos_id])){ - $_SESSION['comments']['_avideo_count_comments_'.$videos_id] = 1; - }else{ - $_SESSION['comments']['_avideo_count_comments_'.$videos_id]++; - } - - $_SESSION['comments']['_avideo_last_comment'] = $obj->time; - $obj->error = false; - $_SESSION['comments'][$index] = $obj; - - return $obj; -} - -require_once 'comment.php'; -if(empty($_REQUEST['video']) && !empty($_REQUEST['comments_id'])){ - $c = new Comment('', '', $_REQUEST['comments_id']); - $_REQUEST['video'] = $c->getVideos_id(); -} - -$isSpam = isCommentASpam($_REQUEST['comment'], $_REQUEST['video']); -if($isSpam->error){ - $obj->msg = $isSpam->msg; - die(json_encode($obj)); -} - -if(!empty($_REQUEST['id'])){ - $_REQUEST['id'] = intval($_REQUEST['id']); - if(Comment::userCanEditComment($_REQUEST['id'])){ - $objC = new Comment("", 0, $_REQUEST['id']); - $objC->setComment($_REQUEST['comment']); - } -}else{ - $objC = new Comment($_REQUEST['comment'], $_REQUEST['video']); - $objC->setComments_id_pai($_REQUEST['comments_id']); -} - -$obj->comments_id = $objC->save(); -if(!empty($obj->comments_id)){ - $obj->error = false; - $obj->msg = __("Your comment has been saved!"); -}else{ - $obj->msg = __("Your comment has NOT been saved!"); -} -die(json_encode($obj)); + $value) { + $_REQUEST[$key]=$value; + } +} + +if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { + $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); + $user->login(false, true); +} + +$obj = new stdClass(); +$obj->error = true; +$obj->msg = ''; + +if (!User::canComment()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +function isCommentASpam($comment, $videos_id) +{ + $comment = trim($comment); + $obj = new stdClass(); + $obj->error = true; + $obj->msg = ''; + $obj->time = time(); + if (empty($comment)) { + $obj->msg = __('Comment is empty'); + return $obj; + } + if (empty($videos_id)) { + $obj->msg = __('Video is empty'); + return $obj; + } + _session_start(); + if (!isset($_SESSION['comments'])) { + $_SESSION['comments'] = []; + } + + // you can only comment each 5 seconds + $rest = $_SESSION['comments']['_avideo_last_comment'] - ($obj->time-5); + if ($rest>0) { + $obj->msg = __('You just comment something, please wait to comment again').', '.$rest.' '.__('Seconds'); + return $obj; + } + + // if you already comment 3 times or more on the same video you must wait 30 seconds + if ($_SESSION['comments']['_avideo_count_comments_'.$videos_id]>3) { + $rest = $_SESSION['comments']['_avideo_last_comment'] - ($obj->time-30); + if ($rest>0) { + $obj->msg = __('You just comment something, please wait to comment again').', '.$rest.' '.__('Seconds'); + return $obj; + } + } + + $index = preg_replace('/[^0-9a-z]/i', '', $comment); + $obj->index = $index; + // you can only repeat the comment (equal or similar) each 60 seconds + if (!empty($_SESSION['comments'][$index])) { + $rest = $_SESSION['comments'][$index]->time - ($obj->time-60); + if ($rest>0) { + $obj->msg = __('You just comment something similar, please wait to comment again').', '.$rest.' '.__('Seconds'); + return $obj; + } + } + + if (empty($_SESSION['comments']['_avideo_count_comments_'.$videos_id])) { + $_SESSION['comments']['_avideo_count_comments_'.$videos_id] = 1; + } else { + $_SESSION['comments']['_avideo_count_comments_'.$videos_id]++; + } + + $_SESSION['comments']['_avideo_last_comment'] = $obj->time; + $obj->error = false; + $_SESSION['comments'][$index] = $obj; + + return $obj; +} + +require_once 'comment.php'; +if (empty($_REQUEST['video']) && !empty($_REQUEST['comments_id'])) { + $c = new Comment('', '', $_REQUEST['comments_id']); + $_REQUEST['video'] = $c->getVideos_id(); +} + +$isSpam = isCommentASpam($_REQUEST['comment'], $_REQUEST['video']); +if ($isSpam->error) { + $obj->msg = $isSpam->msg; + die(json_encode($obj)); +} + +if (!empty($_REQUEST['id'])) { + $_REQUEST['id'] = intval($_REQUEST['id']); + if (Comment::userCanEditComment($_REQUEST['id'])) { + $objC = new Comment("", 0, $_REQUEST['id']); + $objC->setComment($_REQUEST['comment']); + } +} else { + $objC = new Comment($_REQUEST['comment'], $_REQUEST['video']); + $objC->setComments_id_pai($_REQUEST['comments_id']); +} + +$obj->comments_id = $objC->save(); +if (!empty($obj->comments_id)) { + $obj->error = false; + $obj->msg = __("Your comment has been saved!"); +} else { + $obj->msg = __("Your comment has NOT been saved!"); +} +die(json_encode($obj)); diff --git a/objects/commentDelete.json.php b/objects/commentDelete.json.php index a6ccfc54fa..19cfc0f2c5 100644 --- a/objects/commentDelete.json.php +++ b/objects/commentDelete.json.php @@ -1,14 +1,14 @@ -delete().'"}'; +delete().'"}'; diff --git a/objects/comments.json.php b/objects/comments.json.php index 9b8f7783c1..750864764f 100644 --- a/objects/comments.json.php +++ b/objects/comments.json.php @@ -1,31 +1,32 @@ -"); - return stripslashes(str_replace($search, $replace, $subject)); -} - -foreach ($comments as $key => $value) { - $name = User::getNameIdentificationById($value['users_id']); - $comments[$key]['comment'] = '
User Photo
'.$name.' '.humanTiming(strtotime($value['created'])).'
'. fixCommentText(textToLink($value['commentHTML'])).'
'; - $comments[$key]['total_replies'] = Comment::getTotalComments($_GET['video_id'], $comments[$key]['id']); - $comments[$key]['video'] = Video::getVideo($comments[$key]['videos_id']); - unset($comments[$key]['video']['description']); - $comments[$key]['poster'] = Video::getImageFromFilename($comments[$key]['video']['filename']); - $comments[$key]['userCanAdminComment'] = Comment::userCanAdminComment($comments[$key]['id']); - $comments[$key]['userCanEditComment'] = Comment::userCanEditComment($comments[$key]['id']); -} - -echo '{ "current": '. getCurrentPage().',"rowCount": '. getRowCount().', "total": '.$total.', "rows":'. json_encode($comments).'}'; +"]; + return stripslashes(str_replace($search, $replace, $subject)); +} + +foreach ($comments as $key => $value) { + $name = User::getNameIdentificationById($value['users_id']); + $comments[$key]['comment'] = '
User Photo
'.$name.' '.humanTiming(strtotime($value['created'])).'
'. fixCommentText(textToLink($value['commentHTML'])).'
'; + $comments[$key]['total_replies'] = Comment::getTotalComments($_GET['video_id'], $comments[$key]['id']); + $comments[$key]['video'] = Video::getVideo($comments[$key]['videos_id']); + unset($comments[$key]['video']['description']); + $comments[$key]['poster'] = Video::getImageFromFilename($comments[$key]['video']['filename']); + $comments[$key]['userCanAdminComment'] = Comment::userCanAdminComment($comments[$key]['id']); + $comments[$key]['userCanEditComment'] = Comment::userCanEditComment($comments[$key]['id']); +} + +echo '{ "current": '. getCurrentPage().',"rowCount": '. getRowCount().', "total": '.$total.', "rows":'. json_encode($comments).'}'; diff --git a/objects/comments_like.json.php b/objects/comments_like.json.php index 2a49046cac..b0f166d89b 100644 --- a/objects/comments_like.json.php +++ b/objects/comments_like.json.php @@ -1,6 +1,6 @@ login(false, true); } -if(empty($_POST['comments_id']) && !empty($_GET['comments_id'])){ +if (empty($_POST['comments_id']) && !empty($_GET['comments_id'])) { $_POST['comments_id'] = $_GET['comments_id']; } diff --git a/objects/comments_like.php b/objects/comments_like.php index 123046d27e..2aed8437ee 100644 --- a/objects/comments_like.php +++ b/objects/comments_like.php @@ -1,163 +1,163 @@ -comments_id = $comments_id; - $this->users_id = User::getId(); - $this->load(); - // if click again in the same vote, remove the vote - if ($this->like == $like) { - $like = 0; - } - $this->setLike($like); - $this->save(); - } - - private function setLike($like) - { - $like = intval($like); - if (!in_array($like, array(0,1,-1))) { - $like = 0; - } - $this->like = $like; - } - - private function load() - { - $like = $this->getLike(); - if (empty($like)) { - return false; - } - foreach ($like as $key => $value) { - $this->$key = $value; - } - } - - private function getLike() - { - global $global; - if (empty($this->users_id) || empty($this->comments_id)) { - header('Content-Type: application/json'); - die('{"error":"You must have user and videos set to get a like"}'); - } - $sql = "SELECT * FROM comments_likes WHERE users_id = ? AND comments_id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "ii", array($this->users_id,$this->comments_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return ($res) ? $result : false; - } - - private function save() - { - global $global; - if (!User::isLogged()) { - header('Content-Type: application/json'); - die('{"error":"'.__("Permission denied").'"}'); - } - $formats = ""; - $values = array(); - if (!empty($this->id)) { - $sql = "UPDATE comments_likes SET `like` = ?, modified = now() WHERE id = ?"; - $formats = "ii"; - $values = array($this->like,$this->id); - } else { - $sql = "INSERT INTO comments_likes ( `like`,users_id, comments_id, created, modified) VALUES (?, ?, ?, now(), now())"; - $formats = "iii"; - $values = array($this->like,$this->users_id,$this->comments_id); - } - return sqlDAL::writeSql($sql, $formats, $values); - } - - public static function getLikes($comments_id) - { - global $global; - - $obj = new stdClass(); - $obj->comments_id = $comments_id; - $obj->likes = 0; - $obj->dislikes = 0; - $obj->myVote = self::getMyVote($comments_id); - - $sql = "SELECT count(*) as total FROM comments_likes WHERE comments_id = ? AND `like` = 1 "; // like - $res = sqlDAL::readSql($sql, "i", array($comments_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!$res) { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->likes = intval($result['total']); - - $sql = "SELECT count(*) as total FROM comments_likes WHERE comments_id = ? AND `like` = -1 "; // dislike - $res = sqlDAL::readSql($sql, "i", array($comments_id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!$res) { - die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->dislikes = intval($result['total']); - return $obj; - } - - public static function getTotalLikes() - { - global $global; - - $obj = new stdClass(); - $obj->likes = 0; - $obj->dislikes = 0; - - $sql = "SELECT count(*) as total FROM comments_likes WHERE `like` = 1 "; // like - $res = sqlDAL::readSql($sql); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!$res) { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->likes = intval($result['total']); - - $sql = "SELECT count(*) as total FROM comments_likes WHERE `like` = -1 "; // dislike - $res = sqlDAL::readSql($sql); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!$res) { - die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->dislikes = intval($result['total']); - return $obj; - } - - public static function getMyVote($comments_id) - { - global $global; - if (!User::isLogged()) { - return 0; - } - $id = User::getId(); - $sql = "SELECT `like` FROM comments_likes WHERE comments_id = ? AND users_id = ? "; // like - $res = sqlDAL::readSql($sql, "ii", array($comments_id,$id)); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($result)) { - return intval($result['like']); - } - return 0; - } -} +comments_id = $comments_id; + $this->users_id = User::getId(); + $this->load(); + // if click again in the same vote, remove the vote + if ($this->like == $like) { + $like = 0; + } + $this->setLike($like); + $this->save(); + } + + private function setLike($like) + { + $like = intval($like); + if (!in_array($like, [0,1,-1])) { + $like = 0; + } + $this->like = $like; + } + + private function load() + { + $like = $this->getLike(); + if (empty($like)) { + return false; + } + foreach ($like as $key => $value) { + $this->$key = $value; + } + } + + private function getLike() + { + global $global; + if (empty($this->users_id) || empty($this->comments_id)) { + header('Content-Type: application/json'); + die('{"error":"You must have user and videos set to get a like"}'); + } + $sql = "SELECT * FROM comments_likes WHERE users_id = ? AND comments_id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "ii", [$this->users_id,$this->comments_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return ($res) ? $result : false; + } + + private function save() + { + global $global; + if (!User::isLogged()) { + header('Content-Type: application/json'); + die('{"error":"'.__("Permission denied").'"}'); + } + $formats = ''; + $values = []; + if (!empty($this->id)) { + $sql = "UPDATE comments_likes SET `like` = ?, modified = now() WHERE id = ?"; + $formats = "ii"; + $values = [$this->like,$this->id]; + } else { + $sql = "INSERT INTO comments_likes ( `like`,users_id, comments_id, created, modified) VALUES (?, ?, ?, now(), now())"; + $formats = "iii"; + $values = [$this->like,$this->users_id,$this->comments_id]; + } + return sqlDAL::writeSql($sql, $formats, $values); + } + + public static function getLikes($comments_id) + { + global $global; + + $obj = new stdClass(); + $obj->comments_id = $comments_id; + $obj->likes = 0; + $obj->dislikes = 0; + $obj->myVote = self::getMyVote($comments_id); + + $sql = "SELECT count(*) as total FROM comments_likes WHERE comments_id = ? AND `like` = 1 "; // like + $res = sqlDAL::readSql($sql, "i", [$comments_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!$res) { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->likes = intval($result['total']); + + $sql = "SELECT count(*) as total FROM comments_likes WHERE comments_id = ? AND `like` = -1 "; // dislike + $res = sqlDAL::readSql($sql, "i", [$comments_id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!$res) { + die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->dislikes = intval($result['total']); + return $obj; + } + + public static function getTotalLikes() + { + global $global; + + $obj = new stdClass(); + $obj->likes = 0; + $obj->dislikes = 0; + + $sql = "SELECT count(*) as total FROM comments_likes WHERE `like` = 1 "; // like + $res = sqlDAL::readSql($sql); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!$res) { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->likes = intval($result['total']); + + $sql = "SELECT count(*) as total FROM comments_likes WHERE `like` = -1 "; // dislike + $res = sqlDAL::readSql($sql); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!$res) { + die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->dislikes = intval($result['total']); + return $obj; + } + + public static function getMyVote($comments_id) + { + global $global; + if (!User::isLogged()) { + return 0; + } + $id = User::getId(); + $sql = "SELECT `like` FROM comments_likes WHERE comments_id = ? AND users_id = ? "; // like + $res = sqlDAL::readSql($sql, "ii", [$comments_id,$id]); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($result)) { + return intval($result['like']); + } + return 0; + } +} diff --git a/objects/configuration.php b/objects/configuration.php index 4c5d95e73f..71c9eca0a4 100644 --- a/objects/configuration.php +++ b/objects/configuration.php @@ -1,555 +1,621 @@ -load(); - if (!empty($video_resolution)) { - $this->video_resolution = $video_resolution; - } - } - - function load() { - global $global; - $sql = "SELECT * FROM configurations WHERE id = 1 LIMIT 1"; - //echo $sql;exit; - // add true because I was not getting the SMTP configuration on function setSiteSendMessage(&$mail) - $res = sqlDAL::readSql($sql, "", array(), true); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res && !empty($result)) { - $config = $result; - //var_dump($config);exit; - foreach ($config as $key => $value) { - $this->$key = $value; - } - } else { - return false; - } - } - - function save() { - global $global; - if (!User::isAdmin()) { - header('Content-Type: application/json'); - die('{"error":"' . __("Permission denied") . '"}'); - } - $this->users_id = User::getId(); - - ObjectYPT::deleteCache("getEncoderURL"); - - $sql = "UPDATE configurations SET " - . "video_resolution = '{$this->video_resolution}'," - . "webSiteTitle = '{$this->webSiteTitle}'," - . "language = '{$this->language}'," - . "contactEmail = '{$this->contactEmail}'," - . "users_id = '{$this->users_id}', " - . "authCanUploadVideos = '{$this->authCanUploadVideos}'," - . "authCanViewChart = '{$this->authCanViewChart}'," - . "authCanComment = '{$this->authCanComment}'," - . "encoderURL = '{$global['mysqli']->real_escape_string($this->_getEncoderURL())}'," - . "head = '{$global['mysqli']->real_escape_string($this->getHead())}'," - . "adsense = '{$global['mysqli']->real_escape_string($this->getAdsense())}'," - . "mode = '{$this->getMode()}'," - . "logo = '{$global['mysqli']->real_escape_string($this->getLogo())}'," - . "logo_small = '{$global['mysqli']->real_escape_string($this->getLogo_small())}'," - . "disable_analytics = '{$this->getDisable_analytics()}'," - . "disable_youtubeupload = '{$this->getDisable_youtubeupload()}'," - . "allow_download = '{$this->getAllow_download()}'," - . "session_timeout = '{$this->getSession_timeout()}'," - . "autoplay = '{$this->getAutoplay()}'," - . "theme = '{$global['mysqli']->real_escape_string($this->getTheme())}'," - . "smtp = '{$this->getSmtp()}'," - . "smtpAuth = '{$this->getSmtpAuth()}'," - . "smtpSecure = '{$global['mysqli']->real_escape_string($this->getSmtpSecure())}'," - . "smtpHost = '{$global['mysqli']->real_escape_string($this->getSmtpHost())}'," - . "smtpUsername = '{$global['mysqli']->real_escape_string($this->getSmtpUsername())}'," - . "smtpPort = '{$global['mysqli']->real_escape_string($this->getSmtpPort())}'," - . "smtpPassword = '{$global['mysqli']->real_escape_string($this->getSmtpPassword())}'" - . " WHERE id = 1"; - - - return sqlDAL::writeSql($sql); - } - - function getVideo_resolution() { - return $this->video_resolution; - } - - function getUsers_id() { - return $this->users_id; - } - - function getVersion() { - if (empty($this->version)) { - return " 0.1"; - } - return $this->version; - } - - function getWebSiteTitle() { - return $this->webSiteTitle; - } - - function getLanguage() { - if ($this->language == "en") { - return "us"; - } - return $this->language; - } - - function getContactEmail() { - return $this->contactEmail; - } - - function setVideo_resolution($video_resolution) { - $this->video_resolution = $video_resolution; - } - - function setWebSiteTitle($webSiteTitle) { - $this->webSiteTitle = $webSiteTitle; - } - - function setLanguage($language) { - $this->language = $language; - } - - function setContactEmail($contactEmail) { - $this->contactEmail = $contactEmail; - } - - function currentVersionLowerThen($version) { - return version_compare($version, $this->getVersion()) > 0; - } - - function currentVersionGreaterThen($version) { - return version_compare($version, $this->getVersion()) < 0; - } - - function currentVersionEqual($version) { - return version_compare($version, $this->getVersion()) == 0; - } - - function getAuthCanUploadVideos() { - return $this->authCanUploadVideos; - } - - function getAuthCanViewChart() { - return $this->authCanViewChart; - } - - function getAuthCanComment() { - return $this->authCanComment; - } - - function setAuthCanUploadVideos($authCanUploadVideos) { - $this->authCanUploadVideos = intval($authCanUploadVideos); - } - - function setAuthCanViewChart($authCanViewChart) { - $this->authCanViewChart = $authCanViewChart; - } - - function setAuthCanComment($authCanComment) { - $this->authCanComment = $authCanComment; - } - - function getHead() { - return $this->head; - } - - function getLogo($timestamp = false) { - global $global; - if (empty($this->logo)) { - return "view/img/logo.png"; - } - $get = ""; - $file = str_replace("?", "", $global['systemRootPath'] . $this->logo); - if ($timestamp && file_exists($file)) { - $get .= "?" . filemtime($file); - } - return $this->logo . $get; - } - - static function _getFavicon($getPNG = false) { - global $global; - $file = false; - $url = false; - if (!$getPNG) { - $file = $global['systemRootPath'] . "videos/favicon.ico"; - $url = getCDN()."videos/favicon.ico"; - if (!file_exists($file)) { - $file = $global['systemRootPath'] . "view/img/favicon.ico"; - $url = getCDN()."view/img/favicon.ico"; - } - } - if (empty($url) || !file_exists($file)) { - $file = $global['systemRootPath'] . "videos/favicon.png"; - $url = getCDN()."videos/favicon.png"; - if (!file_exists($file)) { - $file = $global['systemRootPath'] . "view/img/favicon.png"; - $url = getCDN()."view/img/favicon.png"; - } - } - return array('file' => $file, 'url' => $url); - } - - function getFavicon($getPNG = false, $getTime = true) { - $return = self::_getFavicon($getPNG); - if ($getTime) { - return $return['url'] . "?" . filemtime($return['file']); - } else { - return $return['url']; - } - } - - static function getOGImage() { - global $global; - $destination = Video::getStoragePath()."cache/og_200X200.jpg"; - $return = self::_getFavicon(true); - if(file_exists($return['file'])){ - convertImageToOG($return['file'], $destination); - } - return getCDN() . "videos/cache/og_200X200.jpg"; - } - - function setHead($head) { - $this->head = $head; - } - - function setLogo($logo) { - $this->logo = $logo; - } - - function getLogo_small() { - if (empty($this->logo_small)) { - return "view/img/logo32.png"; - } - return $this->logo_small; - } - - function setLogo_small($logo_small) { - $this->logo_small = $logo_small; - } - - function getAdsense() { - return $this->adsense; - } - - function setAdsense($adsense) { - $this->adsense = $adsense; - } - - function getMode() { - if (empty($this->mode)) { - return 'Youtube'; - } - return $this->mode; - } - - function setMode($mode) { - $this->mode = $mode; - } - - // version 2.7 - function getDisable_analytics() { - return $this->disable_analytics; - } - - function getDisable_youtubeupload() { - return $this->disable_youtubeupload; - } - - function getAllow_download() { - return $this->allow_download; - } - - function getSession_timeout() { - return $this->session_timeout; - } - - function setDisable_analytics($disable_analytics) { - $this->disable_analytics = ($disable_analytics == 'true' || $disable_analytics == '1') ? 1 : 0; - } - - function setDisable_youtubeupload($disable_youtubeupload) { - $this->disable_youtubeupload = ($disable_youtubeupload == 'true' || $disable_youtubeupload == '1') ? 1 : 0; - } - - function setAllow_download($allow_download) { - $this->allow_download = ($allow_download == 'true' || $allow_download == '1') ? 1 : 0; - } - - function setSession_timeout($session_timeout) { - $this->session_timeout = $session_timeout; - } - - function getAutoplay() { - return intval($this->autoplay); - } - - function setAutoplay($autoplay) { - $this->autoplay = ($autoplay == 'true' || $autoplay == '1') ? 1 : 0; - } - - // end version 2.7 - - static function rewriteConfigFile() { - global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase; - if (empty($global['salt'])) { - $global['salt'] = uniqid(); - } - if (empty($global['disableTimeFix'])) { - $global['disableTimeFix'] = 0; - } - if (empty($global['logfile'])) { - $global['logfile'] = $global['systemRootPath'] . 'videos/avideo.log'; - } - $content = "theme)) { - return "default"; - } - return $this->theme; - } - - function setTheme($theme) { - $this->theme = $theme; - } - - function getSmtp() { - return intval($this->smtp); - } - - function getSmtpAuth() { - return intval($this->smtpAuth); - } - - function getSmtpSecure() { - return $this->smtpSecure; - } - - function getSmtpHost() { - return $this->smtpHost; - } - - function getSmtpUsername() { - return $this->smtpUsername; - } - - function getSmtpPassword() { - return $this->smtpPassword; - } - - function setSmtp($smtp) { - $this->smtp = ($smtp == 'true' || $smtp == '1') ? 1 : 0; - } - - function setSmtpAuth($smtpAuth) { - $this->smtpAuth = ($smtpAuth == 'true' || $smtpAuth == '1') ? 1 : 0; - } - - function setSmtpSecure($smtpSecure) { - $this->smtpSecure = $smtpSecure; - } - - function setSmtpHost($smtpHost) { - $this->smtpHost = $smtpHost; - } - - function setSmtpUsername($smtpUsername) { - $this->smtpUsername = $smtpUsername; - } - - function setSmtpPassword($smtpPassword) { - $this->smtpPassword = $smtpPassword; - } - - function getSmtpPort() { - return intval($this->smtpPort); - } - - function setSmtpPort($smtpPort) { - $this->smtpPort = intval($smtpPort); - } - - function _getEncoderURL() { - if (substr($this->encoderURL, -1) !== '/') { - $this->encoderURL .= "/"; - } - return $this->encoderURL; - } - - function shouldUseEncodernetwork(){ - global $advancedCustom, $global; - if(empty($advancedCustom->useEncoderNetworkRecomendation) || empty($advancedCustom->encoderNetwork)){ - return false; - } - if($advancedCustom->encoderNetwork === 'https://network.avideo.com/'){ - // check if you have your own encoder - $encoderConfigFile = "{$global['systemRootPath']}Encoder/videos/configuration.php"; - if(file_exists($encoderConfigFile)){ // you have an encoder do not use the public one - _error_log("Configuration:shouldUseEncodernetwork 1 You checked the Encoder Network but you have your own encoder, we will ignore this option"); - return false; - } - - if (substr($this->encoderURL, -1) !== '/') { - $this->encoderURL .= "/"; - } - - if(!preg_match('/encoder[1-9].avideo.com/i', $this->encoderURL)){ - $creatingImages = "{$this->encoderURL}view/img/creatingImages.jpg"; - if(isURL200($creatingImages)){ - _error_log("Configuration:shouldUseEncodernetwork 2 You checked the Encoder Network but you have your own encoder, we will ignore this option"); - return false; - } - } - } - return true; - } - - static function deleteEncoderURLCache(){ - _error_log_debug("Configuration::deleteEncoderURLCache"); - $name = "getEncoderURL" . DIRECTORY_SEPARATOR; - $tmpDir = ObjectYPT::getCacheDir(); - $cacheDir = $tmpDir . $name; - ObjectYPT::deleteCache($name); - rrmdir($cacheDir); - } - - function getEncoderURL() { - global $global, $getEncoderURL, $advancedCustom; - if(!empty($global['forceEncoderURL'])){ - return $global['forceEncoderURL']; - } - if (empty($getEncoderURL)) { - $getEncoderURL = ObjectYPT::getCache("getEncoderURL". DIRECTORY_SEPARATOR, 60); - if (empty($getEncoderURL)) { - if ($this->shouldUseEncodernetwork()) { - if (substr($advancedCustom->encoderNetwork, -1) !== '/') { - $advancedCustom->encoderNetwork .= "/"; - } - $bestEncoder = _json_decode(url_get_contents($advancedCustom->encoderNetwork . "view/getBestEncoder.php", "", 10, true)); - if (!empty($bestEncoder->siteURL)) { - $this->encoderURL = $bestEncoder->siteURL; - } else { - error_log("Configuration::getEncoderURL ERROR your network ($advancedCustom->encoderNetwork) is not configured properly This slow down your site a lot, disable the option useEncoderNetworkRecomendation in your CustomizeAdvanced plugin"); - } - }else{ - //error_log("Configuration::getEncoderURL shouldUseEncodernetwork said no"); - } - - if (empty($this->encoderURL)) { - $getEncoderURL = "https://encoder1.avideo.com/"; - } - addLastSlash($this->encoderURL); - $getEncoderURL = $this->encoderURL; - ObjectYPT::setCache("getEncoderURL", $getEncoderURL); - }else{ - //error_log("Configuration::getEncoderURL got it from cache ". json_encode($getEncoderURL)); - } - } - return $getEncoderURL; - } - - function setEncoderURL($encoderURL) { - $this->encoderURL = $encoderURL; - } - - function getPageTitleSeparator() { - if(!defined('PAGE_TITLE_SEPARATOR')){ - define("PAGE_TITLE_SEPARATOR", "·"); // This is ready to be configurable, if needed - } - return " " . PAGE_TITLE_SEPARATOR . " "; - } - -} +load(); + if (!empty($video_resolution)) { + $this->video_resolution = $video_resolution; + } + } + + public function load() + { + global $global; + $sql = "SELECT * FROM configurations WHERE id = 1 LIMIT 1"; + //echo $sql;exit; + // add true because I was not getting the SMTP configuration on function setSiteSendMessage(&$mail) + $res = sqlDAL::readSql($sql, "", [], true); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res && !empty($result)) { + $config = $result; + //var_dump($config);exit; + foreach ($config as $key => $value) { + $this->$key = $value; + } + } else { + return false; + } + } + + public function save() + { + global $global; + if (!User::isAdmin()) { + header('Content-Type: application/json'); + die('{"error":"' . __("Permission denied") . '"}'); + } + $this->users_id = User::getId(); + + ObjectYPT::deleteCache("getEncoderURL"); + + $sql = "UPDATE configurations SET " + . "video_resolution = '{$this->video_resolution}'," + . "webSiteTitle = '{$this->webSiteTitle}'," + . "language = '{$this->language}'," + . "contactEmail = '{$this->contactEmail}'," + . "users_id = '{$this->users_id}', " + . "authCanUploadVideos = '{$this->authCanUploadVideos}'," + . "authCanViewChart = '{$this->authCanViewChart}'," + . "authCanComment = '{$this->authCanComment}'," + . "encoderURL = '{$global['mysqli']->real_escape_string($this->_getEncoderURL())}'," + . "head = '{$global['mysqli']->real_escape_string($this->getHead())}'," + . "adsense = '{$global['mysqli']->real_escape_string($this->getAdsense())}'," + . "mode = '{$this->getMode()}'," + . "logo = '{$global['mysqli']->real_escape_string($this->getLogo())}'," + . "logo_small = '{$global['mysqli']->real_escape_string($this->getLogo_small())}'," + . "disable_analytics = '{$this->getDisable_analytics()}'," + . "disable_youtubeupload = '{$this->getDisable_youtubeupload()}'," + . "allow_download = '{$this->getAllow_download()}'," + . "session_timeout = '{$this->getSession_timeout()}'," + . "autoplay = '{$this->getAutoplay()}'," + . "theme = '{$global['mysqli']->real_escape_string($this->getTheme())}'," + . "smtp = '{$this->getSmtp()}'," + . "smtpAuth = '{$this->getSmtpAuth()}'," + . "smtpSecure = '{$global['mysqli']->real_escape_string($this->getSmtpSecure())}'," + . "smtpHost = '{$global['mysqli']->real_escape_string($this->getSmtpHost())}'," + . "smtpUsername = '{$global['mysqli']->real_escape_string($this->getSmtpUsername())}'," + . "smtpPort = '{$global['mysqli']->real_escape_string($this->getSmtpPort())}'," + . "smtpPassword = '{$global['mysqli']->real_escape_string($this->getSmtpPassword())}'" + . " WHERE id = 1"; + + + return sqlDAL::writeSql($sql); + } + + public function getVideo_resolution() + { + return $this->video_resolution; + } + + public function getUsers_id() + { + return $this->users_id; + } + + public function getVersion() + { + if (empty($this->version)) { + return " 0.1"; + } + return $this->version; + } + + public function getWebSiteTitle() + { + return $this->webSiteTitle; + } + + public function getLanguage() + { + if ($this->language == "en") { + return "us"; + } + return $this->language; + } + + public function getContactEmail() + { + return $this->contactEmail; + } + + public function setVideo_resolution($video_resolution) + { + $this->video_resolution = $video_resolution; + } + + public function setWebSiteTitle($webSiteTitle) + { + $this->webSiteTitle = $webSiteTitle; + } + + public function setLanguage($language) + { + $this->language = $language; + } + + public function setContactEmail($contactEmail) + { + $this->contactEmail = $contactEmail; + } + + public function currentVersionLowerThen($version) + { + return version_compare($version, $this->getVersion()) > 0; + } + + public function currentVersionGreaterThen($version) + { + return version_compare($version, $this->getVersion()) < 0; + } + + public function currentVersionEqual($version) + { + return version_compare($version, $this->getVersion()) == 0; + } + + public function getAuthCanUploadVideos() + { + return $this->authCanUploadVideos; + } + + public function getAuthCanViewChart() + { + return $this->authCanViewChart; + } + + public function getAuthCanComment() + { + return $this->authCanComment; + } + + public function setAuthCanUploadVideos($authCanUploadVideos) + { + $this->authCanUploadVideos = intval($authCanUploadVideos); + } + + public function setAuthCanViewChart($authCanViewChart) + { + $this->authCanViewChart = $authCanViewChart; + } + + public function setAuthCanComment($authCanComment) + { + $this->authCanComment = $authCanComment; + } + + public function getHead() + { + return $this->head; + } + + public function getLogo($timestamp = false) + { + global $global; + if (empty($this->logo)) { + return "view/img/logo.png"; + } + $get = ''; + $file = str_replace("?", "", $global['systemRootPath'] . $this->logo); + if ($timestamp && file_exists($file)) { + $get .= "?" . filemtime($file); + } + return $this->logo . $get; + } + + public static function _getFavicon($getPNG = false) + { + global $global; + $file = false; + $url = false; + if (!$getPNG) { + $file = $global['systemRootPath'] . "videos/favicon.ico"; + $url = getCDN()."videos/favicon.ico"; + if (!file_exists($file)) { + $file = $global['systemRootPath'] . "view/img/favicon.ico"; + $url = getCDN()."view/img/favicon.ico"; + } + } + if (empty($url) || !file_exists($file)) { + $file = $global['systemRootPath'] . "videos/favicon.png"; + $url = getCDN()."videos/favicon.png"; + if (!file_exists($file)) { + $file = $global['systemRootPath'] . "view/img/favicon.png"; + $url = getCDN()."view/img/favicon.png"; + } + } + return ['file' => $file, 'url' => $url]; + } + + public function getFavicon($getPNG = false, $getTime = true) + { + $return = self::_getFavicon($getPNG); + if ($getTime) { + return $return['url'] . "?" . filemtime($return['file']); + } else { + return $return['url']; + } + } + + public static function getOGImage() + { + global $global; + $destination = Video::getStoragePath()."cache/og_200X200.jpg"; + $return = self::_getFavicon(true); + if (file_exists($return['file'])) { + convertImageToOG($return['file'], $destination); + } + return getCDN() . "videos/cache/og_200X200.jpg"; + } + + public function setHead($head) + { + $this->head = $head; + } + + public function setLogo($logo) + { + $this->logo = $logo; + } + + public function getLogo_small() + { + if (empty($this->logo_small)) { + return "view/img/logo32.png"; + } + return $this->logo_small; + } + + public function setLogo_small($logo_small) + { + $this->logo_small = $logo_small; + } + + public function getAdsense() + { + return $this->adsense; + } + + public function setAdsense($adsense) + { + $this->adsense = $adsense; + } + + public function getMode() + { + if (empty($this->mode)) { + return 'Youtube'; + } + return $this->mode; + } + + public function setMode($mode) + { + $this->mode = $mode; + } + + // version 2.7 + public function getDisable_analytics() + { + return $this->disable_analytics; + } + + public function getDisable_youtubeupload() + { + return $this->disable_youtubeupload; + } + + public function getAllow_download() + { + return $this->allow_download; + } + + public function getSession_timeout() + { + return $this->session_timeout; + } + + public function setDisable_analytics($disable_analytics) + { + $this->disable_analytics = ($disable_analytics == 'true' || $disable_analytics == '1') ? 1 : 0; + } + + public function setDisable_youtubeupload($disable_youtubeupload) + { + $this->disable_youtubeupload = ($disable_youtubeupload == 'true' || $disable_youtubeupload == '1') ? 1 : 0; + } + + public function setAllow_download($allow_download) + { + $this->allow_download = ($allow_download == 'true' || $allow_download == '1') ? 1 : 0; + } + + public function setSession_timeout($session_timeout) + { + $this->session_timeout = $session_timeout; + } + + public function getAutoplay() + { + return intval($this->autoplay); + } + + public function setAutoplay($autoplay) + { + $this->autoplay = ($autoplay == 'true' || $autoplay == '1') ? 1 : 0; + } + + // end version 2.7 + + public static function rewriteConfigFile() + { + global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase; + if (empty($global['salt'])) { + $global['salt'] = uniqid(); + } + if (empty($global['disableTimeFix'])) { + $global['disableTimeFix'] = 0; + } + if (empty($global['logfile'])) { + $global['logfile'] = $global['systemRootPath'] . 'videos/avideo.log'; + } + $content = "theme)) { + return "default"; + } + return $this->theme; + } + + public function setTheme($theme) + { + $this->theme = $theme; + } + + public function getSmtp() + { + return intval($this->smtp); + } + + public function getSmtpAuth() + { + return intval($this->smtpAuth); + } + + public function getSmtpSecure() + { + return $this->smtpSecure; + } + + public function getSmtpHost() + { + return $this->smtpHost; + } + + public function getSmtpUsername() + { + return $this->smtpUsername; + } + + public function getSmtpPassword() + { + return $this->smtpPassword; + } + + public function setSmtp($smtp) + { + $this->smtp = ($smtp == 'true' || $smtp == '1') ? 1 : 0; + } + + public function setSmtpAuth($smtpAuth) + { + $this->smtpAuth = ($smtpAuth == 'true' || $smtpAuth == '1') ? 1 : 0; + } + + public function setSmtpSecure($smtpSecure) + { + $this->smtpSecure = $smtpSecure; + } + + public function setSmtpHost($smtpHost) + { + $this->smtpHost = $smtpHost; + } + + public function setSmtpUsername($smtpUsername) + { + $this->smtpUsername = $smtpUsername; + } + + public function setSmtpPassword($smtpPassword) + { + $this->smtpPassword = $smtpPassword; + } + + public function getSmtpPort() + { + return intval($this->smtpPort); + } + + public function setSmtpPort($smtpPort) + { + $this->smtpPort = intval($smtpPort); + } + + public function _getEncoderURL() + { + if (substr($this->encoderURL, -1) !== '/') { + $this->encoderURL .= "/"; + } + return $this->encoderURL; + } + + public function shouldUseEncodernetwork() + { + global $advancedCustom, $global; + if (empty($advancedCustom->useEncoderNetworkRecomendation) || empty($advancedCustom->encoderNetwork)) { + return false; + } + if ($advancedCustom->encoderNetwork === 'https://network.avideo.com/') { + // check if you have your own encoder + $encoderConfigFile = "{$global['systemRootPath']}Encoder/videos/configuration.php"; + if (file_exists($encoderConfigFile)) { // you have an encoder do not use the public one + _error_log("Configuration:shouldUseEncodernetwork 1 You checked the Encoder Network but you have your own encoder, we will ignore this option"); + return false; + } + + if (substr($this->encoderURL, -1) !== '/') { + $this->encoderURL .= "/"; + } + + if (!preg_match('/encoder[1-9].avideo.com/i', $this->encoderURL)) { + $creatingImages = "{$this->encoderURL}view/img/creatingImages.jpg"; + if (isURL200($creatingImages)) { + _error_log("Configuration:shouldUseEncodernetwork 2 You checked the Encoder Network but you have your own encoder, we will ignore this option"); + return false; + } + } + } + return true; + } + + public static function deleteEncoderURLCache() + { + _error_log_debug("Configuration::deleteEncoderURLCache"); + $name = "getEncoderURL" . DIRECTORY_SEPARATOR; + $tmpDir = ObjectYPT::getCacheDir(); + $cacheDir = $tmpDir . $name; + ObjectYPT::deleteCache($name); + rrmdir($cacheDir); + } + + public function getEncoderURL() + { + global $global, $getEncoderURL, $advancedCustom; + if (!empty($global['forceEncoderURL'])) { + return $global['forceEncoderURL']; + } + if (empty($getEncoderURL)) { + $getEncoderURL = ObjectYPT::getCache("getEncoderURL". DIRECTORY_SEPARATOR, 60); + if (empty($getEncoderURL)) { + if ($this->shouldUseEncodernetwork()) { + if (substr($advancedCustom->encoderNetwork, -1) !== '/') { + $advancedCustom->encoderNetwork .= "/"; + } + $bestEncoder = _json_decode(url_get_contents($advancedCustom->encoderNetwork . "view/getBestEncoder.php", "", 10, true)); + if (!empty($bestEncoder->siteURL)) { + $this->encoderURL = $bestEncoder->siteURL; + } else { + error_log("Configuration::getEncoderURL ERROR your network ($advancedCustom->encoderNetwork) is not configured properly This slow down your site a lot, disable the option useEncoderNetworkRecomendation in your CustomizeAdvanced plugin"); + } + } else { + //error_log("Configuration::getEncoderURL shouldUseEncodernetwork said no"); + } + + if (empty($this->encoderURL)) { + $getEncoderURL = "https://encoder1.avideo.com/"; + } + addLastSlash($this->encoderURL); + $getEncoderURL = $this->encoderURL; + ObjectYPT::setCache("getEncoderURL", $getEncoderURL); + } else { + //error_log("Configuration::getEncoderURL got it from cache ". json_encode($getEncoderURL)); + } + } + return $getEncoderURL; + } + + public function setEncoderURL($encoderURL) + { + $this->encoderURL = $encoderURL; + } + + public function getPageTitleSeparator() + { + if (!defined('PAGE_TITLE_SEPARATOR')) { + define("PAGE_TITLE_SEPARATOR", "·"); // This is ready to be configurable, if needed + } + return " " . PAGE_TITLE_SEPARATOR . " "; + } +} diff --git a/objects/configurationClearCache.json.php b/objects/configurationClearCache.json.php index 13b1ee2736..776902222e 100644 --- a/objects/configurationClearCache.json.php +++ b/objects/configurationClearCache.json.php @@ -1,27 +1,27 @@ -error = true; -$obj->msg = ""; -$obj->clearCache = false; -$obj->deleteALLCache = false; -$obj->deleteAllSessionCache = false; -$_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; - -if (!Permissions::canClearCache() || !empty($_REQUEST['sessionOnly'])) { - $obj->deleteAllSessionCache = ObjectYPT::deleteAllSessionCache(); -}else{ - if(!empty($_REQUEST['FirstPage'])){ - $obj->firstPageCache = clearCache(true); - }else{ - $obj->clearCache = clearCache(); - $obj->deleteALLCache = ObjectYPT::deleteALLCache(); - } -} -$obj->error = false; -die(json_encode($obj)); +error = true; +$obj->msg = ''; +$obj->clearCache = false; +$obj->deleteALLCache = false; +$obj->deleteAllSessionCache = false; +$_SESSION['user']['sessionCache']['getAllCategoriesClearCache'] = 1; + +if (!Permissions::canClearCache() || !empty($_REQUEST['sessionOnly'])) { + $obj->deleteAllSessionCache = ObjectYPT::deleteAllSessionCache(); +} else { + if (!empty($_REQUEST['FirstPage'])) { + $obj->firstPageCache = clearCache(true); + } else { + $obj->clearCache = clearCache(); + $obj->deleteALLCache = ObjectYPT::deleteALLCache(); + } +} +$obj->error = false; +die(json_encode($obj)); diff --git a/objects/configurationGenerateSiteMap.json.php b/objects/configurationGenerateSiteMap.json.php index dd8c5b791e..7ff7ba20a4 100644 --- a/objects/configurationGenerateSiteMap.json.php +++ b/objects/configurationGenerateSiteMap.json.php @@ -1,32 +1,31 @@ -error = true; -$obj->msg = ""; - -if (!Permissions::canGenerateSiteMap()) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} -$sitemap = siteMap(); - -if(empty($sitemap)){ - $obj->msg = "Sitemap content is empty"; - die(json_encode($obj)); -} - - -$name = "sitemap.xml"; -ObjectYPT::setCache($name, $sitemap); - -$obj->error = false; -die(json_encode($obj)); +error = true; +$obj->msg = ''; + +if (!Permissions::canGenerateSiteMap()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} +$sitemap = siteMap(); + +if (empty($sitemap)) { + $obj->msg = "Sitemap content is empty"; + die(json_encode($obj)); +} + + +$name = "sitemap.xml"; +ObjectYPT::setCache($name, $sitemap); + +$obj->error = false; +die(json_encode($obj)); diff --git a/objects/configurationUpdate.json.php b/objects/configurationUpdate.json.php index b202bbf766..e149279164 100644 --- a/objects/configurationUpdate.json.php +++ b/objects/configurationUpdate.json.php @@ -1,114 +1,114 @@ -setContactEmail($_POST['contactEmail']); -$config->setLanguage($_POST['language']); -$config->setWebSiteTitle($_POST['webSiteTitle']); -$config->setAuthCanComment($_POST['authCanComment']); -$config->setAuthCanUploadVideos($_POST['authCanUploadVideos']); -$config->setAuthCanViewChart($_POST['authCanViewChart']); -if (empty($global['disableAdvancedConfigurations'])) { - $config->setDisable_analytics($_POST['disable_analytics']); - $config->setDisable_youtubeupload($_POST['disable_youtubeupload']); - $config->setAllow_download($_POST['allow_download']); - $config->setSession_timeout($_POST['session_timeout']); - $config->setEncoderURL($_POST['encoder_url']); - $config->setSmtp($_POST['smtp']); - $config->setSmtpAuth($_POST['smtpAuth']); - $config->setSmtpSecure($_POST['smtpSecure']); - $config->setSmtpHost($_POST['smtpHost']); - $config->setSmtpUsername($_POST['smtpUsername']); - $config->setSmtpPassword($_POST['smtpPassword']); - $config->setSmtpPort($_POST['smtpPort']); -} - -$config->setHead($_POST['head']); -$config->setAdsense($_POST['adsense']); -$config->setMode('Youtube'); - -$config->setAutoplay($_POST['autoplay']); -$config->setTheme($_POST['theme']); - -$imagePath = "videos/userPhoto/"; - -//Check write Access to Directory -if (!file_exists($global['systemRootPath'] . $imagePath)) { - mkdir($global['systemRootPath'] . $imagePath, 0755, true); -} -/* -if (!is_writable($global['systemRootPath'] . $imagePath)) { - $response = array( - "status" => 'error', - "message" => 'No write Access' - ); - print json_encode($response); - return; -} - * - */ -$response = array(); -if (!empty($_POST['logoImgBase64'])) { - $fileData = base64DataToImage($_POST['logoImgBase64']); - $fileName = 'logo.png'; - $photoURL = $imagePath . $fileName; - $bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData); - if ($bytes > 10) { - $response = array( - "status" => 'success', - "url" => $global['systemRootPath'] . $photoURL - ); - $config->setLogo($photoURL); - } else { - $response = array( - "status" => 'error', - "msg" => 'We could not save logo', - "url" => $global['systemRootPath'] . $photoURL - ); - } -} -if (!empty($_POST['faviconBase64'])) { - $imagePath = "videos/"; - $fileData = base64DataToImage($_POST['faviconBase64']); - $fileName = 'favicon.png'; - $photoURL = $imagePath . $fileName; - $bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData); - if ($bytes > 10) { - $response2 = array( - "status" => 'success', - "url" => $global['systemRootPath'] . $photoURL - ); - - $sizes = array( - array(16, 16), - array(24, 24), - array(32, 32), - array(48, 48), - array(144, 144) - ); - - $ico_lib = new PHP_ICO($global['systemRootPath'] . $photoURL, $sizes); - $ico_lib->save_ico($global['systemRootPath'] . $imagePath.'favicon.ico'); - } else { - $response2 = array( - "status" => 'error', - "msg" => 'We could not save favicon', - "url" => $global['systemRootPath'] . $photoURL - ); - } -} - -echo '{"status":"' . $config->save() . '", "respnseLogo": ' . json_encode($response) . ', "respnseFavicon": ' . json_encode($response2) . '}'; +setContactEmail($_POST['contactEmail']); +$config->setLanguage($_POST['language']); +$config->setWebSiteTitle($_POST['webSiteTitle']); +$config->setAuthCanComment($_POST['authCanComment']); +$config->setAuthCanUploadVideos($_POST['authCanUploadVideos']); +$config->setAuthCanViewChart($_POST['authCanViewChart']); +if (empty($global['disableAdvancedConfigurations'])) { + $config->setDisable_analytics($_POST['disable_analytics']); + $config->setDisable_youtubeupload($_POST['disable_youtubeupload']); + $config->setAllow_download($_POST['allow_download']); + $config->setSession_timeout($_POST['session_timeout']); + $config->setEncoderURL($_POST['encoder_url']); + $config->setSmtp($_POST['smtp']); + $config->setSmtpAuth($_POST['smtpAuth']); + $config->setSmtpSecure($_POST['smtpSecure']); + $config->setSmtpHost($_POST['smtpHost']); + $config->setSmtpUsername($_POST['smtpUsername']); + $config->setSmtpPassword($_POST['smtpPassword']); + $config->setSmtpPort($_POST['smtpPort']); +} + +$config->setHead($_POST['head']); +$config->setAdsense($_POST['adsense']); +$config->setMode('Youtube'); + +$config->setAutoplay($_POST['autoplay']); +$config->setTheme($_POST['theme']); + +$imagePath = "videos/userPhoto/"; + +//Check write Access to Directory +if (!file_exists($global['systemRootPath'] . $imagePath)) { + mkdir($global['systemRootPath'] . $imagePath, 0755, true); +} +/* +if (!is_writable($global['systemRootPath'] . $imagePath)) { + $response = array( + "status" => 'error', + "message" => 'No write Access' + ); + print json_encode($response); + return; +} + * + */ +$response = []; +if (!empty($_POST['logoImgBase64'])) { + $fileData = base64DataToImage($_POST['logoImgBase64']); + $fileName = 'logo.png'; + $photoURL = $imagePath . $fileName; + $bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData); + if ($bytes > 10) { + $response = [ + "status" => 'success', + "url" => $global['systemRootPath'] . $photoURL, + ]; + $config->setLogo($photoURL); + } else { + $response = [ + "status" => 'error', + "msg" => 'We could not save logo', + "url" => $global['systemRootPath'] . $photoURL, + ]; + } +} +if (!empty($_POST['faviconBase64'])) { + $imagePath = "videos/"; + $fileData = base64DataToImage($_POST['faviconBase64']); + $fileName = 'favicon.png'; + $photoURL = $imagePath . $fileName; + $bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData); + if ($bytes > 10) { + $response2 = [ + "status" => 'success', + "url" => $global['systemRootPath'] . $photoURL, + ]; + + $sizes = [ + [16, 16], + [24, 24], + [32, 32], + [48, 48], + [144, 144], + ]; + + $ico_lib = new PHP_ICO($global['systemRootPath'] . $photoURL, $sizes); + $ico_lib->save_ico($global['systemRootPath'] . $imagePath.'favicon.ico'); + } else { + $response2 = [ + "status" => 'error', + "msg" => 'We could not save favicon', + "url" => $global['systemRootPath'] . $photoURL, + ]; + } +} + +echo '{"status":"' . $config->save() . '", "respnseLogo": ' . json_encode($response) . ', "respnseFavicon": ' . json_encode($response2) . '}'; diff --git a/objects/emailAllUsers.json.php b/objects/emailAllUsers.json.php index c3f39ae6ec..0935c634dc 100644 --- a/objects/emailAllUsers.json.php +++ b/objects/emailAllUsers.json.php @@ -1,71 +1,71 @@ -error = false; -$obj->msg = array(); -//Create a new PHPMailer instance -$mail = new \PHPMailer\PHPMailer\PHPMailer; -setSiteSendMessage($mail); -//Set who the message is to be sent from -$mail->setFrom($config->getContactEmail()); -$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle(); -$mail->msgHTML($_POST['message']); -$count = 0; -$currentCount = 0; -foreach ($users as $value) { - if ($count % $mailsLimit === 0) { - if ($count !== 0) { - if (!$mail->send()) { - $obj->error = true; - $obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo; - } - $mail->ClearAddresses(); - $mail->ClearCCs(); - $mail->ClearBCCs(); - $currentCount = 0; - } - } - $mail->addBCC($value["email"]); - $count++; - $currentCount++; -} -if ($currentCount && !$mail->send()) { - $obj->error = true; - $obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo; -} -$obj->count = $count; -echo json_encode($obj); +error = false; +$obj->msg = []; +//Create a new PHPMailer instance +$mail = new \PHPMailer\PHPMailer\PHPMailer(); +setSiteSendMessage($mail); +//Set who the message is to be sent from +$mail->setFrom($config->getContactEmail()); +$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle(); +$mail->msgHTML($_POST['message']); +$count = 0; +$currentCount = 0; +foreach ($users as $value) { + if ($count % $mailsLimit === 0) { + if ($count !== 0) { + if (!$mail->send()) { + $obj->error = true; + $obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo; + } + $mail->ClearAddresses(); + $mail->ClearCCs(); + $mail->ClearBCCs(); + $currentCount = 0; + } + } + $mail->addBCC($value["email"]); + $count++; + $currentCount++; +} +if ($currentCount && !$mail->send()) { + $obj->error = true; + $obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo; +} +$obj->count = $count; +echo json_encode($obj); diff --git a/objects/functionCountDownPage.php b/objects/functionCountDownPage.php index afda52d817..81a66a88ee 100644 --- a/objects/functionCountDownPage.php +++ b/objects/functionCountDownPage.php @@ -1,643 +1,643 @@ - - - - - Coming Soon 1 - - - - - - - - - - - - - -
- -
- -
-
- 0 - -
- -
- 0 - -
- -
- 0 - -
- -
- 0 - -
-
- -
-
- -
-
- -
-

- -

-
- -
-
- - - - - - - - - - - - + + + + + Coming Soon 1 + + + + + + + + + + + + + +
+ +
+ +
+
+ 0 + +
+ +
+ 0 + +
+ +
+ 0 + +
+ +
+ 0 + +
+
+ +
+
+ +
+
+ +
+

+ +

+
+ +
+
+ + + + + + + + + + + + diff --git a/objects/functionCroppie.php b/objects/functionCroppie.php index 5760b9ef0c..36ed1b17c6 100644 --- a/objects/functionCroppie.php +++ b/objects/functionCroppie.php @@ -1,70 +1,70 @@ - - - - -
-
-
-
- - -
-
-
- -
-
- + + + + +
+
+
+
+ + +
+
+
+ +
+
+ diff --git a/objects/functiondiskUsageBars.php b/objects/functiondiskUsageBars.php index 123f170083..09564decfc 100644 --- a/objects/functiondiskUsageBars.php +++ b/objects/functiondiskUsageBars.php @@ -1,29 +1,29 @@ - -
-
-
- videos_dir_used_percentage; ?>% -
-
- disk_used_percentage - $getDiskUsage->videos_dir_used_percentage; ?>% -
-
- disk_free_space_percentage; ?>% -
-
-
- : videos_dir_human; ?> (videos_dir_used_percentage; ?>%) -
-
- : disk_used_human; ?> (disk_used_percentage - $getDiskUsage->videos_dir_used_percentage; ?>%) -
-
- : disk_free_space_human; ?> (disk_free_space_percentage; ?>%) -
-
-disk_free_space_percentage < 15 && $getDiskUsage->disk_free_space < 53687091200) { // 53687091200 = 50 GB - echo ""; -} + +
+
+
+ videos_dir_used_percentage; ?>% +
+
+ disk_used_percentage - $getDiskUsage->videos_dir_used_percentage; ?>% +
+
+ disk_free_space_percentage; ?>% +
+
+
+ : videos_dir_human; ?> (videos_dir_used_percentage; ?>%) +
+
+ : disk_used_human; ?> (disk_used_percentage - $getDiskUsage->videos_dir_used_percentage; ?>%) +
+
+ : disk_free_space_human; ?> (disk_free_space_percentage; ?>%) +
+
+disk_free_space_percentage < 15 && $getDiskUsage->disk_free_space < 53687091200) { // 53687091200 = 50 GB + echo ""; +} diff --git a/objects/functiongetOpenGraph.php b/objects/functiongetOpenGraph.php index 264b768fb9..05817aa2bb 100644 --- a/objects/functiongetOpenGraph.php +++ b/objects/functiongetOpenGraph.php @@ -1,138 +1,136 @@ -".PHP_EOL; -if (empty($videos_id)) { - echo PHP_EOL."".PHP_EOL; - if (!empty($_GET['videoName'])) { - echo PHP_EOL."".PHP_EOL; - $video = Video::getVideoFromCleanTitle($_GET['videoName']); - } -} else { - echo PHP_EOL."".PHP_EOL; - $video = Video::getVideoLight($videos_id); -} -if (empty($video)) { - echo PHP_EOL."".PHP_EOL; - return false; -} -$videos_id = $video['id']; -$source = Video::getSourceFile($video['filename']); -$imgw = 1024; -$imgh = 768; -if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { - $img = $source['url']; - $data = getimgsize($source['path']); - $imgw = $data[0]; - $imgh = $data[1]; -} else if ($video['type'] == "audio") { - $img = 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; -} -$twitter_site = $advancedCustom->twitter_site; -$title = _substr(html2plainText($video['title']), 0,55); -$description = _substr(html2plainText($video['description']), 0,155); -$ogURL = Video::getLinkToVideo($videos_id); -?> - - - - - - - - - - - - - - -"; - } - if(empty($source['url'])){ - echo ""; - } -}else{ - $source['url'] = str_replace(".m3u8", ".m3u8.mp4", $source['url']); -} -if (!AVideoPlugin::isEnabledByName("SecureVideosDirectory") && !empty($source['url'])) { - ?> - - - - - - "; - } - if(empty($source['url'])){ - echo ""; - } - - ?> - - - - - - - -twitter_player)) { - if (!AVideoPlugin::isEnabledByName("SecureVideosDirectory") && !empty($source['url'])) { - ?> - - " /> - - - - - - - - - - twitter_summary_large_image)) { - ?> - - - - - - - - - -".PHP_EOL; +if (empty($videos_id)) { + echo PHP_EOL."".PHP_EOL; + if (!empty($_GET['videoName'])) { + echo PHP_EOL."".PHP_EOL; + $video = Video::getVideoFromCleanTitle($_GET['videoName']); + } +} else { + echo PHP_EOL."".PHP_EOL; + $video = Video::getVideoLight($videos_id); +} +if (empty($video)) { + echo PHP_EOL."".PHP_EOL; + return false; +} +$videos_id = $video['id']; +$source = Video::getSourceFile($video['filename']); +$imgw = 1024; +$imgh = 768; +if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { + $img = $source['url']; + $data = getimgsize($source['path']); + $imgw = $data[0]; + $imgh = $data[1]; +} 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; +} +$twitter_site = $advancedCustom->twitter_site; +$title = _substr(html2plainText($video['title']), 0, 55); +$description = _substr(html2plainText($video['description']), 0, 155); +$ogURL = Video::getLinkToVideo($videos_id); +?> + + + + + + + + + + + + + + +"; + } + if (empty($source['url'])) { + echo ""; + } +} else { + $source['url'] = str_replace(".m3u8", ".m3u8.mp4", $source['url']); +} +if (!AVideoPlugin::isEnabledByName("SecureVideosDirectory") && !empty($source['url'])) { + ?> + + + + + + "; + } + if (empty($source['url'])) { + echo ""; + } ?> + + + + + + + +twitter_player)) { + if (!AVideoPlugin::isEnabledByName("SecureVideosDirectory") && !empty($source['url'])) { + ?> + + " /> + + + + + + + + + + twitter_summary_large_image)) { + ?> + + + + + + + + + + -
- -
-
-
- -
- - +
+
+ +
+
+
+ +
+ + diff --git a/objects/functiongetShareMenu.php b/objects/functiongetShareMenu.php index 708286d5bb..807ae7f446 100644 --- a/objects/functiongetShareMenu.php +++ b/objects/functiongetShareMenu.php @@ -1,202 +1,197 @@ - -
-
-
- -
-
- -
-
-

(Iframe):

- -

(Object):

- -

(HTML):

- -

(BBCode):

- -
- disableEmailSharing)) { - $loaderSequenceName = uniqid(); - ?> -
- - - - - -
-
- -
- -
-
- - " class="form-control" type="text"> -
-
-
- - - -
- -
-
- - -
-
-
-
- -
-
- - - " class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText"> -
-
-
- -
- -
- -
-
- -
-
- - -
- - - - -
-
-
-
+ +
+
+
+ +
+
+ +
+
+

(Iframe):

+ +

(Object):

+ +

(HTML):

+ +

(BBCode):

+ +
+ disableEmailSharing)) { + $loaderSequenceName = uniqid(); ?> +
+ + + + + +
+
+ +
+ +
+
+ + " class="form-control" type="text"> +
+
+
+ + + +
+ +
+
+ + +
+
+
+
+ +
+
+ + + " class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText"> +
+
+
+ +
+ +
+ +
+
+ +
+
+ + +
+ + + + +
+
+
+
diff --git a/objects/functionogSite.php b/objects/functionogSite.php index 705eada537..5e7fb588a7 100644 --- a/objects/functionogSite.php +++ b/objects/functionogSite.php @@ -1,86 +1,82 @@ -".PHP_EOL; -if ($users_id = isChannel()) { - echo PHP_EOL."".PHP_EOL; - $imgw = 200; - $imgh = 200; - $img = User::getOGImage($users_id); - $title = User::getNameIdentificationById($users_id); - $url = User::getChannelLink($users_id); - ?> - - - ".PHP_EOL; - ?> - - - getWebSiteTitle()); - $url = $global['webSiteRootURL']; - echo PHP_EOL."".PHP_EOL; - ?> - - - getDescription(); - } -} - -$description = $title; -if(!empty($customizePluginDescription)){ - $description = $customizePluginDescription; -}else -if(!empty($metaDescription)){ - $description = $metaDescription; -} - -?> - - - - - - - - - - - - - - -twitter_summary_large_image)) { - ?> - - - - - - - +".PHP_EOL; +if ($users_id = isChannel()) { + echo PHP_EOL."".PHP_EOL; + $imgw = 200; + $imgh = 200; + $img = User::getOGImage($users_id); + $title = User::getNameIdentificationById($users_id); + $url = User::getChannelLink($users_id); ?> + + + ".PHP_EOL; ?> + + + getWebSiteTitle()); + $url = $global['webSiteRootURL']; + echo PHP_EOL."".PHP_EOL; ?> + + + getDescription(); + } +} + +$description = $title; +if (!empty($customizePluginDescription)) { + $description = $customizePluginDescription; +} elseif (!empty($metaDescription)) { + $description = $metaDescription; +} + +?> + + + + + + + + + + + + + + +twitter_summary_large_image)) { + ?> + + + + + + + \ No newline at end of file diff --git a/objects/functions.php b/objects/functions.php index 0adc9428f2..74b10f809e 100644 --- a/objects/functions.php +++ b/objects/functions.php @@ -1,7704 +1,8073 @@ - 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) { - if (!is_numeric($time)) { - $time = strtotime($time); - } - $time = secondsIntervalFromNow($time, $useDatabaseTime); - if (empty($time)) { - return __("Now"); - } else if ($time > 0) { - return secondsToHumanTiming($time, $precision) . ' ' . __('Ago'); - } - 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.3.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 isAPPInstalled($appName) { - $appName = preg_replace('/[^a-z0-9_-]/i', '', $appName); - return trim(shell_exec("which {$appName}")); -} - -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"] == "Test of comment" && User::isAdmin()) { - $mail->SMTPDebug = 3; - $mail->Debugoutput = function ($str, $level) { - _error_log("SMTP ERROR $level; message: $str", AVideoLog::$ERROR); - }; - } - $mail->SMTPOptions = array( - 'ssl' => array( - 'verify_peer' => false, - 'verify_peer_name' => false, - 'allow_self_signed' => true - ) - ); - $mail->SMTPAuth = $config->getSmtpAuth(); // authentication enabled - $mail->SMTPSecure = $config->getSmtpSecure(); // secure transfer enabled REQUIRED for Gmail - $mail->Host = $config->getSmtpHost(); - $mail->Port = $config->getSmtpPort(); - $mail->Username = $config->getSmtpUsername(); - $mail->Password = $config->getSmtpPassword(); - //_error_log(print_r($config, true)); - } else { - _error_log("Sending SendMail Email"); - $mail->isSendmail(); - } -} - -function array_iunique($array) { - return array_intersect_key($array, array_unique(array_map("strtolower", $array))); -} - -function partition(array $list, $totalItens) { - $listlen = count($list); - _error_log("partition: listlen={$listlen} totalItens={$totalItens}"); - $p = ceil($listlen / $totalItens); - $partlen = floor($listlen / $p); - - $partition = array(); - $mark = 0; - for ($index = 0; $index < $p; $index++) { - $partition[$index] = array_slice($list, $mark, $totalItens); - $mark += $totalItens; - } - - return $partition; -} - -function sendSiteEmail($to, $subject, $message) { - global $advancedCustom; - if (empty($to)) { - return false; - } - if (!is_array($to)) { - $to = array($to); - } - - if (empty($advancedCustom)) { - $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); - } - - $subject = UTF8encode($subject); - $message = UTF8encode($message); - $message = createEmailMessageFromTemplate($message); - _error_log("sendSiteEmail [" . count($to) . "] {$subject}"); - global $config, $global; - //require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; - $contactEmail = $config->getContactEmail(); - $webSiteTitle = $config->getWebSiteTitle(); - try { - if (!is_array($to)) { - $mail = new \PHPMailer\PHPMailer\PHPMailer; - setSiteSendMessage($mail); - $mail->setFrom($contactEmail, $webSiteTitle); - $mail->Subject = $subject . " - " . $webSiteTitle; - $mail->msgHTML($message); - - $mail->addAddress($to); - - $resp = $mail->send(); - if (!$resp) { - _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); - } else { - _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); - } - } else { - $size = intval(@$advancedCustom->splitBulkEmailSend); - if (empty($size)) { - $size = 90; - } - - $to = array_iunique($to); - $pieces = partition($to, $size); - foreach ($pieces as $piece) { - $mail = new \PHPMailer\PHPMailer\PHPMailer; - setSiteSendMessage($mail); - $mail->setFrom($contactEmail, $webSiteTitle); - $mail->Subject = $subject . " - " . $webSiteTitle; - $mail->msgHTML($message); - $count = 0; - foreach ($piece as $value) { - $count++; - _error_log("sendSiteEmail::addBCC [{$count}] {$value}"); - $mail->addBCC($value); - } - - $resp = $mail->send(); - if (!$resp) { - _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); - } else { - _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); - } - } - } - //Set the subject line - return $resp; - } catch (phpmailerException $e) { - _error_log($e->errorMessage()); //Pretty error messages from PHPMailer - } catch (Exception $e) { - _error_log($e->getMessage()); //Boring error messages from anything else! - } -} - -function sendSiteEmailAsync($to, $subject, $message) { - global $global; - $content = array('to' => $to, 'subject' => $subject, 'message' => $message); - $tmpFile = getTmpFile(); - file_put_contents($tmpFile, _json_encode($content)); - //outputAndContinueInBackground(); - $command = "php {$global['systemRootPath']}objects/sendSiteEmailAsync.php '$tmpFile'"; - - _error_log("sendSiteEmailAsync start ($command)"); - $pid = execAsync($command); - _error_log("sendSiteEmailAsync end {$pid}"); - return $pid; -} - -function createEmailMessageFromTemplate($message) { - - //check if the message already have a HTML body - if (preg_match("/html>/i", $message)) { - return $message; - } - - global $global, $config; - $text = file_get_contents("{$global['systemRootPath']}view/include/emailTemplate.html"); - $siteTitle = $config->getWebSiteTitle(); - $logo = "getLogo(true) . "\" alt=\"{$siteTitle}\">"; - - $words = array($logo, $message, $siteTitle); - $replace = array('{logo}', '{message}', '{siteTitle}'); - - return str_replace($replace, $words, $text); -} - -function sendEmailToSiteOwner($subject, $message) { - global $advancedCustom; - $subject = UTF8encode($subject); - $message = UTF8encode($message); - _error_log("sendEmailToSiteOwner {$subject}"); - global $config, $global; - require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; - $contactEmail = $config->getContactEmail(); - $webSiteTitle = $config->getWebSiteTitle(); - try { - $mail = new \PHPMailer\PHPMailer\PHPMailer; - setSiteSendMessage($mail); - $mail->setFrom($contactEmail, $webSiteTitle); - $mail->Subject = $subject . " - " . $webSiteTitle; - $mail->msgHTML($message); - $mail->addAddress($contactEmail); - $resp = $mail->send(); - if (!$resp) { - _error_log("sendEmailToSiteOwner Error Info: {$mail->ErrorInfo}"); - } else { - _error_log("sendEmailToSiteOwner Success Info: $subject " . json_encode($to)); - } - return $resp; - } catch (phpmailerException $e) { - _error_log($e->errorMessage()); //Pretty error messages from PHPMailer - } catch (Exception $e) { - _error_log($e->getMessage()); //Boring error messages from anything else! - } -} - -function parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { - global $global; - //_error_log("parseVideos: $videoString"); - if (strpos($videoString, 'youtube.com/embed') !== false) { - return $videoString . (parse_url($videoString, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' - . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; - } - if (strpos($videoString, 'iframe') !== false) { - // retrieve the video url - $anchorRegex = '/src="(.*)?"/isU'; - $results = array(); - if (preg_match($anchorRegex, $video, $results)) { - $link = trim($results[1]); - } - } else { - // we already have a url - $link = $videoString; - } - - if (stripos($link, 'embed') !== false) { - return $link . (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' - . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; - } elseif (strpos($link, 'youtube.com') !== false) { - preg_match( - '/[\\?\\&]v=([^\\?\\&]+)/', - $link, - $matches - ); - //the ID of the YouTube URL: x6qe_kVaBpg - if (empty($matches[1])) { - return $link; - } - $id = $matches[1]; - return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' - . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; - } elseif (strpos($link, 'youtu.be') !== false) { - //https://youtu.be/9XXOBSsPoMU - preg_match( - '/youtu.be\/([a-zA-Z0-9_]+)($|\/)/', - $link, - $matches - ); - //the ID of the YouTube URL: x6qe_kVaBpg - $id = $matches[1]; - return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' - . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; - } elseif (strpos($link, 'player.vimeo.com') !== false) { - // works on: - // http://player.vimeo.com/video/37985580?title=0&byline=0&portrait=0 - $videoIdRegex = '/player.vimeo.com\/video\/([0-9]+)\??/i'; - preg_match($videoIdRegex, $link, $matches); - $id = $matches[1]; - return '//player.vimeo.com/video/' . $id; - } elseif (strpos($link, 'vimeo.com/channels') !== false) { - //extract the ID - preg_match( - '/\/\/(www\.)?vimeo.com\/channels\/[a-z0-9-]+\/(\d+)($|\/)/i', - $link, - $matches - ); - - //the ID of the Vimeo URL: 71673549 - $id = $matches[2]; - return '//player.vimeo.com/video/' . $id; - } elseif (strpos($link, 'vimeo.com') !== false) { - //extract the ID - preg_match( - '/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/', - $link, - $matches - ); - - //the ID of the Vimeo URL: 71673549 - $id = $matches[2]; - return '//player.vimeo.com/video/' . $id; - } elseif (strpos($link, 'dailymotion.com') !== false) { - //extract the ID - preg_match( - '/\/\/(www\.)?dailymotion.com\/video\/([a-zA-Z0-9_]+)($|\/)/', - $link, - $matches - ); - - //the ID of the Vimeo URL: 71673549 - $id = $matches[2]; - return '//www.dailymotion.com/embed/video/' . $id; - } elseif (strpos($link, 'metacafe.com') !== false) { - //extract the ID - preg_match( - '/\/\/(www\.)?metacafe.com\/watch\/([a-zA-Z0-9_\/-]+)$/', - $link, - $matches - ); - $id = $matches[2]; - return '//www.metacafe.com/embed/' . $id; - } elseif (strpos($link, 'vid.me') !== false) { - //extract the ID - preg_match( - '/\/\/(www\.)?vid.me\/([a-zA-Z0-9_-]+)$/', - $link, - $matches - ); - - $id = $matches[2]; - return '//vid.me/e/' . $id; - } elseif (strpos($link, 'rutube.ru') !== false) { - //extract the ID - preg_match('/\/\/(www\.)?rutube.ru\/video\/([a-zA-Z0-9_-]+)\/.*/', $link, $matches); - $id = $matches[2]; - return '//rutube.ru/play/embed/' . $id; - } elseif (strpos($link, 'ok.ru') !== false) { - //extract the ID - preg_match('/\/\/(www\.)?ok.ru\/video\/([a-zA-Z0-9_-]+)$/', $link, $matches); - - $id = $matches[2]; - return '//ok.ru/videoembed/' . $id; - } elseif (strpos($link, 'streamable.com') !== false) { - //extract the ID - preg_match('/\/\/(www\.)?streamable.com\/([a-zA-Z0-9_-]+)$/', $link, $matches); - - $id = $matches[2]; - return '//streamable.com/s/' . $id; - } elseif (strpos($link, 'twitch.tv/videos') !== false) { - //extract the ID - preg_match('/\/\/(www\.)?twitch.tv\/videos\/([a-zA-Z0-9_-]+)$/', $link, $matches); - if (!empty($matches[2])) { - $id = $matches[2]; - return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); - } - //extract the ID - preg_match('/\/\/(www\.)?twitch.tv\/[a-zA-Z0-9_-]+\/v\/([a-zA-Z0-9_-]+)$/', $link, $matches); - - $id = $matches[2]; - return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); - } elseif (strpos($link, 'twitch.tv') !== false) { - //extract the ID - preg_match('/\/\/(www\.)?twitch.tv\/([a-zA-Z0-9_-]+)$/', $link, $matches); - - $id = $matches[2]; - return '//player.twitch.tv/?channel=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); - } elseif (strpos($link, 'bitchute.com/video') !== false) { - //extract the ID - preg_match('/\/\/(www\.)?bitchute.com\/video\/([^\/]+)/', $link, $matches); - $id = $matches[2]; - return 'https://www.bitchute.com/embed/' . $id . '/?parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); - } elseif (strpos($link, '/evideo/') !== false) { - //extract the ID - preg_match('/(http.+)\/evideo\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); - - //the AVideo site - $site = $matches[1]; - $id = $matches[2]; - return $site . '/evideoEmbed/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; - } elseif (strpos($link, '/video/') !== false) { - //extract the ID - preg_match('/(http.+)\/video\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); - - //the AVideo site - if (!empty($matches[1])) { - $site = $matches[1]; - $id = $matches[2]; - return $site . '/videoEmbeded/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; - } else { - return $link; - } - } - - $url = $videoString; - $url_parsed = parse_url($url); - if (empty($url_parsed['query'])) { - return ""; - } - $new_qs_parsed = array(); - // Grab our first query string - parse_str($url_parsed['query'], $new_qs_parsed); - // Here's the other query string - $other_query_string = 'modestbranding=1&showinfo=' - . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; - $other_qs_parsed = array(); - parse_str($other_query_string, $other_qs_parsed); - // Stitch the two query strings together - $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); - $final_query_string = http_build_query($final_query_string_array); - // Now, our final URL: - if (empty($url_parsed['scheme'])) { - $scheme = ''; - } else { - $scheme = "{$url_parsed['scheme']}:"; - } - $new_url = $scheme - . '//' - . $url_parsed['host'] - . $url_parsed['path'] - . '?' - . $final_query_string; - - return $new_url; - // return data -} - -$canUseCDN = array(); - -function canUseCDN($videos_id) { - if (empty($videos_id)) { - return false; - } - global $global, $canUseCDN; - if (!isset($canUseCDN[$videos_id])) { - require_once $global['systemRootPath'] . 'plugin/VR360/Objects/VideosVR360.php'; - $pvr360 = AVideoPlugin::isEnabledByName('VR360'); - // if the VR360 is enabled you can not use the CDN, it fail to load the GL - $isVR360Enabled = VideosVR360::isVR360Enabled($videos_id); - if ($pvr360 && $isVR360Enabled) { - $ret = false; - } else { - $ret = true; - } - - //_error_log(json_encode(array('canUseCDN'=>$ret, '$pvr360'=>$pvr360, '$isVR360Enabled'=>$isVR360Enabled, '$videos_id'=>$videos_id))); - $canUseCDN[$videos_id] = $ret; - } - return $canUseCDN[$videos_id]; -} - -function clearVideosURL($fileName = "") { - global $global; - $path = getCacheDir() . "getVideosURL/"; - if (empty($path)) { - rrmdir($path); - } else { - $cacheFilename = "{$path}{$fileName}.cache"; - @unlink($cacheFilename); - } -} - -function maxLifetime() { - global $maxLifetime; - if (!isset($maxLifetime)) { - $aws_s3 = AVideoPlugin::getObjectDataIfEnabled('AWS_S3'); - $bb_b2 = AVideoPlugin::getObjectDataIfEnabled('Blackblaze_B2'); - $secure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); - $maxLifetime = 0; - if (!empty($aws_s3) && empty($aws_s3->makeMyFilesPublicRead) && !empty($aws_s3->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $aws_s3->presignedRequestSecondsTimeout < $maxLifetime)) { - $maxLifetime = $aws_s3->presignedRequestSecondsTimeout; - //_error_log("maxLifetime: AWS_S3 = {$maxLifetime}"); - } - if (!empty($bb_b2) && empty($bb_b2->usePublicBucket) && !empty($bb_b2->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $bb_b2->presignedRequestSecondsTimeout < $maxLifetime)) { - $maxLifetime = $bb_b2->presignedRequestSecondsTimeout; - //_error_log("maxLifetime: B2 = {$maxLifetime}"); - } - if (!empty($secure) && !empty($secure->tokenTimeOut) && (empty($maxLifetime) || $secure->tokenTimeOut < $maxLifetime)) { - $maxLifetime = $secure->tokenTimeOut; - //_error_log("maxLifetime: Secure = {$maxLifetime}"); - } - } - return $maxLifetime; -} - -$cacheExpirationTime = false; - -function cacheExpirationTime() { - if (isBot()) { - return 604800; // 1 week - } - global $cacheExpirationTime; - if (empty($cacheExpirationTime)) { - $obj = AVideoPlugin::getObjectDataIfEnabled('Cache'); - $cacheExpirationTime = @$obj->cacheTimeInSeconds; - } - return intval($cacheExpirationTime); -} - -/** - * Tell whether a file should recreate a cache, based on its time and the plugin's token expiration. - * @param type $filename - * @return boolean - */ -function recreateCache($filename) { - return (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()); -} - -function _getImagesURL($fileName, $type) { - global $global; - $files = array(); - $source = Video::getSourceFile($fileName, ".jpg"); - $file1 = $source['path']; - if (file_exists($file1)) { - $files["jpg"] = array( - 'filename' => "{$fileName}.jpg", - 'path' => $file1, - 'url' => $source['url'], - 'type' => 'image', - ); - } else { - unset($file1); - $files["jpg"] = array( - 'filename' => "{$type}.png", - 'path' => getCDN() . "view/img/{$type}.png", - 'url' => getCDN() . "view/img/{$type}.png", - 'type' => 'image', - ); - } - $source = Video::getSourceFile($fileName, "_portrait.jpg"); - $file2 = $source['path']; - if (file_exists($file2)) { - $files["pjpg"] = array( - 'filename' => "{$fileName}_portrait.jpg", - 'path' => $file2, - 'url' => $source['url'], - 'type' => 'image', - ); - } elseif ($type != 'image') { - if (!empty($file1)) { - $files["pjpg"] = $files["jpg"]; - } else { - $files["pjpg"] = array( - 'filename' => "{$type}_portrait.png", - 'path' => getCDN() . "view/img/{$type}_portrait.png", - 'url' => getCDN() . "view/img/{$type}_portrait.png", - 'type' => 'image', - ); - } - } - return $files; -} - -function getVideosURLPDF($fileName) { - global $global; - if (empty($fileName)) { - return array(); - } - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $start = $time; - - $source = Video::getSourceFile($fileName, ".pdf"); - $file = $source['path']; - $files["pdf"] = array( - 'filename' => "{$fileName}.pdf", - 'path' => $file, - 'url' => $source['url'], - 'type' => 'pdf', - ); - $files = array_merge($files, _getImagesURL($fileName, 'pdf')); - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $finish = $time; - $total_time = round(($finish - $start), 4); - //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); - return $files; -} - -function getVideosURLIMAGE($fileName) { - global $global; - if (empty($fileName)) { - return array(); - } - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $start = $time; - - $types = array('png', 'gif', 'webp', 'jpg'); - - foreach ($types as $value) { - $source = Video::getSourceFile($fileName, ".{$value}"); - $file = $source['path']; - $files["image"] = array( - 'filename' => "{$fileName}.{$value}", - 'path' => $file, - 'url' => $source['url'], - 'type' => 'image', - ); - if (file_exists($file)) { - break; - } - } - - $files = array_merge($files, _getImagesURL($fileName, 'image')); - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $finish = $time; - $total_time = round(($finish - $start), 4); - //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); - return $files; -} - -function getVideosURLZIP($fileName) { - global $global; - if (empty($fileName)) { - return array(); - } - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $start = $time; - - $types = array('zip'); - - foreach ($types as $value) { - $source = Video::getSourceFile($fileName, ".{$value}"); - $file = $source['path']; - $files["zip"] = array( - 'filename' => "{$fileName}.zip", - 'path' => $file, - 'url' => $source['url'], - 'type' => 'zip', - ); - if (file_exists($file)) { - break; - } - } - - $files = array_merge($files, _getImagesURL($fileName, 'zip')); - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $finish = $time; - $total_time = round(($finish - $start), 4); - //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); - return $files; -} - -function getVideosURLArticle($fileName) { - global $global; - if (empty($fileName)) { - return array(); - } - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $start = $time; - //$files = array_merge($files, _getImagesURL($fileName, 'article')); - $files = _getImagesURL($fileName, 'article'); - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $finish = $time; - $total_time = round(($finish - $start), 4); - //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); - return $files; -} - -function getVideosURLAudio($fileName, $fileNameisThePath = false) { - global $global; - if (empty($fileName)) { - return array(); - } - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $start = $time; - if ($fileNameisThePath) { - $filename = basename($fileName); - $path = Video::getPathToFile($filename); - if (filesize($path) < 20) { - $objCDNS = AVideoPlugin::getObjectDataIfEnabled('CDN'); - if (!empty($objCDNS) && $objCDNS->enable_storage) { - $url = CDNStorage::getURL("{$filename}"); - } - } - if (empty($url)) { - $url = Video::getURLToFile($filename); - } - - $files["mp3"] = array( - 'filename' => $filename, - 'path' => $path, - 'url' => $url, - 'url_noCDN' => $url, - 'type' => 'audio', - 'format' => 'mp3', - ); - } else { - $source = Video::getSourceFile($fileName, ".mp3"); - $file = $source['path']; - $files["mp3"] = array( - 'filename' => "{$fileName}.mp3", - 'path' => $file, - 'url' => $source['url'], - 'url_noCDN' => @$source['url_noCDN'], - 'type' => 'audio', - 'format' => 'mp3', - ); - } - - $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 getVideosURLMP3Only($fileName) { - $allFiles = getVideosURL_V2($fileName); - if (is_array($allFiles)) { - foreach ($allFiles as $key => $value) { - if ($value['format'] !== 'mp3') { - 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 getVideosURLMP4WEBMMP3Only($fileName) { - return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName), getVideosURLMP3Only($fileName)); -} - -function getVideosURLOnly($fileName) { - $allFiles = getVideosURL_V2($fileName); // disable this function soon - foreach ($allFiles as $key => $value) { - if ($value['type'] !== 'video') { - unset($allFiles[$key]); - } - } - return $allFiles; -} - -function getAudioURLOnly($fileName) { - $allFiles = getVideosURL_V2($fileName); // disable this function soon - foreach ($allFiles as $key => $value) { - if ($value['type'] !== 'audio') { - unset($allFiles[$key]); - } - } - return $allFiles; -} - -function getAudioOrVideoURLOnly($fileName) { - $allFiles = getVideosURL_V2($fileName); // disable this function soon - foreach ($allFiles as $key => $value) { - if ($value['type'] !== 'video' && $value['type'] !== 'audio') { - unset($allFiles[$key]); - } - } - return $allFiles; -} - -function getVideosDir() { - return Video::getStoragePath(); -} - -$getVideosURL_V2Array = array(); - -function getVideosURL_V2($fileName, $recreateCache = false) { - global $global, $getVideosURL_V2Array; - if (empty($fileName)) { - return array(); - } - //$recreateCache = true; - $cleanfilename = Video::getCleanFilenameFromFile($fileName); - - if (!empty($getVideosURL_V2Array[$cleanfilename])) { - return $getVideosURL_V2Array[$cleanfilename]; - } - - $paths = Video::getPaths($cleanfilename); - - $pdf = $paths['path'] . "{$cleanfilename}.pdf"; - $mp3 = $paths['path'] . "{$cleanfilename}.mp3"; - if (file_exists($pdf)) { - return getVideosURLPDF($fileName); - } elseif (file_exists($mp3)) { - return getVideosURLAudio($mp3, true); - } - $cacheName = "getVideosURL_V2$fileName"; - if (empty($recreateCache)) { - $lifetime = maxLifetime(); - - $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; - TimeLogStart($TimeLog1); - $files = object_to_array(ObjectYPT::getCache($cacheName, $lifetime, true)); - if (is_array($files)) { - //_error_log("getVideosURL_V2: do NOT recreate lifetime = {$lifetime}"); - $preg_match_url = addcslashes(getCDN(), "/") . "videos"; - foreach ($files as $value) { - // check if is a dummy file and the URL still wrong - $pathFilesize = filesize($value['path']); - if ( - $value['type'] === 'video' && // is a video - preg_match("/^{$preg_match_url}/", $value['url']) && // the URL is the same as the main domain - $pathFilesize < 20) { // file size is small - _error_log("getVideosURL_V2:: dummy file found, fix cache " . json_encode(array("/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), $pathFilesize, $value))); - unset($files); - $video = Video::getVideoFromFileName($fileName, true, true); - Video::clearCache($video['id']); - break; - } else { - //_error_log("getVideosURL_V2:: NOT dummy file ". json_encode(array("/^{$preg_match_url}video/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']),filesize($value['path']),$value))); - } - } - //_error_log("getVideosURL_V2:: cachestill good ". json_encode($files)); - } else { - //_error_log("getVideosURL_V2:: cache not found ". json_encode($files)); - } - TimeLogEnd($TimeLog1, __LINE__); - } else { - _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - } - if (empty($files)) { - $files = array(); - $plugin = AVideoPlugin::loadPlugin("VideoHLS"); - if (!empty($plugin)) { - $timeName = "getVideosURL_V2::VideoHLS::getSourceFile($fileName)"; - TimeLogStart($timeName); - $files = VideoHLS::getSourceFile($fileName, true); - TimeLogEnd($timeName, __LINE__); - } - $video = array('webm', 'mp4'); - $audio = array('mp3', 'ogg'); - $image = array('jpg', 'gif', 'webp'); - - $formats = array_merge($video, $audio, $image); - - //$globQuery = getVideosDir()."{$cleanfilename}*.{" . implode(",", $formats) . "}"; - //$filesInDir = glob($globQuery, GLOB_BRACE); - $timeName = "getVideosURL_V2::globVideosDir($cleanfilename)"; - TimeLogStart($timeName); - $filesInDir = globVideosDir($cleanfilename, true); - TimeLogEnd($timeName, __LINE__); - - $timeName = "getVideosURL_V2::foreach"; - TimeLogStart($timeName); - foreach ($filesInDir as $file) { - $parts = pathinfo($file); - - if ($parts['filename'] == 'index') { - $parts['filename'] = str_replace(Video::getPathToFile($parts['dirname']), '', $parts['dirname']); - } - - //$timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; - //TimeLogStart($timeName2); - $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); - //TimeLogEnd($timeName2, __LINE__); - if (empty($source)) { - continue; - } - if (in_array($parts['extension'], $image) && filesize($file) < 1000 && !preg_match("/Dummy File/i", file_get_contents($file))) { - continue; - } - - if (preg_match("/{$cleanfilename}(_.+)[.]{$parts['extension']}$/", $file, $matches)) { - $resolution = $matches[1]; - } else { - preg_match('/_([^_]{0,4}).' . $parts['extension'] . '$/', $file, $matches); - $resolution = @$matches[1]; - } - $type = 'video'; - if (in_array($parts['extension'], $video)) { - $type = 'video'; - } elseif (in_array($parts['extension'], $audio)) { - $type = 'audio'; - } elseif (in_array($parts['extension'], $image) || preg_match('/^(gif|jpg|webp|png|jpeg)/i', $parts['extension'])) { - $type = 'image'; - if (!preg_match('/(thumb|roku)/', $resolution)) { - $resolution = ''; - } - } - $files["{$parts['extension']}{$resolution}"] = array( - 'filename' => "{$parts['filename']}.{$parts['extension']}", - 'path' => $file, - 'url' => $source['url'], - 'url_noCDN' => @$source['url_noCDN'], - '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: ($file_src) " . $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); - if (empty($src)) { - return false; - } - $ws = imagesx($src); - $hs = imagesy($src); - - if ($ws < $wd) { - $dst_x = ($wd - $ws) / 2; - } else { - $dst_x = 0; - } - - if ($hs < $hd) { - $dst_y = ($hd - $hs) / 2; - } else { - $dst_y = 0; - } - - $mapImage = imagecreatetruecolor($wd, $hd); - $bgColor = imagecolorallocate($mapImage, 0, 0, 0); - imagefill($mapImage, 0, 0, $bgColor); - - $tileImg = imagecreatefromjpeg($file_dest); - imagecopy($mapImage, $tileImg, $dst_x, $dst_y, 0, 0, $ws, $hs); - - $saved = imagejpeg($mapImage, $file_dest, $q); - - return $saved; -} - -function im_resizePNG($file_src, $file_dest, $wd, $hd) { - - $srcImage = imagecreatefrompng($file_src); - $ws = imagesx($srcImage); - $hs = imagesy($srcImage); - - $targetImage = imagecreatetruecolor($wd, $hd); - imagealphablending($targetImage, false); - imagesavealpha($targetImage, true); - - imagecopyresampled($targetImage, $srcImage, - 0, 0, - 0, 0, - $wd, $hd, - $ws, $hs); - - $saved = imagepng($targetImage, $file_dest); - - return $saved; -} - -function im_resizeV3($file_src, $file_dest, $wd, $hd) { - - return im_resizeV2($file_src, $file_dest, $wd, $hd); // ffmpeg disabled - - _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_gif($file_src, $file_dest, $max_width, $max_height) { - if (class_exists('Imagick')) { - $imagick = new Imagick($file_src); - - $format = $imagick->getImageFormat(); - if ($format == 'GIF') { - $imagick = $imagick->coalesceImages(); - do { - $imagick->resizeImage($max_width, $max_height, Imagick::FILTER_BOX, 1); - } while ($imagick->nextImage()); - $imagick = $imagick->deconstructImages(); - $imagick->writeImages($file_dest, true); - } - - $imagick->clear(); - $imagick->destroy(); - } else { - copy($file_src, $file_dest); - } -} - -function im_resize_max_size($file_src, $file_dest, $max_width, $max_height) { - $fn = $file_src; - - $extension = strtolower(pathinfo($file_dest, PATHINFO_EXTENSION)); - - if ($extension == 'gif') { - im_resize_gif($file_src, $file_dest, $max_width, $max_height); - @unlink($file_src); - return true; - } - - $tmpFile = getTmpFile() . ".{$extension}"; - 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)) { - //_error_log("convertImage: IMAGETYPE_JPEG"); - $imageTmp = imagecreatefromjpeg($originalImage); - } elseif ($imagetype == IMAGETYPE_PNG || preg_match('/png/i', $ext)) { - //_error_log("convertImage: IMAGETYPE_PNG"); - $imageTmp = imagecreatefrompng($originalImage); - } elseif ($imagetype == IMAGETYPE_GIF || preg_match('/gif/i', $ext)) { - //_error_log("convertImage: IMAGETYPE_GIF"); - $imageTmp = imagecreatefromgif($originalImage); - } elseif ($imagetype == IMAGETYPE_BMP || preg_match('/bmp/i', $ext)) { - //_error_log("convertImage: IMAGETYPE_BMP"); - $imageTmp = imagecreatefrombmp($originalImage); - } elseif ($imagetype == IMAGETYPE_WEBP || preg_match('/webp/i', $ext)) { - //_error_log("convertImage: IMAGETYPE_WEBP"); - $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 ($imageTmp===false) { - _error_log("convertImage: could not create a resource: $originalImage, $outputImage, $quality, $ext " . json_encode(debug_backtrace())); - 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") { - if ($filename == '.zip') { - return false; - } - global $global; - $obj = new stdClass(); - $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); - $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); - $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); - $paths = Video::getPaths($filename, true); - $destinationFile = "{$paths['path']}{$filename}"; - //$destinationFile = getVideosDir() . "{$filename}"; - _error_log("decideMoveUploadedToVideos: {$filename}"); - $path_info = pathinfo($filename); - if ($type !== "zip" && $path_info['extension'] === 'zip') { - _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); - $paths = Video::getPaths($path_info['filename']); - $dir = $paths['path']; - unzipDirectory($tmp_name, $dir); // unzip it - cleanDirectory($dir); - if (!empty($aws_s3)) { - //$aws_s3->move_uploaded_file($tmp_name, $filename); - } elseif (!empty($bb_b2)) { - $bb_b2->move_uploaded_directory($dir); - } elseif (!empty($ftp)) { - //$ftp->move_uploaded_file($tmp_name, $filename); - } - } else { - _error_log("decideMoveUploadedToVideos: NOT ZIp file {$filename}"); - if (!empty($aws_s3)) { - _error_log("decideMoveUploadedToVideos: S3 {$filename}"); - $aws_s3->move_uploaded_file($tmp_name, $filename); - } elseif (!empty($bb_b2)) { - _error_log("decideMoveUploadedToVideos: B2 {$filename}"); - $bb_b2->move_uploaded_file($tmp_name, $filename); - } elseif (!empty($ftp)) { - _error_log("decideMoveUploadedToVideos: FTP {$filename}"); - $ftp->move_uploaded_file($tmp_name, $filename); - } else { - _error_log("decideMoveUploadedToVideos: Local {$filename}"); - if (!move_uploaded_file($tmp_name, $destinationFile)) { - if (!rename($tmp_name, $destinationFile)) { - if (!copy($tmp_name, $destinationFile)) { - $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, $destinationFile)"; - die(json_encode($obj)); - } - } - } - if (file_exists($destinationFile)) { - _error_log("decideMoveUploadedToVideos: SUCCESS Local {$destinationFile}"); - } else { - _error_log("decideMoveUploadedToVideos: ERROR Local {$destinationFile}"); - } - chmod($destinationFile, 0644); - } - } - sleep(1); - $fsize = @filesize($destinationFile); - _error_log("decideMoveUploadedToVideos: destinationFile {$destinationFile} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")"); - Video::clearCacheFromFilename($filename); - return $destinationFile; -} - -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) { - $created = false; - if (substr($path, -1) !== DIRECTORY_SEPARATOR) { - $path = pathinfo($path, PATHINFO_DIRNAME); - } - if (!is_dir($path)) { - //if(preg_match('/getvideoinfo/i', $path)){var_dump(debug_backtrace());} - $created = mkdir($path, 0755, true); - /* - if (!$created) { - _error_log('make_path: could not create the dir ' . json_encode($path) . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - } - */ - } else { - $created = true; - } - return $created; -} - -/** - * for security clean all non secure files from directory - * @param type $dir - * @param type $allowedExtensions - * @return type - */ -function cleanDirectory($dir, $allowedExtensions = array('key', 'm3u8', 'ts', 'vtt', 'jpg', 'gif', 'mp3', 'webm', 'webp')) { - $ffs = scandir($dir); - - unset($ffs[array_search('.', $ffs, true)]); - unset($ffs[array_search('..', $ffs, true)]); - - // prevent empty ordered elements - if (count($ffs) < 1) { - return; - } - - foreach ($ffs as $ff) { - $current = $dir . '/' . $ff; - if (is_dir($current)) { - cleanDirectory($current, $allowedExtensions); - } - $path_parts = pathinfo($current); - if (!empty($path_parts['extension']) && !in_array($path_parts['extension'], $allowedExtensions)) { - unlink($current); - } - } -} - -function decideFile_put_contentsToVideos($tmp_name, $filename) { - global $global; - $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); - $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); - $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); - if (!empty($bb_b2)) { - $bb_b2->move_uploaded_file($tmp_name, $filename); - } elseif (!empty($aws_s3)) { - $aws_s3->move_uploaded_file($tmp_name, $filename); - } elseif (!empty($ftp)) { - $ftp->move_uploaded_file($tmp_name, $filename); - } else { - $path = Video::getPathToFile($filename); - if (!move_uploaded_file($tmp_name, $path)) { - $obj->msg = "Error on move_uploaded_file({$tmp_name}, {$filename})"; - die(json_encode($obj)); - } - } -} - -function isAnyStorageEnabled() { - if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) { - return true; - } else - if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { - return true; - } else - if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { - return true; - } else - if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { - return true; - } - return false; -} - -if (!function_exists('mime_content_type')) { - - function mime_content_type($filename) { - return mime_content_type_per_filename($filename); - } - -} - -function fontAwesomeClassName($filename) { - $mime_type = mime_content_type_per_filename($filename); - // List of official MIME Types: http://www.iana.org/assignments/media-types/media-types.xhtml - $icon_classes = array( -// Media - 'image' => 'fas fa-file-image', - 'audio' => 'fas fa-file-audio', - 'video' => 'fas fa-file-video', - // Documents - 'application/pdf' => 'fas fa-file-pdf', - 'application/msword' => 'fas fa-file-word', - 'application/vnd.ms-word' => 'fas fa-file-word', - 'application/vnd.oasis.opendocument.text' => 'fas fa-file-word', - 'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fas fa-file-word', - 'application/vnd.ms-excel' => 'fas fa-file-excel', - 'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fas fa-file-excel', - 'application/vnd.oasis.opendocument.spreadsheet' => 'fas fa-file-excel', - 'application/vnd.ms-powerpoint' => 'fas fa-file-powerpoint', - 'application/vnd.openxmlformats-officedocument.presentationml' => 'fas fa-file-powerpoint', - 'application/vnd.oasis.opendocument.presentation' => 'fas fa-file-powerpoint', - 'text/plain' => 'far fa-file-alt', - 'text/html' => 'fas fa-code', - 'application/json' => 'fas fa-code', - // Archives - 'application/gzip' => 'far fa-file-archive', - 'application/zip' => 'far fa-file-archive', - ); - foreach ($icon_classes as $text => $icon) { - if (strpos($mime_type, $text) === 0) { - return $icon; - } - } - return 'fas fa-file'; -} - -function mime_content_type_per_filename($filename) { - $mime_types = array( - 'txt' => 'text/plain', - 'htm' => 'text/html', - 'html' => 'text/html', - 'php' => 'text/html', - 'css' => 'text/css', - 'js' => 'application/javascript', - 'json' => 'application/json', - 'xml' => 'application/xml', - 'swf' => 'application/x-shockwave-flash', - 'flv' => 'video/x-flv', - // images - 'png' => 'image/png', - 'jpe' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'gif' => 'image/gif', - 'bmp' => 'image/bmp', - 'ico' => 'image/vnd.microsoft.icon', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'svg' => 'image/svg+xml', - 'svgz' => 'image/svg+xml', - // archives - 'zip' => 'application/zip', - 'rar' => 'application/x-rar-compressed', - 'exe' => 'application/x-msdownload', - 'msi' => 'application/x-msdownload', - 'cab' => 'application/vnd.ms-cab-compressed', - // audio/video - 'mp3' => 'audio/mpeg', - 'qt' => 'video/quicktime', - 'mov' => 'video/quicktime', - 'mp4' => 'video/mp4', - 'avi' => 'video/avi', - 'mkv' => 'video/mkv', - 'wav' => 'audio/wav', - 'm4v' => 'video/mpeg', - 'webm' => 'video/webm', - 'wmv' => 'video/wmv', - 'mpg' => 'video/mpeg', - 'mpeg' => 'video/mpeg', - 'f4v' => 'video/x-flv', - 'm4v' => 'video/m4v', - 'm4a' => 'video/quicktime', - 'm2p' => 'video/quicktime', - 'rm' => 'video/quicktime', - 'vob' => 'video/quicktime', - 'mkv' => 'video/quicktime', - '3gp' => 'video/quicktime', - 'm3u8' => 'application/x-mpegURL', - // adobe - 'pdf' => 'application/pdf', - 'psd' => 'image/vnd.adobe.photoshop', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - // ms office - 'doc' => 'application/msword', - 'rtf' => 'application/rtf', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - // open office - 'odt' => 'application/vnd.oasis.opendocument.text', - 'ods' => 'application/vnd.oasis.opendocument.spreadsheet' - ); - if (filter_var($filename, FILTER_VALIDATE_URL) === false) { - $ext = pathinfo($filename, PATHINFO_EXTENSION); - } else { - $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION); - } - - if ($ext === 'mp4' || $ext === 'webm') { - $securePlugin = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); - if (!empty($securePlugin)) { - if (method_exists($securePlugin, "useEncoderWatrermarkFromFileName") && $securePlugin->useEncoderWatrermarkFromFileName($filename)) { - return "application/x-mpegURL"; - } - } - } - - if (array_key_exists($ext, $mime_types)) { - return $mime_types[$ext]; - } elseif (function_exists('finfo_open')) { - $finfo = finfo_open(FILEINFO_MIME); - $mimetype = finfo_file($finfo, $filename); - finfo_close($finfo); - return $mimetype; - } else { - return 'application/octet-stream'; - } -} - -function combineFiles($filesArray, $extension = "js") { - global $global, $advancedCustom; - - if ($extension == 'js' && isBot()) { - return getCDN() . 'view/js/empty.js'; - } - - $relativeDir = 'videos/cache/' . $extension . '/'; - $cacheDir = $global['systemRootPath'] . $relativeDir; - $str = ""; - $fileName = ""; - foreach ($filesArray as $value) { - $fileName .= $value . filectime($global['systemRootPath'] . $value) . filemtime($global['systemRootPath'] . $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)); - } - if (!is_dir($cacheDir)) { - make_path($cacheDir); - } - $bytes = _file_put_contents($cacheDir . $md5FileName, $str); - if (empty($bytes)) { - _error_log('combineFiles: error on save strlen=' . strlen($str) . ' ' . $cacheDir . $md5FileName . ' cacheDir=' . $cacheDir); - return false; - } - } - - return getURL($relativeDir . $md5FileName); -} - -function combineFilesHTML($filesArray, $extension = "js", $doNotCombine = false) { - if (empty($doNotCombine)) { - $jsURL = combineFiles($filesArray, $extension); - } - if ($extension == "js") { - if (empty($jsURL)) { - $str = ''; - foreach ($filesArray as $value) { - $jsURL = getURL($value); - $str .= ''; - } - return $str; - } else { - return ''; - } - } else { - if (empty($jsURL)) { - $str = ''; - foreach ($filesArray as $value) { - $jsURL = getURL($value); - $str .= ''; - } - return $str; - } else { - return ''; - } - } -} - -function local_get_contents($path) { - if (function_exists('fopen')) { - $myfile = fopen($path, "r") or die("Unable to open file! [{$path}]"); - $text = fread($myfile, filesize($path)); - fclose($myfile); - return $text; - } -} - -function getSelfUserAgent() { - global $global, $AVideoStreamer_UA; - $agent = $AVideoStreamer_UA . "_"; - $agent .= md5($global['salt']); - return $agent; -} - -function isValidM3U8Link($url, $timeout = 3) { - if (!isValidURL($url)) { - return false; - } - $content = url_get_contents($url, '', $timeout); - if (!empty($content)) { - if (preg_match('/EXTM3U/', $content)) { - return true; - } - } - return false; -} - -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(DEBUG_BACKTRACE_IGNORE_ARGS))); - } - $agent = getSelfUserAgent(); - - if (empty($ctx)) { - $opts = array( - 'http' => array('header' => "User-Agent: {$agent}\r\n"), - "ssl" => array( - "verify_peer" => false, - "verify_peer_name" => false, - "allow_self_signed" => true, - ), - ); - if (!empty($timeout)) { - ini_set('default_socket_timeout', $timeout); - $opts['http'] = array('timeout' => $timeout); - } - $context = stream_context_create($opts); - } else { - $context = $ctx; - } - if (ini_get('allow_url_fopen')) { - if ($debug) { - _error_log("url_get_contents: allow_url_fopen {$url}"); - } - try { - $tmp = @file_get_contents($url, false, $context); - if ($tmp != false) { - $response = remove_utf8_bom($tmp); - if ($debug) { - //_error_log("url_get_contents: SUCCESS file_get_contents($url) {$response}"); - _error_log("url_get_contents: SUCCESS file_get_contents($url)"); - } - return $response; - } - if ($debug) { - _error_log("url_get_contents: ERROR file_get_contents($url) "); - } - } catch (ErrorException $e) { - if ($debug) { - _error_log("url_get_contents: allow_url_fopen ERROR " . $e->getMessage() . " {$url}"); - } - return "url_get_contents: " . $e->getMessage(); - } - } elseif (function_exists('curl_init')) { - if ($debug) { - _error_log("url_get_contents: CURL {$url} "); - } - $ch = curl_init(); - curl_setopt($ch, CURLOPT_USERAGENT, $agent); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - if (!empty($timeout)) { - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout + 10); - } - $output = curl_exec($ch); - curl_close($ch); - if ($debug) { - _error_log("url_get_contents: CURL SUCCESS {$url}"); - } - return remove_utf8_bom($output); - } - if ($debug) { - _error_log("url_get_contents: Nothing yet {$url}"); - } - - // try wget - $filename = getTmpDir("YPTurl_get_contents") . md5($url); - if ($debug) { - _error_log("url_get_contents: try wget $filename {$url}"); - } - if (wget($url, $filename, $debug)) { - if ($debug) { - _error_log("url_get_contents: wget success {$url} "); - } - $result = file_get_contents($filename); - unlink($filename); - if (!empty($result)) { - return remove_utf8_bom($result); - } - } elseif ($debug) { - _error_log("url_get_contents: try wget fail {$url}"); - } - - return false; -} - -function getUpdatesFilesArray() { - global $config, $global; - if (!class_exists('User') || !User::isAdmin()) { - return array(); - } - $files1 = scandir($global['systemRootPath'] . "updatedb"); - $updateFiles = array(); - foreach ($files1 as $value) { - preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); - if (!empty($match)) { - if ($config->currentVersionLowerThen($match[1])) { - $updateFiles[] = array('filename' => $match[0], 'version' => $match[1]); - } - } - } - return $updateFiles; -} - -function thereIsAnyUpdate() { - if (!User::isAdmin()) { - return false; - } - $name = 'thereIsAnyUpdate'; - if (!isset($_SESSION['sessionCache'][$name])) { - $files = getUpdatesFilesArray(); - if (!empty($files)) { - _session_start(); - $_SESSION['sessionCache'][$name] = $files; - } - } - return @$_SESSION['sessionCache'][$name]; -} - -function thereIsAnyRemoteUpdate() { - if (!User::isAdmin()) { - return false; - } - global $config; - - $cacheName = '_thereIsAnyRemoteUpdate'; - $cache = ObjectYPT::getCache($cacheName, 86400); // 24 hours - if (!empty($cache)) { - return $cache; - } - - //$version = _json_decode(url_get_contents("https://tutorials.avideo.com/version")); - $version = _json_decode(url_get_contents("https://tutorialsavideo.b-cdn.net/version", "", 4)); - if (empty($version)) { - return false; - } - $name = 'thereIsAnyRemoteUpdate'; - if (!isset($_SESSION['sessionCache'][$name])) { - if (!empty($version)) { - _session_start(); - if (version_compare($config->getVersion(), $version->version) === -1) { - $_SESSION['sessionCache'][$name] = $version; - } else { - $_SESSION['sessionCache'][$name] = false; - } - } - } - ObjectYPT::setCache($cacheName, $_SESSION['sessionCache'][$name]); - return $_SESSION['sessionCache'][$name]; -} - -function UTF8encode($data) { - global $advancedCustom, $global; - - if (!empty($advancedCustom->utf8Encode)) { - return utf8_encode($data); - } - if (!empty($advancedCustom->utf8Decode)) { - return utf8_decode($data); - } - return $data; -} - -//detect search engine bots -function isBot() { - global $_isBot; - if (empty($_SERVER['HTTP_USER_AGENT'])) { - return true; - } - if (isAVideoEncoder()) { - return false; - } - if (isset($_isBot)) { - return $_isBot; - } - $_isBot = false; - // User lowercase string for comparison. - $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']); - // A list of some common words used only for bots and crawlers. - $bot_identifiers = array( - 'bot', - 'slurp', - 'crawler', - 'spider', - 'curl', - 'facebook', - 'fetch', - 'loader', - 'lighthouse', - 'pingdom', - 'gtmetrix', - 'ptst', - 'dmbrowser', - 'dareboost' - ); - // See if one of the identifiers is in the UA string. - foreach ($bot_identifiers as $identifier) { - if (stripos($user_agent, $identifier) !== false) { - $_isBot = true; - break; - } - } - return $_isBot; -} - -/** - * A function that could get me the last N lines of a log file. - * @param type $filepath - * @param type $lines - * @param type $adaptive - * @return boolean - */ -function tail($filepath, $lines = 1, $adaptive = true, $returnArray = false) { - if (!function_exists('mb_strlen')) { - $msg = "AVideoLog::ERROR you need to install the mb_strlen function to make it work, please the command 'sudo apt install php-mbstring'"; - if ($returnArray) { - return array(array($msg)); - } else { - return $msg; - } - } - // Open file - $f = @fopen($filepath, "rb"); - if ($f === false) { - return false; - } - - // Sets buffer size, according to the number of lines to retrieve. - // This gives a performance boost when reading a few lines from the file. - if (!$adaptive) { - $buffer = 4096; - } else { - $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096)); - } - - // Jump to last character - fseek($f, -1, SEEK_END); - // Read it and adjust line number if necessary - // (Otherwise the result would be wrong if file doesn't end with a blank line) - if (fread($f, 1) != "\n") { - $lines -= 1; - } - - // Start reading - $output = ''; - $chunk = ''; - // While we would like more - while (ftell($f) > 0 && $lines >= 0) { - // Figure out how far back we should jump - $seek = min(ftell($f), $buffer); - // Do the jump (backwards, relative to where we are) - fseek($f, -$seek, SEEK_CUR); - // Read a chunk and prepend it to our output - $output = ($chunk = fread($f, $seek)) . $output; - // Jump back to where we started reading - fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR); - // Decrease our line counter - $lines -= substr_count($chunk, "\n"); - } - // While we have too many lines - // (Because of buffer size we might have read too many) - while ($lines++ < 0) { - // Find first newline and remove all text before that - $output = substr($output, strpos($output, "\n") + 1); - } - // Close file and return - fclose($f); - $output = trim($output); - if ($returnArray) { - $array = explode("\n", $output); - $newArray = array(); - foreach ($array as $value) { - $newArray[] = array($value); - } - return $newArray; - } else { - return $output; - } -} - -function encryptPassword($password, $noSalt = false) { - global $advancedCustom, $global, $advancedCustomUser; - if (!empty($advancedCustomUser->encryptPasswordsWithSalt) && !empty($global['salt']) && empty($noSalt)) { - $password .= $global['salt']; - } - - return md5(hash("whirlpool", sha1($password))); -} - -function encryptPasswordVerify($password, $hash, $encodedPass = false) { - global $advancedCustom, $global; - if (!$encodedPass || $encodedPass === 'false') { - //_error_log("encryptPasswordVerify: encrypt"); - $passwordSalted = encryptPassword($password); - // in case you enable the salt later - $passwordUnSalted = encryptPassword($password, true); - } else { - //_error_log("encryptPasswordVerify: do not encrypt"); - $passwordSalted = $password; - // in case you enable the salt later - $passwordUnSalted = $password; - } - //_error_log("passwordSalted = $passwordSalted, hash=$hash, passwordUnSalted=$passwordUnSalted"); - return $passwordSalted === $hash || $passwordUnSalted === $hash || $password === $hash; -} - -function encryptPasswordV2($uniqueSalt, $password, $noSalt = false) { - global $advancedCustom, $global, $advancedCustomUser; - if (!empty($advancedCustomUser->encryptPasswordsWithSalt) && !empty($global['salt']) && empty($noSalt)) { - $password .= $global['salt']; - } - $password .= md5($uniqueSalt); - return md5(hash("whirlpool", sha1($password))); -} - -function encryptPasswordVerifyV2($uniqueSalt, $password, $hash, $encodedPass = false) { - global $advancedCustom, $global; - if (!$encodedPass || $encodedPass === 'false') { - //_error_log("encryptPasswordVerify: encrypt"); - $passwordSalted = encryptPasswordV2($uniqueSalt, $password); - // in case you enable the salt later - $passwordUnSalted = encryptPasswordV2($uniqueSalt, $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 isChannelPage() { - return strpos($_SERVER["SCRIPT_NAME"], 'view/channel.php') !== false; -} - -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, $global; - $md5 = md5($global['salt']); - if (preg_match("/{$AVideoStreamer_UA}_{$md5}/", $_SERVER["HTTP_USER_AGENT"])) { - return true; - } - return false; -} - -function isAVideoUserAgent($user_agent = "") { - if (empty($user_agent)) { - $user_agent = @$_SERVER['HTTP_USER_AGENT']; - } - if (empty($user_agent)) { - return false; - } - global $AVideoMobileAPP_UA, $AVideoEncoder_UA, $AVideoStreamer_UA, $AVideoStorage_UA, $global; - - // Lavf = ffmpeg - $agents = array($AVideoMobileAPP_UA, $AVideoEncoder_UA, $AVideoStreamer_UA, $AVideoStorage_UA, 'Lavf'); - - foreach ($agents as $value) { - if (preg_match("/{$value}/", $_SERVER["HTTP_USER_AGENT"])) { - 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 verify($url) { - ini_set('default_socket_timeout', 5); - $cacheFile = sys_get_temp_dir() . "/" . md5($url) . "_verify.log"; - $lifetime = 86400; //24 hours - error_log("Verification Start {$url}"); - $verifyURL = "https://search.avideo.com/verify.php?url=" . urlencode($url); - if (!file_exists($cacheFile) || (time() > (filemtime($cacheFile) + $lifetime))) { - error_log("Verification Creating the Cache {$url}"); - $result = url_get_contents($verifyURL, '', 5); - file_put_contents($cacheFile, $result); - } else { - error_log("Verification GetFrom Cache {$url}"); - $result = file_get_contents($cacheFile); - } - error_log("Verification Response ($verifyURL): {$result}"); - return json_decode($result); -} - -function isVerified($url) { - $resultV = verify($url); - if (!empty($resultV) && !$resultV->verified) { - error_log("Error on Login not verified"); - return false; - } - return true; -} - -function siteMap() { - _error_log("siteMap: start"); - ini_set('memory_limit', '-1'); - ini_set('max_execution_time', 0); - @session_write_close(); - global $global, $advancedCustom; - $global['disableVideoTags'] = 1; - $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"; - TimeLogStart("siteMap getAllUsersThatHasVideos"); - $users = User::getAllUsersThatHasVideos(true); - _error_log("siteMap: getAllUsers " . count($users)); - foreach ($users as $value) { - $xml .= ' - - ' . User::getChannelLink($value['id']) . ' - ' . $date . ' - daily - 0.90 - - '; - } - TimeLogEnd("siteMap getAllUsersThatHasVideos", __LINE__, 0.5); - TimeLogStart("siteMap getAllCategories"); - $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 - - '; - } - TimeLogEnd("siteMap getAllCategories", __LINE__, 0.5); - TimeLogStart("siteMap getAllVideos"); - $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']; - - TimeLogStart("siteMap Video::getPoster $videos_id"); - $img = Video::getPoster($videos_id); - TimeLogEnd("siteMap Video::getPoster $videos_id", __LINE__, 0.5); - - $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; - } - - TimeLogStart("siteMap Video::getLink $videos_id"); - $loc = Video::getLink($video['id'], $video['clean_title']); - TimeLogEnd("siteMap Video::getLink $videos_id", __LINE__, 0.5); - $title = strip_tags($video['title']); - $description = _substr(strip_tags(br2nl($description)), 0, 2048); - TimeLogStart("siteMap Video::getLinkToVideo $videos_id"); - $player_loc = Video::getLinkToVideo($video['id'], $video['clean_title'], true); - TimeLogEnd("siteMap Video::getLinkToVideo $videos_id", __LINE__, 0.5); - TimeLogStart("siteMap Video::isPublic $videos_id"); - $requires_subscription = Video::isPublic($video['id']) ? "no" : "yes"; - TimeLogEnd("siteMap Video::isPublic $videos_id", __LINE__, 0.5); - TimeLogStart("siteMap Video::getChannelLink $videos_id"); - $uploader_info = User::getChannelLink($video['users_id']); - TimeLogEnd("siteMap Video::getChannelLink $videos_id", __LINE__, 0.5); - TimeLogStart("siteMap Video::getNameIdentificationById $videos_id"); - $uploader = htmlentities(User::getNameIdentificationById($video['users_id'])); - TimeLogEnd("siteMap Video::getNameIdentificationById $videos_id", __LINE__, 0.5); - - $xml .= ' - - ' . $loc . ' - - ' . $img . ' - - - - ' . $duration . ' - ' . $video['views_count'] . ' - ' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00 - yes - ' . $requires_subscription . ' - ' . $uploader . ' - no - - - '; - } - TimeLogEnd("siteMap getAllVideos", __LINE__, 0.5); - $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; - cleanUpAccessControlHeader(); - 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 cleanUpAccessControlHeader() { - if (!headers_sent()) { - foreach (headers_list() as $header) { - if (preg_match('/Access-Control-Allow-Origin/i', $header)) { - $parts = explode(':', $header); - header_remove($parts[0]); - } - } - } -} - -function rrmdir($dir) { - //if(preg_match('/cache/i', $dir)){_error_log("rrmdir($dir) ". json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));exit;} - - $dir = str_replace(array('//', '\\\\'), DIRECTORY_SEPARATOR, $dir); - //_error_log('rrmdir: ' . $dir); - if (empty($dir)) { - _error_log('rrmdir: the dir was empty'); - return false; - } - global $global; - $dir = fixPath($dir); - $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; - } - rrmdirCommandLine($dir); - if (is_dir($dir)) { - //_error_log('rrmdir: The Directory was not deleted, trying again ' . $dir); - $objects = scandir($dir); - //_error_log('rrmdir: scandir ' . $dir . ' '. json_encode($objects)); - foreach ($objects as $object) { - if ($object != "." && $object != "..") { - if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) { - rrmdir($dir . DIRECTORY_SEPARATOR . $object); - } else { - unlink($dir . DIRECTORY_SEPARATOR . $object); - } - } - } - if (preg_match('/(\/|^)videos(\/cache)?\/?$/i', $dir)) { - _error_log('rrmdir: do not delete videos or cache folder ' . $dir); - // do not delete videos or cache folder - return false; - } - if (rmdir($dir)) { - return true; - } else { - _error_log('rrmdir: could not delete folder ' . $dir); - return false; - } - } else { - //_error_log('rrmdir: The Directory does not exists '.$dir); - return true; - } -} - -function rrmdirCommandLine($dir, $async = false) { - if (is_dir($dir)) { - if (isWindows()) { - $command = ('rd /s /q ' . $dir); - } else { - $command = ('rm -fR ' . $dir); - } - - if ($async) { - return execAsync($command); - } else { - return exec($command); - } - } -} - -/** - * 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']; - - $img = Video::getPoster($videos_id); - - $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']; - $img = Video::getPoster($videos_id); - - $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; - return $name; -} - -function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) { - global $global; - if (!empty($global['noDebug']) || empty($global['start'][$name])) { - return false; - } - if (!empty($global['TimeLogLimit'])) { - $TimeLogLimit = $global['TimeLogLimit']; - } - $time = microtime(); - $time = explode(' ', $time); - $time = $time[1] + $time[0]; - $finish = $time; - $total_time = round(($finish - $global['start'][$name]), 4); - if (empty($global['noDebugSlowProcess']) && $total_time > $TimeLogLimit) { - _error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}"); - } - TimeLogStart($name); -} - -class AVideoLog { - - public static $DEBUG = 0; - public static $WARNING = 1; - public static $ERROR = 2; - public static $SECURITY = 3; - public static $SOCKET = 4; - -} - -function _error_log_debug($message, $show_args = false) { - $array = debug_backtrace(); - $message .= PHP_EOL; - foreach ($array as $value) { - $message .= "function: {$value['function']} Line: {{$value['line']}} File: {{$value['file']}}" . PHP_EOL; - if ($show_args) { - $message .= print_r($value['args'], true) . PHP_EOL; - } - } - _error_log(PHP_EOL . '***' . PHP_EOL . $message . '***'); -} - -function _error_log($message, $type = 0, $doNotRepeat = false) { - if (empty($doNotRepeat)) { - // do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error - $doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']); - } - if ($doNotRepeat) { - return false; - } - global $global; - if (!empty($global['noDebug']) && $type == 0) { - return false; - } - if (!is_string($message)) { - $message = json_encode($message); - } - $prefix = "AVideoLog::"; - switch ($type) { - case AVideoLog::$DEBUG: - $prefix .= "DEBUG: "; - break; - case AVideoLog::$WARNING: - $prefix .= "WARNING: "; - break; - case AVideoLog::$ERROR: - $prefix .= "ERROR: "; - break; - case AVideoLog::$SECURITY: - $prefix .= "SECURITY: "; - break; - case AVideoLog::$SOCKET: - $prefix .= "SOCKET: "; - break; - } - error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}"); -} - -function postVariables($url, $array, $httpcodeOnly = true, $timeout = 10) { - if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { - return false; - } - $array = object_to_array($array); - $ch = curl_init($url); - if ($httpcodeOnly) { - @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers - @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body - } else { - curl_setopt($curl, CURLOPT_USERAGENT, getSelfUserAgent()); - } - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout + 1); //The maximum number of seconds to allow cURL functions to execute. - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $array); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - - // execute! - $response = curl_exec($ch); - if ($httpcodeOnly) { - $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - // close the connection, release resources used - curl_close($ch); - if ($httpcode == 200) { - return true; - } - return $httpcode; - } else { - curl_close($ch); - return $response; - } -} - -function _session_start(array $options = array()) { - try { - if (!empty($_GET['PHPSESSID'])) { - if ($_GET['PHPSESSID'] !== session_id()) { - if (session_status() != PHP_SESSION_NONE) { - @session_write_close(); - } - session_id($_GET['PHPSESSID']); - //_error_log("captcha: session_id changed to " . $_GET['PHPSESSID']); - } - unset($_GET['PHPSESSID']); - return @session_start($options); - } else 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()) { - //_error_log('MySQL Connect '. json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $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()) { - //_error_log('MySQL Closed '. json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $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 (!empty($global['mysqli']) && 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; - $lockFile = getVideosDir() . '.clearCache.lock'; - if (file_exists($lockFile) && filectime($lockFile) > strtotime('-5 minutes')) { - _error_log('clearCache is in progress ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - return false; - } - $start = microtime(true); - _error_log('clearCache starts '); - file_put_contents($lockFile, time()); - - $dir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; - $tmpDir = ObjectYPT::getCacheDir('firstPage'); - $parts = explode('firstpage', $tmpDir); - - if ($firstPageOnly || !empty($_REQUEST['FirstPage'])) { - $tmpDir = $parts[0] . 'firstpage' . DIRECTORY_SEPARATOR; - //var_dump($tmpDir);exit; - $dir .= "firstPage" . DIRECTORY_SEPARATOR; - } else { - $tmpDir = $parts[0]; - } - - //_error_log('clearCache 1: '.$dir); - rrmdir($dir); - rrmdir($tmpDir); - ObjectYPT::deleteCache("getEncoderURL"); - unlink($lockFile); - $end = microtime(true) - $start; - _error_log("clearCache end in {$end} seconds"); - return true; -} - -function clearAllUsersSessionCache() { - sendSocketMessageToAll(time(), 'socketClearSessionCache'); -} - -function clearFirstPageCache() { - return clearCache(true); -} - -function getUsageFromFilename($filename, $dir = "") { - global $global; - - if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage - return 0; - } - - if (empty($dir)) { - $paths = Video::getPaths($filename); - $dir = $paths['path']; - } - $dir = addLastSlash($dir); - $totalSize = 0; - _error_log("getUsageFromFilename: start {$dir}{$filename} " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - //$files = glob("{$dir}{$filename}*"); - $paths = Video::getPaths($filename); - - if (is_dir($paths['path'])) { - $files = array($paths['path']); - } else { - $files = globVideosDir($filename); - } - //var_dump($paths, $files, $filename);exit; - session_write_close(); - $filesProcessed = array(); - if (empty($files)) { - _error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - make_path($dir); - file_put_contents("{$dir}{$filename}.notfound", time()); - $totalSize = 10; - } else { - foreach ($files as $f) { - if (strpos($f, '.size.lock') !== false) { - continue; - } - if (is_dir($f)) { - $dirSize = getDirSize($f, true); - _error_log("getUsageFromFilename: is Dir dirSize={$dirSize} " . humanFileSize($dirSize) . " {$f}"); - $totalSize += $dirSize; - $minDirSize = 4000000; - $isEnabled = AVideoPlugin::isEnabledByName('YPTStorage'); - $isEnabledCDN = AVideoPlugin::getObjectDataIfEnabled('CDN'); - $isEnabledS3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); - if (!empty($isEnabledCDN) && $isEnabledCDN->enable_storage) { - $v = Video::getVideoFromFileName($filename); - if (!empty($v)) { - $size = CDNStorage::getRemoteDirectorySize($v['id']); - _error_log("getUsageFromFilename: CDNStorage found $size " . humanFileSize($size)); - $totalSize += $size; - } - } - if ($dirSize < $minDirSize && $isEnabled) { - // probably the HLS file is hosted on the YPTStorage - $info = YPTStorage::getFileInfo($filename); - if (!empty($info->size)) { - _error_log("getUsageFromFilename: found info on the YPTStorage " . print_r($info, true)); - $totalSize += $info->size; - } else { - _error_log("getUsageFromFilename: there is no info on the YPTStorage " . print_r($info, true)); - } - } else if ($dirSize < $minDirSize && $isEnabledS3) { - // probably the HLS file is hosted on the S3 - $size = $isEnabledS3->getFilesize($filename); - if (!empty($size)) { - _error_log("getUsageFromFilename: found info on the AWS_S3 {$filename} {$size}"); - $totalSize += $size; - } else { - _error_log("getUsageFromFilename: there is no info on the AWS_S3 {$filename} {$size}"); - } - } else { - if (!($dirSize < $minDirSize)) { - _error_log("getUsageFromFilename: does not have the size to process $dirSize < $minDirSize"); - } - if (!$isEnabled) { - _error_log("getUsageFromFilename: YPTStorage is disabled"); - } - if (!$isEnabledCDN) { - _error_log("getUsageFromFilename: CDN Storage is disabled"); - } - if (!$isEnabledS3) { - _error_log("getUsageFromFilename: S3 Storage is disabled"); - } - } - } 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, $forceNew = false) { - global $_getDirSize; - - if (!isset($_getDirSize)) { - $_getDirSize = array(); - } - if (empty($forceNew) && isset($_getDirSize[$dir])) { - return $_getDirSize[$dir]; - } - - _error_log("getDirSize: start {$dir}"); - - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - $return = foldersize($dir); - $_getDirSize[$dir] = $return; - return $return; - } 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; - $_getDirSize[$dir] = $return; - return $return; - } 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]); - $_getDirSize[$dir] = $return; - return $return; - } - - _error_log("getDirSize: ERROR on pregmatch {$output[0]}"); - $return = 0; - $_getDirSize[$dir] = $return; - return $return; - } - } -} - -function foldersize($path) { - $total_size = 0; - $files = scandir($path); - $cleanPath = rtrim($path, '/') . '/'; - - foreach ($files as $t) { - if ($t <> "." && $t <> "..") { - $currentFile = $cleanPath . $t; - if (is_dir($currentFile)) { - $size = foldersize($currentFile); - $total_size += $size; - } else { - $size = filesize($currentFile); - $total_size += $size; - } - } - } - - return $total_size; -} - -function getDiskUsage() { - global $global; - $dir = getVideosDir() . ""; - $obj = new stdClass(); - $obj->disk_free_space = disk_free_space($dir); - $obj->disk_total_space = disk_total_space($dir); - $obj->videos_dir = getDirSize($dir); - $obj->disk_used = $obj->disk_total_space - $obj->disk_free_space; - $obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir; - $obj->disk_free_space_human = humanFileSize($obj->disk_free_space); - $obj->disk_total_space_human = humanFileSize($obj->disk_total_space); - $obj->videos_dir_human = humanFileSize($obj->videos_dir); - $obj->disk_used_human = humanFileSize($obj->disk_used); - $obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other); - // percentage of disk used - $obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100); - $obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100); - $obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100); - - return $obj; -} - -function unsetSearch() { - unset($_GET['searchPhrase'], $_POST['searchPhrase'], $_GET['search'], $_GET['q']); -} - -function encrypt_decrypt($string, $action) { - global $global; - $output = false; - - $encrypt_method = "AES-256-CBC"; - $secret_key = 'This is my secret key'; - $secret_iv = $global['systemRootPath']; - while (strlen($secret_iv) < 16) { - $secret_iv .= $global['systemRootPath']; - } - if (empty($secret_iv)) { - $secret_iv = '1234567890abcdef'; - } - // 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; - $obj->timezone = date_default_timezone_get(); - - 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; - } - $old_timezone = date_default_timezone_get(); - date_default_timezone_set($obj->timezone); - $time = time(); - date_default_timezone_set($old_timezone); - if (!($time >= $obj->time && $time <= $obj->timeout)) { - _error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout"); - return false; - } - return true; -} - -class YPTvideoObject { - - public $id; - public $title; - public $description; - public $thumbnails; - public $channelTitle; - public $videoLink; - - public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) { - $this->id = $id; - $this->title = $title; - $this->description = $description; - $this->thumbnails = $thumbnails; - $this->channelTitle = $channelTitle; - $this->videoLink = $videoLink; - } - -} - -function isToShowDuration($type) { - $notShowTo = array('pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks'); - if (in_array($type, $notShowTo)) { - return false; - } else { - return true; - } -} - -function _dieAndLogObject($obj, $prefix = "") { - $objString = json_encode($obj); - _error_log($prefix . $objString); - die($objString); -} - -function isAVideoPlayer() { - if (isVideo() || isSerie()) { - return true; - } - return false; -} - -function isFirstPage() { - global $isFirstPage, $global; - return !empty($isFirstPage) || getSelfURI() === "{$global['webSiteRootURL']}view/"; -} - -function isVideo() { - global $isModeYouTube, $global; - if (!empty($global['doNotLoadPlayer'])) { - return false; - } - return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive(); -} - -function isVideoTypeEmbed() { - global $isVideoTypeEmbed; - - if (isVideo() && !empty($isVideoTypeEmbed) && $videos_id = getVideos_id()) { - return $videos_id; - } - - return false; -} - -function isAudio() { - global $isAudio; - return !empty($isAudio); -} - -function isSerie() { - return isPlayList(); -} - -function isPlayList() { - global $isPlayList, $isSerie; - return !empty($isSerie) || !empty($isPlayList); -} - -function isChannel() { - global $isChannel; - if (!empty($isChannel) && !isVideo()) { - $user_id = 0; - if (empty($_GET['channelName'])) { - if (User::isLogged()) { - $user_id = User::getId(); - } else { - return false; - } - } else { - $_GET['channelName'] = xss_esc($_GET['channelName']); - $user = User::getChannelOwner($_GET['channelName']); - if (!empty($user)) { - $user_id = $user['id']; - } else { - $user_id = $_GET['channelName']; - } - } - return $user_id; - } - return false; -} - -function isEmbed() { - global $isEmbed, $global; - if (!empty($global['doNotLoadPlayer'])) { - return false; - } - return !empty($isEmbed); -} - -function isWebRTC() { - global $isWebRTC, $global; - if (!empty($global['doNotLoadPlayer'])) { - return false; - } - return !empty($isWebRTC); -} - -function isLive() { - global $isLive, $global; - if (!empty($global['doNotLoadPlayer'])) { - return false; - } - if (class_exists('LiveTransmition') && class_exists('Live')) { - $livet = LiveTransmition::getFromRequest(); - if (!empty($livet)) { - setLiveKey($livet['key'], Live::getLiveServersIdRequest(), @$_REQUEST['live_index']); - $isLive = 1; - } - } - 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 (isWebRTC()) { - return false; - } - if (isLive()) { - $obj = AVideoPlugin::getObjectData('Live'); - if (empty($obj->disableDVR)) { - return true; - } - } elseif (isAVideoPlayer()) { - return true; - } - return false; -} - -function isHLS() { - global $video, $global; - if (isLive()) { - return true; - } elseif (!empty($video) && $video['type'] == 'video' && file_exists(Video::getPathToFile("{$video['filename']}/index.m3u8"))) { - return true; - } - return false; -} - -function getRedirectUri() { - if (!empty($_GET['redirectUri'])) { - return $_GET['redirectUri']; - } - if (!empty($_SESSION['redirectUri'])) { - return $_SESSION['redirectUri']; - } - if (!empty($_SERVER["HTTP_REFERER"])) { - return $_SERVER["HTTP_REFERER"]; - } - return getRequestURI(); -} - -function setRedirectUri($redirectUri) { - _session_start(); - $_SESSION['redirectUri'] = $redirectUri; -} - -function redirectIfRedirectUriIsSet() { - $redirectUri = false; - if (!empty($_GET['redirectUri'])) { - if (isSameDomainAsMyAVideo($_GET['redirectUri'])) { - $redirectUri = $_GET['redirectUri']; - } - } - if (!empty($_SESSION['redirectUri'])) { - if (isSameDomainAsMyAVideo($_SESSION['redirectUri'])) { - $redirectUri = $_SESSION['redirectUri']; - } - _session_start(); - unset($_SESSION['redirectUri']); - } - - if (!empty($redirectUri)) { - header("Location: {$_SESSION['redirectUri']}"); - exit; - } -} - -function getRedirectToVideo($videos_id) { - $redirectUri = getRedirectUri(); - $isEmbed = 0; - if (stripos($redirectUri, "embed") !== false) { - $isEmbed = 1; - } - $video = Video::getVideoLight($videos_id); - if (empty($video)) { - return false; - } - return Video::getLink($videos_id, $video['clean_title'], $isEmbed); -} - -function getRequestURI() { - if (empty($_SERVER['REQUEST_URI'])) { - return ""; - } - return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; -} - -function getSelfURI() { - if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) { - return ""; - } - $queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']); - $phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']); - $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError"; - $url = rtrim($url, '?'); - return $url; -} - -function isSameVideoAsSelfURI($url) { - return URLsAreSameVideo($url, getSelfURI()); -} - -function URLsAreSameVideo($url1, $url2) { - $videos_id1 = getVideoIDFromURL($url1); - $videos_id2 = getVideoIDFromURL($url2); - if (empty($videos_id1) || empty($videos_id2)) { - return false; - } - return $videos_id1 === $videos_id2; -} - -function getVideos_id() { - global $_getVideos_id; - $videos_id = false; - if (isset($_getVideos_id) && is_int($_getVideos_id)) { - return $_getVideos_id; - } - if (isVideo()) { - $videos_id = getVideoIDFromURL(getSelfURI()); - if (empty($videos_id) && !empty($_REQUEST['videoName'])) { - $video = Video::getVideoFromCleanTitle($_REQUEST['videoName']); - if (!empty($video)) { - $videos_id = $video['id']; - } - } - setVideos_id($videos_id); - } - if (empty($videos_id) && !empty($_REQUEST['playlists_id'])) { - AVideoPlugin::loadPlugin('PlayLists'); - $video = PlayLists::isPlayListASerie($_REQUEST['playlists_id']); - if (!empty($video)) { - $videos_id = $video['id']; - } - } - - if (empty($videos_id) && !empty($_REQUEST['v'])) { - $videos_id = $_REQUEST['v']; - } - - $videos_id = videosHashToID($videos_id); - - return $videos_id; -} - -function setVideos_id($videos_id) { - global $_getVideos_id; - $_getVideos_id = $videos_id; -} - -function getPlaylists_id() { - global $_isPlayList; - if (!isset($_isPlayList)) { - $_isPlayList = false; - if (isPlayList()) { - $_isPlayList = intval(@$_GET['playlists_id']); - if (empty($_isPlayList)) { - $videos_id = getVideos_id(); - if (empty($videos_id)) { - $_isPlayList = false; - } else { - $v = Video::getVideoLight($videos_id); - if (empty($v) || empty($v['serie_playlists_id'])) { - $_isPlayList = false; - } else { - $_isPlayList = $v['serie_playlists_id']; - } - } - } - } - } - return $_isPlayList; -} - -function isVideoOrAudioNotEmbed() { - if (!isVideo()) { - return false; - } - $videos_id = getVideos_id(); - if (empty($videos_id)) { - return false; - } - $v = Video::getVideoLight($videos_id); - if (empty($v)) { - return false; - } - $types = array('audio', 'video'); - if (in_array($v['type'], $types)) { - return true; - } - return false; -} - -function getVideoIDFromURL($url) { - if (preg_match("/v=([0-9]+)/", $url, $matches)) { - return intval($matches[1]); - } - if (preg_match('/\/(video|videoEmbed|v|vEmbed|article|articleEmbed)\/([0-9]+)/', $url, $matches)) { - if (is_numeric($matches[1])) { - return intval($matches[1]); - } else if (is_numeric($matches[2])) { - return intval($matches[2]); - } - } - 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']; - } - } - } - if (preg_match("/v=(\.[0-9a-zA-Z_-]+)/", $url, $matches)) { - return hashToID($matches[1]); - } - if (preg_match('/\/(video|videoEmbed|v|vEmbed|article|articleEmbed)\/(\.[0-9a-zA-Z_-]+)/', $url, $matches)) { - return hashToID($matches[2]); - } - return false; -} - -function getBackURL() { - global $global; - $backURL = getRedirectUri(); - if (empty($backURL)) { - $backURL = getRequestURI(); - } - if (isSameVideoAsSelfURI($backURL)) { - $backURL = getHomeURL(); - } - return $backURL; -} - -function getHomeURL() { - global $global, $advancedCustomUser, $advancedCustom; - if (isValidURL($advancedCustomUser->afterLoginGoToURL)) { - return $advancedCustomUser->afterLoginGoToURL; - } elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) { - return $advancedCustom->logoMenuBarURL; - } - return $global['webSiteRootURL']; -} - -function isValidURL($url) { - //var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL)); - if (empty($url) || !is_string($url)) { - return false; - } - if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) { - return true; - } - return false; -} - -function hasLastSlash($word) { - return substr($word, -1) === '/'; -} - -function addLastSlash($word) { - return $word . (hasLastSlash($word) ? "" : "/"); -} - -function URLHasLastSlash() { - return hasLastSlash($_SERVER["REQUEST_URI"]); -} - -function ucname($str) { - $str = ucwords(strtolower($str)); - - foreach (array('\'', '-') as $delim) { - if (strpos($str, $delim) !== false) { - $str = implode($delim, array_map('ucfirst', explode($delim, $str))); - } - } - return $str; -} - -function sanitize_input($input) { - return htmlentities(strip_tags($input)); -} - -function sanitize_array_item(&$item, $key) { - $item = sanitize_input($item); -} - -function getSEOComplement($parameters = array()) { - global $config; - - $allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null; - $addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true; - $addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true; - - $parts = array(); - - if (!empty($_GET['error'])) { - array_push($parts, __("Error")); - } - - if ($addCategory && !empty($_GET['catName'])) { - array_push($parts, $_GET['catName']); - } - - if (!empty($_GET['channelName'])) { - array_push($parts, $_GET['channelName']); - } - - if (!empty($_GET['type'])) { - $type = $_GET['type']; - if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) { - array_push($parts, __(ucname($type))); - } - } - - if (!empty($_GET['showOnly'])) { - array_push($parts, $_GET['showOnly']); - } - - if (!empty($_GET['page'])) { - $page = intval($_GET['page']); - if ($page > 1) { - array_push($parts, sprintf(__("Page %d"), $page)); - } - } - - // Cleaning all entries in the $parts array - array_walk($parts, 'sanitize_array_item'); - - $txt = implode($config->getPageTitleSeparator(), $parts); - $txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt; - - return $txt; -} - -function getCurrentPage() { - if (!empty($_REQUEST['current'])) { - return intval($_REQUEST['current']); - } elseif (!empty($_POST['current'])) { - return intval($_POST['current']); - } elseif (!empty($_GET['current'])) { - return intval($_GET['current']); - } elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid - $start = intval($_GET['start']); - $length = intval($_GET['length']); - if (!empty($start) && !empty($length)) { - return floor($start / $length) + 1; - } - } - return 1; -} - -function getRowCount($default = 1000) { - global $global; - if (!empty($_REQUEST['rowCount'])) { - $defaultN = intval($_REQUEST['rowCount']); - } elseif (!empty($_POST['rowCount'])) { - $defaultN = intval($_POST['rowCount']); - } elseif (!empty($_GET['rowCount'])) { - $defaultN = intval($_GET['rowCount']); - } elseif (!empty($_REQUEST['length'])) { - $defaultN = intval($_REQUEST['length']); - } elseif (!empty($_POST['length'])) { - $defaultN = intval($_POST['length']); - } elseif (!empty($_GET['length'])) { - $defaultN = intval($_GET['length']); - } elseif (!empty($global['rowCount'])) { - $defaultN = intval($global['rowCount']); - } - return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default; -} - -function getSearchVar() { - if (!empty($_REQUEST['search'])) { - return $_REQUEST['search']; - } elseif (!empty($_REQUEST['q'])) { - return $_REQUEST['q']; - } - if (!empty($_REQUEST['searchPhrase'])) { - return $_REQUEST['searchPhrase']; - } elseif (!empty($_REQUEST['search']['value'])) { - return $_REQUEST['search']['value']; - } - return ""; -} - -$cleanSearchHistory = ""; - -function cleanSearchVar() { - global $cleanSearchHistory; - $search = getSearchVar(); - if (!empty($search)) { - $cleanSearchHistory = $search; - } - $searchIdex = array('q', 'searchPhrase', 'search'); - foreach ($searchIdex as $value) { - unset($_REQUEST[$value], $_POST[$value], $_GET[$value]); - } -} - -function reloadSearchVar() { - global $cleanSearchHistory; - $_REQUEST['search'] = $cleanSearchHistory; - if (empty($_GET['search'])) { - $_GET['search'] = $cleanSearchHistory; - } - if (empty($_POST['search'])) { - $_POST['search'] = $cleanSearchHistory; - } -} - -function wget($url, $filename, $debug = false) { - if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) { - return false; - } - if (wgetIsLocked($url)) { - if ($debug) { - _error_log("wget: ERROR the url is already downloading $url, $filename"); - } - return false; - } - wgetLock($url); - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - $content = @file_get_contents($url); - if (!empty($content) && file_put_contents($filename, $content) > 100) { - wgetRemoveLock($url); - return true; - } - wgetRemoveLock($url); - return false; - } - $cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate"; - if ($debug) { - _error_log("wget Start ({$cmd}) "); - } - //echo $cmd; - exec($cmd); - wgetRemoveLock($url); - if (!file_exists($filename)) { - _error_log("wget: ERROR the url does not download $url, $filename"); - return false; - } - if ($_SERVER['SCRIPT_NAME'] !== '/plugin/Live/m3u8.php' && empty(filesize($filename))) { - _error_log("wget: ERROR the url download but is empty $url, $filename"); - return true; - } - return false; -} - -/** - * Copy remote file over HTTP one small chunk at a time. - * - * @param $infile The full URL to the remote file - * @param $outfile The path where to save the file - */ -function copyfile_chunked($infile, $outfile) { - $chunksize = 10 * (1024 * 1024); // 10 Megs - - /** - * parse_url breaks a part a URL into it's parts, i.e. host, path, - * query string, etc. - */ - $parts = parse_url($infile); - $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5); - $o_handle = fopen($outfile, 'wb'); - - if ($i_handle == false || $o_handle == false) { - return false; - } - - if (!empty($parts['query'])) { - $parts['path'] .= '?' . $parts['query']; - } - - /** - * Send the request to the server for the file - */ - $request = "GET {$parts['path']} HTTP/1.1\r\n"; - $request .= "Host: {$parts['host']}\r\n"; - $request .= "User-Agent: Mozilla/5.0\r\n"; - $request .= "Keep-Alive: 115\r\n"; - $request .= "Connection: keep-alive\r\n\r\n"; - fwrite($i_handle, $request); - - /** - * Now read the headers from the remote server. We'll need - * to get the content length. - */ - $headers = array(); - while (!feof($i_handle)) { - $line = fgets($i_handle); - if ($line == "\r\n") - break; - $headers[] = $line; - } - - /** - * Look for the Content-Length header, and get the size - * of the remote file. - */ - $length = 0; - foreach ($headers as $header) { - if (stripos($header, 'Content-Length:') === 0) { - $length = (int) str_replace('Content-Length: ', '', $header); - break; - } - } - - /** - * Start reading in the remote file, and writing it to the - * local file one chunk at a time. - */ - $cnt = 0; - while (!feof($i_handle)) { - $buf = ''; - $buf = fread($i_handle, $chunksize); - $bytes = fwrite($o_handle, $buf); - if ($bytes == false) { - return false; - } - $cnt += $bytes; - - /** - * We're done reading when we've reached the conent length - */ - if ($cnt >= $length) - break; - } - - fclose($i_handle); - fclose($o_handle); - return $cnt; -} - -function wgetLockFile($url) { - return getTmpDir("YPTWget") . md5($url) . ".lock"; -} - -function wgetLock($url) { - $file = wgetLockFile($url); - return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX); -} - -function wgetRemoveLock($url) { - $filename = wgetLockFile($url); - if (!file_exists($filename)) { - return false; - } - return unlink($filename); -} - -function getLockFile($name) { - return getTmpDir("YPTLockFile") . md5($name) . ".lock"; -} - -function setLock($name) { - $file = getLockFile($name); - return file_put_contents($file, time()); -} - -function isLock($name, $timeout = 60) { - $file = getLockFile($name); - if (file_exists($file)) { - $time = intval(file_get_contents($file)); - if ($time + $timeout < time()) { - return false; - } - } -} - -function removeLock($name) { - $filename = getLockFile($name); - if (!file_exists($filename)) { - return false; - } - return unlink($filename); -} - -function wgetIsLocked($url) { - $filename = wgetLockFile($url); - if (!file_exists($filename)) { - return false; - } - $time = intval(file_get_contents($filename)); - if (time() - $time > 36000) { // more then 10 hours - unlink($filename); - return false; - } - return true; -} - -// due the some OS gives a fake is_writable response -function isWritable($dir) { - $dir = rtrim($dir, '/') . '/'; - $file = $dir . uniqid(); - $result = false; - $time = time(); - if (@file_put_contents($file, $time)) { - if ($fileTime = @file_get_contents($file)) { - if ($fileTime == $time) { - $result = true; - } - } - } - @unlink($file); - return $result; -} - -function _isWritable($dir) { - if (!isWritable($dir)) { - return false; - } - $tmpFile = "{$dir}" . uniqid(); - $bytes = @file_put_contents($tmpFile, time()); - @unlink($tmpFile); - return !empty($bytes); -} - -function getTmpDir($subdir = "") { - global $global; - if (empty($_SESSION['getTmpDir'])) { - $_SESSION['getTmpDir'] = array(); - } - if (empty($_SESSION['getTmpDir'][$subdir . "_"])) { - if (empty($global['tmpDir'])) { - $tmpDir = sys_get_temp_dir(); - if (empty($tmpDir) || !_isWritable($tmpDir)) { - $tmpDir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; - } - $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - $tmpDir = "{$tmpDir}{$subdir}"; - } else { - $tmpDir = $global['tmpDir']; - } - $tmpDir = addLastSlash($tmpDir); - if (!is_dir($tmpDir)) { - mkdir($tmpDir, 0755, true); - } - _session_start(); - $_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir; - } else { - $tmpDir = $_SESSION['getTmpDir'][$subdir . "_"]; - } - return $tmpDir; -} - -function getTmpFile() { - return getTmpDir("tmpFiles") . uniqid(); -} - -function getMySQLDate() { - global $global; - $sql = "SELECT now() as time FROM configurations LIMIT 1"; - // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about - $res = sqlDAL::readSql($sql); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - $row = $data['time']; - } else { - $row = false; - } - return $row; -} - -function _file_put_contents($filename, $data, $flags = 0, $context = null) { - make_path($filename); - return file_put_contents($filename, $data, $flags, $context); -} - -function html2plainText($html) { - $text = strip_tags($html); - $text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text)); - return $text; -} - -function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') { - if (empty($paceholder)) { - $paceholder = __("Password"); - } - ?> -
- - > - -
- - -
- > - -
- - - - - " . 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 (empty($json) && json_last_error()) { - //_error_log("_json_encode: Error 1 Found: " . json_last_error_msg()); - $object = object_to_array($object); - $json = json_encode($object); - if (empty($json) && 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: {$object} " . json_last_error_msg() . PHP_EOL . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $objectEncoded = $object; - array_walk_recursive($objectEncoded, function (&$item) { - if (is_string($item)) { - $item = utf8_encode($item); - } - }); - $json = json_encode($objectEncoded); - if (empty($json) && 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 (empty($json) && json_last_error()) { - _error_log("_json_encode: Error 6 Found: " . json_last_error_msg()); - $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); - if (json_last_error()) { - _error_log("_json_encode: Error 7 Found: " . json_last_error_msg()); - } - } - } - } - } - } - } - return $json; -} - -function _json_decode($object) { - if (empty($object)) { - return false; - } - if (!is_string($object)) { - return $object; - } - $json = json_decode($object); - if ($json === NULL) { - $object = str_replace(array("\r", "\n"), array('\r', '\n'), $object); - return json_decode($object); - } else { - return $json; - } -} - -// this will make sure the strring will fits in the database field -function _substr($string, $start, $length = null) { - // make sure the name is not chunked in case of multibyte string - if (function_exists("mb_strcut")) { - return mb_strcut($string, $start, $length, "UTF-8"); - } else { - return substr($string, $start, $length); - } -} - -function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") { - global $global, $advancedCustom; - if ($total < 2) { - return ''; - } - - if (empty($page)) { - $page = getCurrentPage(); - } - - $isInfiniteScroll = !empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector); - - $uid = md5($link); - - if ($total < $maxVisible) { - $maxVisible = $total; - } - if (empty($link)) { - $link = getSelfURI(); - if (preg_match("/(current=[0-9]+)/i", $link, $match)) { - $link = str_replace($match[1], "current={page}", $link); - } else { - //$link = addQueryStringParameter($link, 'current', '{page}'); - $link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}'; - } - } - - $class = ""; - if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) { - $class = "infiniteScrollPagination{$uid} hidden"; - } - - if ($isInfiniteScroll && $page > 1) { - if (preg_match("/\{page\}/", $link, $match)) { - $pageForwardLink = str_replace("{page}", $page + 1, $link); - } else { - $pageForwardLink = addQueryStringParameter($link, 'current', $page + 1); - } - - return ""; - } - - $pag = ' '; - - 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", $videoLengthInSeconds = 0) { - 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, $unlockPassword='', $namespace='') { - global $global; - if(!empty($unlockPassword)){ - if(empty($namespace)){ - $namespace = $_SERVER["SCRIPT_FILENAME"]; - } - if(!empty($_REQUEST['unlockPassword'])){ - if($_REQUEST['unlockPassword'] == $unlockPassword){ - _session_start(); - if(!isset($_SESSION['user']['forbiddenPage'])){ - $_SESSION['user']['forbiddenPage'] = array(); - } - $_SESSION['user']['forbiddenPage'][$namespace] = $_REQUEST['unlockPassword']; - } - } - if(!empty($_SESSION['user']['forbiddenPage'][$namespace]) && $unlockPassword === $_SESSION['user']['forbiddenPage'][$namespace]){ - return true; - } - } - $_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)) { - var_dump($error); - _error_log($error, AVideoLog::$ERROR); - header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); - if (!User::isAdmin()) { - if (!preg_match('/json\.php$/i', $_SERVER['PHP_SELF'])) { - echo '' . PHP_EOL; - include $global['systemRootPath'] . 'view/maintanance.html'; - } else { - $o = new stdClass(); - $o->error = true; - $o->msg = __('Under Maintanance'); - echo json_encode($o); - } - } else { - echo '
';
-            var_dump($error);
-            var_dump(debug_backtrace());
-            echo '
'; - } - 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() { - return ''; //TODO check why it is slowing down - 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; - $domain = preg_replace('/:[0-9]+$/', '', $domain); - $_getDomain = $domain; - return $domain; -} - -function getHostOnlyFromURL($url) { - $parse = parse_url($url); - $domain = $parse['host']; - $domain = str_replace("www.", "", $domain); - $domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain; - $domain = preg_replace('/:[0-9]+$/', '', $domain); - return $domain; -} - -/** - * It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc. - * - * From the IETF RFC4122: - * 8-4-4-4-12 - * @return string - */ -function getDeviceID($useRandomString = true) { - $ip = md5(getRealIpAddr()); - if (empty($_SERVER['HTTP_USER_AGENT'])) { - $device = "unknowDevice-{$ip}"; - $device .= '-' . intval(User::getId()); - return $device; - } - - if (empty($useRandomString)) { - $device = 'ypt-' . get_browser_name() . '-' . getOS() . '-' . $ip . '-' . md5($_SERVER['HTTP_USER_AGENT']); - $device = str_replace( - array('[', ']', ' '), - array('', '', '_'), $device); - $device .= '-' . intval(User::getId()); - return $device; - } - - $cookieName = "yptDeviceID"; - if (empty($_COOKIE[$cookieName])) { - if (empty($_GET[$cookieName])) { - $id = uniqidV4(); - $_GET[$cookieName] = $id; - } - if (empty($_SESSION[$cookieName])) { - _session_start(); - $_SESSION[$cookieName] = $_GET[$cookieName]; - } else { - $_GET[$cookieName] = $_SESSION[$cookieName]; - } - if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) { - return "getDeviceIDError"; - } - $_COOKIE[$cookieName] = $_GET[$cookieName]; - return $_GET[$cookieName]; - } - return $_COOKIE[$cookieName]; -} - -function deviceIdToObject($deviceID) { - $parts = explode('-', $deviceID); - $obj = new stdClass(); - $obj->browser = ''; - $obj->os = ''; - $obj->ip = ''; - $obj->user_agent = ''; - $obj->users_id = 0; - - foreach ($parts as $key => $value) { - $parts[$key] = str_replace('_', ' ', $value); - } - - switch ($parts[0]) { - case 'ypt': - $obj->browser = $parts[1]; - $obj->os = $parts[2]; - $obj->ip = $parts[3]; - $obj->user_agent = $parts[4]; - $obj->users_id = $parts[5]; - break; - case 'unknowDevice': - $obj->browser = $parts[0]; - $obj->os = 'unknow OS'; - $obj->ip = $parts[1]; - $obj->user_agent = 'unknow UA'; - $obj->users_id = $parts[2]; - break; - default: - break; - } - return $obj; -} - -function uniqidV4() { - $randomString = openssl_random_pseudo_bytes(16); - $time_low = bin2hex(substr($randomString, 0, 4)); - $time_mid = bin2hex(substr($randomString, 4, 2)); - $time_hi_and_version = bin2hex(substr($randomString, 6, 2)); - $clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2)); - $node = bin2hex(substr($randomString, 10, 6)); - - /** - * Set the four most significant bits (bits 12 through 15) of the - * time_hi_and_version field to the 4-bit version number from - * Section 4.1.3. - * @see http://tools.ietf.org/html/rfc4122#section-4.1.3 - */ - $time_hi_and_version = hexdec($time_hi_and_version); - $time_hi_and_version = $time_hi_and_version >> 4; - $time_hi_and_version = $time_hi_and_version | 0x4000; - - /** - * Set the two most significant bits (bits 6 and 7) of the - * clock_seq_hi_and_reserved to zero and one, respectively. - */ - $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved); - $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2; - $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000; - - return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node); -} - -// guid - -function _setcookie($cookieName, $value, $expires = 0) { - if (empty($expires)) { - if (empty($config) || !is_object($config)) { - $config = new Configuration(); - } - $expires = time() + $config->getSession_timeout(); - } - - if (version_compare(phpversion(), '7.3', '>=')) { - $cookie_options = array( - 'expires' => $expires, - 'path' => '/', - 'domain' => getDomain(), - 'secure' => true, - 'httponly' => false, - 'samesite' => 'None'); - return setcookie($cookieName, $value, $cookie_options); - } else { - return setcookie($cookieName, $value, (int) $expires, "/", getDomain()); - } -} - -function _unsetcookie($cookieName) { - $domain = getDomain(); - $expires = strtotime("-10 years"); - $value = ""; - _setcookie($cookieName, $value, $expires); - setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires); - setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain)); - setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain); - setcookie($cookieName, $value, (int) $expires, "/", "." . $domain); - setcookie($cookieName, $value, (int) $expires, "/", $domain); - setcookie($cookieName, $value, (int) $expires, "/"); - setcookie($cookieName, $value, (int) $expires); - unset($_COOKIE[$cookieName]); -} - -/** - * This function is not 100% but try to tell if the site is in an iFrame - * @global type $global - * @return boolean - */ -function isIframeInDifferentDomain() { - global $global; - if (!isIframe()) { - return false; - } - return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']); -} - -function isIframe() { - global $global; - if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') { - return true; - } - if (empty($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == $global['webSiteRootURL'] || str_replace('view/', '', getSelfURI()) == $global['webSiteRootURL']) { - return false; - } - return true; -} - -function getCredentialsURL() { - global $global; - return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1"; -} - -function gotToLoginAndComeBackHere($msg) { - global $global; - if (User::isLogged()) { - forbiddenPage($msg); - exit; - } - if (!empty($_GET['comebackhere'])) { - return false; - } - header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1"); - exit; -} - -function setAlertMessage($msg, $type = "msg") { - _session_start(); - $_SESSION['YPTalertMessage'][] = array($msg, $type); -} - -function setToastMessage($msg) { - setAlertMessage($msg, "toast"); -} - -function showAlertMessage() { - if (!empty($_SESSION['YPTalertMessage'])) { - foreach ($_SESSION['YPTalertMessage'] as $value) { - if (!empty($value[0])) { - if (empty($_GET[$value[1]])) { - $_GET[$value[1]] = array(); - } - $_GET[$value[1]][] = $value[0]; - } - } - _session_start(); - unset($_SESSION['YPTalertMessage']); - } - - $joinString = array('error', 'msg', 'success'); - foreach ($joinString as $value) { - if (!empty($_GET[$value]) && is_array($_GET[$value])) { - $_GET[$value] = array_unique($_GET[$value]); - $newStr = array(); - foreach ($_GET[$value] as $value2) { - if (!empty($value2)) { - $newStr[] = $value2; - } - } - $_GET[$value] = implode("
", $newStr); - } - } - - $check = array('error', 'msg', 'success', 'toast'); - foreach ($check as $value) { - if (!empty($_GET[$value])) { - if (is_array($_GET[$value])) { - $newStr = array(); - foreach ($_GET[$value] as $key => $value2) { - $value2 = str_replace('"', "''", $value2); - if (!empty($value2)) { - $newStr[] = $value2; - } - } - $_GET[$value] = $newStr; - } else { - $_GET[$value] = str_replace('"', "''", $_GET[$value]); - } - } - } - echo "/** showAlertMessage **/", PHP_EOL; - if (!empty($_GET['error'])) { - echo 'avideoAlertError("' . $_GET['error'] . '");'; - echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; - } - if (!empty($_GET['msg'])) { - echo 'avideoAlertInfo("' . $_GET['msg'] . '");'; - echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; - } - if (!empty($_GET['success'])) { - echo 'avideoAlertSuccess("' . $_GET['success'] . '");'; - echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; - } - if (!empty($_GET['toast'])) { - if (!is_array($_GET['toast'])) { - $_GET['toast'] = array($_GET['toast']); - } else { - $_GET['toast'] = array_unique($_GET['toast']); - } - foreach ($_GET['toast'] as $key => $value) { - $hideAfter = strlen(strip_tags($value)) * 150; - - if ($hideAfter < 3000) { - $hideAfter = 3000; - } - if ($hideAfter > 15000) { - $hideAfter = 15000; - } - - echo '$.toast({ - text: "' . $value . '", - hideAfter: ' . $hideAfter . ' // in milli seconds - });console.log("Toast Hide after ' . $hideAfter . '");'; - } - echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; - } - echo PHP_EOL, "/** showAlertMessage END **/"; -} - -function getResolutionLabel($res) { - if ($res == 720) { - return "" . getResolutionText($res) . ""; - } elseif ($res == 1080) { - return "" . getResolutionText($res) . ""; - } elseif ($res == 1440) { - return "" . getResolutionText($res) . ""; - } elseif ($res == 2160) { - return "" . getResolutionText($res) . ""; - } elseif ($res == 4320) { - return "" . getResolutionText($res) . ""; - } else { - return ''; - } -} - -function getResolutionText($res) { - $res = intval($res); - if ($res >= 720 && $res < 1080) { - return "HD"; - } elseif ($res >= 1080 && $res < 1440) { - return "FHD"; - } elseif ($res >= 1440 && $res < 2160) { - return "FHD+"; - } elseif ($res >= 2160 && $res < 4320) { - return "4K"; - } elseif ($res >= 4320) { - return "8K"; - } else { - return ''; - } -} - -function getResolutionTextRoku($res) { - $res = intval($res); - if ($res >= 720 && $res < 1080) { - return "HD"; - } elseif ($res >= 1080 && $res < 2160) { - return "FHD"; - } elseif ($res >= 2160) { - return "UHD"; - } else { - return 'SD'; - } -} - -// just realize the readdir is a lot faster then glob -function _glob($dir, $pattern) { - global $_glob; - if (empty($dir)) { - return array(); - } - if (empty($_glob)) { - $_glob = array(); - } - $name = md5($dir . $pattern); - if (isset($_glob[$name])) { - return $_glob[$name]; - } - $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - $array = array(); - if (is_dir($dir) && $handle = opendir($dir)) { - $count = 0; - while (false !== ($file_name = readdir($handle))) { - if ($file_name == '.' || $file_name == '..') { - continue; - } - //_error_log("_glob: {$dir}{$file_name} [$pattern]"); - //var_dump($pattern, $file_name, preg_match($pattern, $file_name)); - if (preg_match($pattern, $file_name)) { - $array[] = "{$dir}{$file_name}"; - } - } - closedir($handle); - } - $_glob[$name] = $array; - return $array; -} - -function globVideosDir($filename, $filesOnly = false) { - global $global; - if (empty($filename)) { - return array(); - } - $cleanfilename = Video::getCleanFilenameFromFile($filename); - $paths = Video::getPaths($filename); - - $dir = $paths['path']; - - if (is_dir($dir . $filename)) { - $dir = $dir . $filename; - $cleanfilename = ''; - } - - $pattern = "/{$cleanfilename}.*"; - if (!empty($filesOnly)) { - $formats = getValidFormats(); - $pattern .= ".(" . implode("|", $formats) . ")"; - } - $pattern .= "/"; - //var_dump($dir, $pattern); - return _glob($dir, $pattern); -} - -function getValidFormats() { - $video = array('webm', 'mp4', 'm3u8'); - $audio = array('mp3', 'ogg'); - $image = array('jpg', 'gif', 'webp'); - return array_merge($video, $audio, $image); -} - -function isValidFormats($format) { - $format = str_replace(".", "", $format); - return in_array($format, getValidFormats()); -} - -function getTimerFromDates($startTime, $endTime = 0) { - if (!is_int($startTime)) { - $startTime = strtotime($startTime); - } - if (!is_int($endTime)) { - $endTime = strtotime($endTime); - } - if (empty($endTime)) { - $endTime = time(); - } - $timer = abs($endTime - $startTime); - $uid = uniqid(); - return ""; -} - -function getServerClock() { - $id = uniqid(); - $today = getdate(); - $html = '00:00:00'; - $html .= ""; - return $html; -} - -/** - * Xsendfile and FFMPEG are required for this feature - * @global type $global - * @param type $filepath - * @return boolean - */ -function downloadHLS($filepath) { - global $global; - - if (!CustomizeUser::canDownloadVideos()) { - _error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO"); - return false; - } - - if (!file_exists($filepath)) { - _error_log("downloadHLS: file NOT found: {$filepath}"); - return false; - } - $output = m3u8ToMP4($filepath); - - if (!empty($output['error'])) { - $msg = 'downloadHLS was not possible'; - if (User::isAdmin()) { - $msg .= '
' . "m3u8ToMP4($filepath) return empty
" . nl2br($output['msg']); - } - _error_log("downloadHLS: m3u8ToMP4($filepath) return empty"); - die($msg); - } - - $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['error'])) { - - $msg = 'playHLSasMP4 was not possible'; - if (User::isAdmin()) { - $msg .= '
' . "m3u8ToMP4($filepath) return empty
" . nl2br($output['msg']); - } - die($msg); - } - - $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}"; - $msg = ''; - $error = true; - make_path($outputpath); - if (empty($outputfilename)) { - $msg = "downloadHLS: empty outputfilename {$outputfilename}"; - _error_log($msg); - return array('error' => $error, 'msg' => $msg); - } - _error_log("downloadHLS: m3u8ToMP4($input)"); - //var_dump(!preg_match('/^http/i', $input), filesize($input), preg_match('/.m3u8$/i', $input)); - $ism3u8 = preg_match('/.m3u8$/i', $input); - if (!preg_match('/^http/i', $input) && (filesize($input) <= 10 || $ism3u8)) { // dummy file - $filepath = escapeshellcmd(pathToRemoteURL($input, true, true)); - if ($ism3u8 && !preg_match('/.m3u8$/i', $filepath)) { - $filepath = addLastSlash($filepath) . 'index.m3u8'; - } - - $token = getToken(60); - $filepath = addQueryStringParameter($filepath, 'globalToken', $token); - } else { - $filepath = escapeshellcmd($input); - } - - if (is_dir($filepath)) { - $filepath = addLastSlash($filepath) . 'index.m3u8'; - } - - $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}"; - $msg1 = "downloadHLS: Exec Command ({$command})"; - _error_log($msg1); - //var_dump($outputfilename, $command, $_GET, $filepath);exit; - exec($command . " 2>&1", $output, $return); - if (!empty($return)) { - $msg2 = "downloadHLS: ERROR 1 " . implode(PHP_EOL, $output); - _error_log($msg2); - - $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);exit; - exec($command . " 2>&1", $output, $return); - if (!empty($return)) { - $msg3 = "downloadHLS: ERROR 2 " . implode(PHP_EOL, $output); - $finalMsg = $msg1 . PHP_EOL . $msg2 . PHP_EOL . $msg3; - _error_log($msg3); - return array('error' => $error, 'msg' => $finalMsg); - } - } - } else { - $msg = "downloadHLS: outputpath already exists ({$outputpath})"; - _error_log($msg); - } - $error = false; - return array('error' => $error, 'msg' => $msg, '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($destination) || empty($_POST[$postIndex])) { - return false; - } - $fileData = base64DataToImage($_POST[$postIndex]); - - $path_parts = pathinfo($destination); - $tmpDestination = $destination; - $extension = strtolower($path_parts['extension']); - if($extension!=='png'){ - $tmpDestination = $destination.'.png'; - } - - $saved = _file_put_contents($tmpDestination, $fileData); - - if($saved){ - if($extension!=='png'){ - convertImage($tmpDestination, $destination, 100); - unlink($tmpDestination); - } - } - //var_dump($saved, $tmpDestination, $destination, $extension);exit; - return $saved; -} - -function get_ffmpeg($ignoreGPU = false) { - global $global; - $complement = ''; - //$complement = ' -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 . $complement; -} - -function isHTMLPage($url) { - if (preg_match('/https?:\/\/(www\.)?(youtu.be|youtube.com|vimeo.com|bitchute.com)\//i', $url)) { - return true; - } else if ($type = getHeaderContentTypeFromURL($url)) { - if (preg_match('/text\/html/i', $type)) { - return true; - } - } - return false; -} - -function getHeaderContentTypeFromURL($url) { - if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) { - return $type; - } - return false; -} - -function canFullScreen() { - global $doNotFullScreen; - if (!empty($doNotFullScreen) || isSerie() || !isVideo()) { - return false; - } - return true; -} - -function getTinyMCE($id, $simpleMode = false) { - global $global; - ob_start(); - include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php'; - $contents = ob_get_contents(); - ob_end_clean(); - return $contents; -} - -function pathToRemoteURL($filename, $forceHTTP = false, $ignoreCDN = 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 (!preg_match('/index.m3u8$/', $filename)) { - if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { - $source = $aws_s3->getAddress("{$fileName}"); - $url = $source['url']; - if (empty($ignoreCDN)) { - $url = replaceCDNIfNeed($url, 'CDN_S3'); - } else if (!empty($source['url_noCDN'])) { - $url = $source['url_noCDN']; - } - } else - if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { - $source = $bb_b2->getAddress("{$fileName}"); - $url = $source['url']; - if (empty($ignoreCDN)) { - $url = replaceCDNIfNeed($url, 'CDN_B2'); - } else if (!empty($source['url_noCDN'])) { - $url = $source['url_noCDN']; - } - } else - if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { - $source = $ftp->getAddress("{$fileName}"); - $url = $source['url']; - if (empty($ignoreCDN)) { - $url = replaceCDNIfNeed($url, 'CDN_FTP'); - } else if (!empty($source['url_noCDN'])) { - $url = $source['url_noCDN']; - } - } - } - } - if (empty($url)) { - if ($forceHTTP) { - $paths = Video::getPaths($filename); - //$url = str_replace(getVideosDir(), getCDN() . "videos/", $filename); - if (empty($ignoreCDN)) { - $url = getCDN() . "{$paths['relative']}"; - } else { - $url = "{$global['webSiteRootURL']}{$paths['relative']}"; - } - if (preg_match('/index.m3u8$/', $filename) && !preg_match('/index.m3u8$/', $url)) { - $url .= 'index.m3u8'; - } - } else { - $url = $filename; - } - } - - //$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url); - - $pathToRemoteURL[$filename] = $url; - return $url; -} - -function getFilenameFromPath($path) { - global $global; - $fileName = Video::getCleanFilenameFromFile($path); - return $fileName; -} - -function showCloseButton() { - global $global, $showCloseButtonIncluded; - if (!empty($showCloseButtonIncluded)) { - return ''; - } - if (isSerie()) { - return ''; - } - - if (!isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Gallery")) { - if (!empty($obj->playVideoOnFullscreen)) { - $_REQUEST['showCloseButton'] = 1; - } - } - if (isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Live")) { - if (!empty($obj->playLiveInFullScreen)) { - $_REQUEST['showCloseButton'] = 1; - } - } - if (!empty($_REQUEST['showCloseButton'])) { - $showCloseButtonIncluded = 1; - include $global['systemRootPath'] . 'view/include/youtubeModeOnFullscreenCloseButton.php'; - } - return ''; -} - -function getThemes() { - global $_getThemes, $global; - if (isset($_getThemes)) { - return $_getThemes; - } - $_getThemes = array(); - foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) { - $fileEx = basename($filename, ".css"); - $_getThemes[] = $fileEx; - } - return $_getThemes; -} - -function getCurrentTheme() { - global $config; - if (!empty($_REQUEST['customCSS'])) { - _setcookie('customCSS', $_REQUEST['customCSS']); - return $_REQUEST['customCSS']; - } - if (!empty($_COOKIE['customCSS'])) { - return $_COOKIE['customCSS']; - } - return $config->getTheme(); -} - -/* - * $users_id="" or 0 means send messages to all users - * $users_id="-1" means send to no one - */ - -function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern = "") { - if (AVideoPlugin::isEnabledByName('YPTSocket')) { - if (!is_string($msg)) { - $msg = json_encode($msg); - } - $obj = YPTSocket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern); - if ($obj->error && !empty($obj->msg)) { - _error_log("sendSocketMessage " . $obj->msg); - } - return $obj; - } - return false; -} - -function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") { - _error_log("sendSocketMessageToUsers_id start " . json_encode($users_id)); - 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 sendSocketErrorMessageToUsers_id($msg, $users_id, $callbackJSFunction = "avideoResponse") { - $newMessage = new stdClass(); - $newMessage->error = true; - $newMessage->msg = $msg; - return sendSocketMessageToUsers_id($newMessage, $users_id, $callbackJSFunction); -} - -function sendSocketSuccessMessageToUsers_id($msg, $users_id, $callbackJSFunction = "avideoResponse") { - $newMessage = new stdClass(); - $newMessage->error = false; - $newMessage->msg = $msg; - return sendSocketMessageToUsers_id($newMessage, $users_id, $callbackJSFunction); -} - -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 (isWindows()) { - //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 (isWindows()) { - exec("taskkill /F /PID $pid"); - } else { - exec("kill -9 $pid"); - } - return true; -} - -function isWindows() { - return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; -} - -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('isURL200Clear: ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - rrmdir($cacheDir); -} - -function deleteStatsNotifications() { - Live::deleteStatsCache(); - $cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications"; - ObjectYPT::deleteCache($cacheName); -} - -function getStatsNotifications($force_recreate = false) { - $cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications"; - unset($_POST['sort']); - if ($force_recreate) { - Live::deleteStatsCache(); - } else { - $json = ObjectYPT::getCache($cacheName, 0, true); - } - if (empty($json) || !empty($json->error) || !isset($json->error)) { - //_error_log('getStatsNotifications: 1 ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - $json = Live::getStats(); - $json = object_to_array($json); - - if (empty($json['applications']) && is_array($json)) { - $oldjson = $json; - $json = array(); - $json['applications'] = array(); - foreach ($oldjson 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['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); - } - if (empty($json['countLiveStream']) || $json['countLiveStream'] < $json['total']) { - $json['countLiveStream'] = $json['total']; - } - 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($msg = '') { - 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(); - echo $msg; - @header("Connection: close"); - @header("Content-Length: " . ob_get_length()); - @header("HTTP/1.1 200 OK"); - ob_end_flush(); - flush(); -} - -function cleanUpRowFromDatabase($row) { - if (is_array($row)) { - foreach ($row as $key => $value) { - if (preg_match('/pass/i', $key)) { - unset($row[$key]); - } - } - } - return $row; -} - -function getImageTransparent1pxURL() { - global $global; - return getCDN() . "view/img/transparent1px.png"; -} - -function getDatabaseTime() { - global $global, $_getDatabaseTime; - if (isset($_getDatabaseTime)) { - return $_getDatabaseTime; - } - $sql = "SELECT CURRENT_TIMESTAMP"; - $res = sqlDAL::readSql($sql); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - $row = $data; - } else { - $row = false; - } - $_getDatabaseTime = strtotime($row['CURRENT_TIMESTAMP']); - return $_getDatabaseTime; -} - -function get_js_availableLangs() { - global $global; - if (empty($global['js_availableLangs'])) { - include_once $global['systemRootPath'] . 'objects/bcp47.php'; - } - return $global['js_availableLangs']; -} - -function listAllWordsToTranslate() { - global $global; - $cacheName = 'listAllWordsToTranslate'; - $cache = ObjectYPT::getCache($cacheName, 0); - if (!empty($cache)) { - return object_to_array($cache); - } - ini_set('max_execution_time', 300); - - function listAll($dir) { - $vars = array(); - if (preg_match('/vendor.*$/', $dir)) { - return $vars; - } - 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_numeric($time1)) { - $time1 = strtotime($time1); - } - if (!is_numeric($time2)) { - $time2 = strtotime($time2); - } - - return $time1 - $time2; -} - -function secondsIntervalHuman($time, $useDatabaseTime = true) { - $dif = secondsIntervalFromNow($time, $useDatabaseTime); - if ($dif < 0) { - return humanTimingAfterwards($time, 0, $useDatabaseTime); - } else { - return humanTimingAgo($time, 0, $useDatabaseTime); - } -} - -function isTimeForFuture($time, $useDatabaseTime = true) { - $dif = secondsIntervalFromNow($time, $useDatabaseTime); - if ($dif < 0) { - return true; - } else { - return false; - } -} - -function secondsIntervalFromNow($time, $useDatabaseTimeOrTimezoneString = true) { - $timeNow = time(); - //var_dump($time, $useDatabaseTimeOrTimezoneString); - if (!empty($useDatabaseTimeOrTimezoneString)) { - if (is_numeric($useDatabaseTimeOrTimezoneString) || is_bool($useDatabaseTimeOrTimezoneString)) { - //echo $time.'-'.__LINE__.'=>'; - $timeNow = getDatabaseTime(); - } else if (is_string($useDatabaseTimeOrTimezoneString)) { - //echo '-'.__LINE__.PHP_EOL.PHP_EOL; - $timeNow = getTimeInTimezone($timeNow, $useDatabaseTimeOrTimezoneString); - } - } - return secondsInterval($timeNow, $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 (isWindows()) { - $path = str_replace('/', DIRECTORY_SEPARATOR, $path); - $path = str_replace('\\\\\\', DIRECTORY_SEPARATOR, $path); - } else { - $path = str_replace('\\', DIRECTORY_SEPARATOR, $path); - } - if ($addLastSlash) { - $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - } - return $path; -} - -function idToHash($id) { - global $global, $_idToHash; - - if (!isset($_idToHash)) { - $_idToHash = array(); - } - - if (!empty($_idToHash[$id])) { - return $_idToHash[$id]; - } - - if (!empty($global['useLongHash'])) { - $base = 2; - $cipher_algo = 'des'; - } else { - $base = 32; - $cipher_algo = 'rc4'; - } - if (empty($global['salt'])) { - $global['salt'] = '11234567890abcdef'; - } - $idConverted = base_convert($id, 10, $base); - $hash = (@openssl_encrypt($idConverted, $cipher_algo, $global['salt'])); - //$hash = preg_replace('/^([+]+)/', '', $hash); - $hash = preg_replace('/(=+)$/', '', $hash); - $hash = str_replace(array('/', '+', '='), array('_', '-', '.'), $hash); - //return base64_encode($hash); - $_idToHash[$id] = $hash; - return $hash; -} - -function hashToID($hash) { - global $global; - if (!empty($global['useLongHash'])) { - $base = 2; - $cipher_algo = 'des'; - } else { - $base = 32; - $cipher_algo = 'rc4'; - } - //$hash = str_pad($hash, 4, "="); - $hash = str_replace(array('_', '-', '.'), array('/', '+', '='), $hash); - //$hash = base64_decode($hash); - $decrypt = openssl_decrypt(($hash), $cipher_algo, $global['salt']); - $decrypt = base_convert($decrypt, $base, 10); - return intval($decrypt); -} - -function videosHashToID($hash_of_videos_id) { - if (is_int($hash_of_videos_id)) { - return $hash_of_videos_id; - } - if (!is_string($hash_of_videos_id) && !is_numeric($hash_of_videos_id)) { - if (is_array($hash_of_videos_id)) { - return $hash_of_videos_id; - } else { - 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 (!empty($advancedCustom) && 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 getURL($relativePath) { - global $global; - if (!isset($_SESSION['user']['sessionCache']['getURL'])) { - $_SESSION['user']['sessionCache']['getURL'] = array(); - } - if (!empty($_SESSION['user']['sessionCache']['getURL'][$relativePath])) { - return $_SESSION['user']['sessionCache']['getURL'][$relativePath]; - } - - $file = "{$global['systemRootPath']}{$relativePath}"; - $url = getCDN() . $relativePath; - if (file_exists($file)) { - $cache = @filemtime($file) . '_' . @filectime($file); - $url = addQueryStringParameter($url, 'cache', $cache); - $_SESSION['user']['sessionCache']['getURL'][$relativePath] = $url; - } else { - $url = addQueryStringParameter($url, 'cache', 'not_found'); - } - - return $url; -} - -function getCDNOrURL($url, $type = 'CDN', $id = 0) { - if (!preg_match('/^http/i', $url)) { - return $url; - } - $cdn = getCDN($type, $id); - if (!empty($cdn)) { - return $cdn; - } - return addLastSlash($url); -} - -function replaceCDNIfNeed($url, $type = 'CDN', $id = 0) { - $cdn = getCDN($type, $id); - if (empty($cdn)) { - return $url; - } - - return str_replace(parse_url($url, PHP_URL_HOST), parse_url($cdn, PHP_URL_HOST), $url); -} - -function isIPPrivate($ip) { - if ($ip == '192.168.1.4') { - return false; - } - if (!filter_var($ip, FILTER_VALIDATE_IP)) { - return false; - } - $result = filter_var( - $ip, - FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); - if (empty($result)) { - return true; - } - return false; -} - -function countDownPage($toTime, $message, $image, $bgImage) { - global $global; - include $global['systemRootPath'] . 'objects/functionCountDownPage.php'; - exit; -} - -function inputToRequest() { - $content = file_get_contents("php://input"); - if (!empty($content)) { - $json = json_decode($content); - if (empty($json)) { - return false; - } - foreach ($json as $key => $value) { - if (!isset($_REQUEST[$key])) { - $_REQUEST[$key] = $value; - } - } - } -} - -function useVideoHashOrLogin() { - - if (!empty($_REQUEST['video_id_hash'])) { - $videos_id = Video::getVideoIdFromHash($_REQUEST['video_id_hash']); - if (!empty($videos_id)) { - $users_id = Video::getOwner($videos_id); - $user = new User($users_id); - _error_log("useVideoHashOrLogin: $users_id, $videos_id"); - return $user->login(true); - } - } - return User::loginFromRequest(); -} - -function strip_specific_tags($string, $tags_to_strip = array('script', 'style', 'iframe', 'object', 'applet', 'link')) { - foreach ($tags_to_strip as $tag) { - $string = preg_replace('/<' . $tag . '[^>]*>(.*?)<\/' . $tag . '>/s', '$1', $string); - } - return $string; -} - -function strip_render_blocking_resources($string) { - $tags_to_strip = array('link', 'style'); - $head = preg_match('/(.*)<\/head>/s', $string, $matches); - $string = str_replace($matches[0], '{_head_}', $string); - foreach ($tags_to_strip as $tag) { - $string = preg_replace('/<' . $tag . '[^>]*>(.*?)<\/' . $tag . '>/s', '', $string); - $string = preg_replace('/<' . $tag . '[^>]*\/>/s', '', $string); - } - $string = str_replace('{_head_}', $matches[0], $string); - return $string; -} - -function optimizeHTMLTags($html) { - return $html; - //$html = optimizeCSS($html); - //$html = optimizeJS($html); - return $html . '<--! optimized -->'; -} - -function optimizeCSS($html) { - global $global; - $css = ''; - $cacheDir = getVideosDir() . 'cache/'; - $cacheName = md5(getSelfURI() . User::getId()) . '.css'; - $filename = "{$cacheDir}{$cacheName}"; - $urlname = "{$global['webSiteRootURL']}videos/cache/{$cacheName}"; - $HTMLTag = ""; - $fileExists = file_exists($filename); - //$fileExists = false; - // get link tags - $pattern = '/((<(link)[^>]*(stylesheet|css)[^>]*\/>)|(<(style)[^>]*>([^<]+)<\/style>))/i'; - preg_match_all($pattern, $html, $matches); - foreach ($matches[3] as $key => $type) { - if (strtolower($type) == 'link') { - $linkTag = $matches[0][$key]; - $pattern = '/href=.(http[^"\']+)/i'; - preg_match($pattern, $linkTag, $href); - if (empty($href)) { - continue; - } - if (!$fileExists) { - $content = url_get_contents($href[1]); - if (empty($content)) { - continue; - } - $css .= PHP_EOL . " /* link {$href[1]} */ " . $content; - } - $html = str_replace($linkTag, '', $html); - } else { - if (!$fileExists) { - $css .= PHP_EOL . ' /* style */ ' . $matches[7][$key]; - } - $html = str_replace($matches[1][$key], '', $html); - } - } - if (!$fileExists) { - _file_put_contents($filename, $css); - } - return str_replace('', '' . PHP_EOL . $HTMLTag . PHP_EOL . '', $html); -} - -function optimizeJS($html) { - global $global; - $js = ''; - $cacheDir = getVideosDir() . 'cache/'; - $cacheName = md5(getSelfURI() . User::getId()) . '.js'; - $filename = "{$cacheDir}{$cacheName}"; - $urlname = "{$global['webSiteRootURL']}videos/cache/{$cacheName}"; - $HTMLTag = ""; - $fileExists = file_exists($filename); - $fileExists = false; - // get link tags - $pattern = '/((]+(src=[^ ]+)[^>]*>( *)<\/script>)|(]*>([^<]+)<\/script>))/si'; - preg_match_all($pattern, $html, $matches); - foreach ($matches[2] as $key => $type) { - if (empty($type)) { - if (preg_match('/application_ld_json/i', $matches[1][$key])) { - continue; - } - $js .= PHP_EOL . " /* js */ " . $matches[6][$key]; - $html = str_replace($matches[1][$key], '', $html); - } else { - $pattern = '/src=.(http[^"\']+)/i'; - preg_match($pattern, $type, $href); - if (empty($href)) { - continue; - } - if (preg_match('/(jquery|video-js|videojs)/i', $href[1])) { - continue; - } - if (!$fileExists) { - $content = url_get_contents($href[1]); - if (empty($content)) { - continue; - } - $js .= PHP_EOL . " /* js link {$href[1]} */ " . $content; - } - $html = str_replace($type, '', $html); - } - } - if (!$fileExists) { - _file_put_contents($filename, $js); - } - return str_replace('', '' . PHP_EOL . $HTMLTag . PHP_EOL . '', $html); -} - -function mysqlBeginTransaction() { - global $global; - _error_log('Begin transaction ' . getSelfURI()); - $global['mysqli']->autocommit(false); -} - -function mysqlRollback() { - global $global; - _error_log('Rollback transaction ' . getSelfURI(), AVideoLog::$ERROR); - $global['mysqli']->rollback(); - $global['mysqli']->autocommit(true); -} - -function mysqlCommit() { - global $global; - _error_log('Commit transaction ' . getSelfURI()); - $global['mysqli']->commit(); - $global['mysqli']->autocommit(true); -} - -function number_format_short($n, $precision = 1) { - $n = floatval($n); - if ($n < 900) { - // 0 - 900 - $n_format = number_format($n, $precision); - $suffix = ''; - } else if ($n < 900000) { - // 0.9k-850k - $n_format = number_format($n / 1000, $precision); - $suffix = 'K'; - } else if ($n < 900000000) { - // 0.9m-850m - $n_format = number_format($n / 1000000, $precision); - $suffix = 'M'; - } else if ($n < 900000000000) { - // 0.9b-850b - $n_format = number_format($n / 1000000000, $precision); - $suffix = 'B'; - } else { - // 0.9t+ - $n_format = number_format($n / 1000000000000, $precision); - $suffix = 'T'; - } - - // Remove unnecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1" - // Intentionally does not affect partials, eg "1.50" -> "1.50" - if ($precision > 0) { - $dotzero = '.' . str_repeat('0', $precision); - $n_format = str_replace($dotzero, '', $n_format); - } - - return $n_format . $suffix; -} - -function seconds2human($ss) { - $s = $ss % 60; - $m = floor(($ss % 3600) / 60); - $h = floor(($ss % 86400) / 3600); - $d = floor(($ss % 2592000) / 86400); - $M = floor($ss / 2592000); - - $times = array(); - - if (!empty($M)) { - $times[] = "$M " . __('m'); - } - if (!empty($d)) { - $times[] = "$d " . __('d'); - } - if (!empty($h)) { - $times[] = "$h " . __('h'); - } - if (!empty($m)) { - $times[] = "$m " . __('min'); - } - if (!empty($s)) { - $times[] = "$s " . __('sec'); - } - - return implode(', ', $times); -} - -/** - * convert a time in a timezone into my time - * @param type $time - * @param type $timezone - * @return type - */ -function getTimeInTimezone($time, $timezone) { - if (!is_numeric($time)) { - $time = strtotime($time); - } - if (empty($timezone) || empty(date_default_timezone_get()) || $timezone == date_default_timezone_get()) { - return $time; - } - $date = new DateTime(date('Y-m-d H:i:s', $time)); - $date->setTimezone(new DateTimeZone($timezone)); - //$date->setTimezone(date_default_timezone_get()); - $dateString = $date->format('Y-m-d H:i:s'); - return strtotime($dateString); -} - -function listFolderFiles($dir) { - if (empty($dir)) { - return array(); - } - $ffs = scandir($dir); - - unset($ffs[array_search('.', $ffs, true)]); - unset($ffs[array_search('..', $ffs, true)]); - - $files = array(); - // prevent empty ordered elements - if (count($ffs) >= 1) { - foreach ($ffs as $ff) { - $dir = rtrim($dir, DIRECTORY_SEPARATOR); - $file = $dir . DIRECTORY_SEPARATOR . $ff; - if (is_dir($file)) { - $files[] = listFolderFiles($file); - } else { - $files[] = $file; - } - } - } - return $files; -} - -function convertToMyTimezone($date, $fromTimezone) { - $time = getTimestampFromTimezone($date, $fromTimezone); - return date('Y-m-d H:i:s', $time); -} - -function getTimestampFromTimezone($date, $fromTimezone) { - $date = new DateTime($date, new DateTimeZone($fromTimezone)); - return $date->getTimestamp(); -} - -function getCSSAnimation($type = 'animate__flipInX', $loaderSequenceName = 'default', $delay = 0.1) { - global $_getCSSAnimationClassDelay; - getCSSAnimationClassAndStyleAddWait($delay, $loaderSequenceName); - return array('class' => 'animate__animated ' . $type, 'style' => "-webkit-animation-delay: {$_getCSSAnimationClassDelay[$loaderSequenceName]}s; animation-delay: {$_getCSSAnimationClassDelay[$loaderSequenceName]}s;"); -} - -function getCSSAnimationClassAndStyleAddWait($delay, $loaderSequenceName = 'default') { - global $_getCSSAnimationClassDelay; - if (!isset($_getCSSAnimationClassDelay)) { - $_getCSSAnimationClassDelay = array(); - } - if (empty($_getCSSAnimationClassDelay[$loaderSequenceName])) { - $_getCSSAnimationClassDelay[$loaderSequenceName] = 0; - } - $_getCSSAnimationClassDelay[$loaderSequenceName] += $delay; -} - -function getCSSAnimationClassAndStyle($type = 'animate__flipInX', $loaderSequenceName = 'default', $delay = 0.1) { - $array = getCSSAnimation($type, $loaderSequenceName, $delay); - return "{$array['class']}\" style=\"{$array['style']}"; -} - -function isImage($file) { - list($width, $height, $type, $attr) = getimagesize($file); - if ($type == IMAGETYPE_PNG) { - return 'png'; - } - if ($type == IMAGETYPE_JPEG) { - return 'jpg'; - } - if ($type == IMAGETYPE_GIF) { - return 'gif'; - } - return false; -} - -function isHTMLEmpty($html_string) { - return empty(trim(strip_specific_tags($html_string, array('br', 'p')))); -} - -function totalImageColors($image_path) { - $img = imagecreatefromjpeg($image_path); - $w = imagesx($img); - $h = imagesy($img); - - // capture the raw data of the image - ob_start(); - imagegd2($img, null, $w); - $data = ob_get_clean(); - $totalLength = strlen($data); - - // calculate the length of the actual pixel data - // from that we can derive the header size - $pixelDataLength = $w * $h * 4; - $headerLength = $totalLength - $pixelDataLength; - - // use each four-byte segment as the key to a hash table - $counts = array(); - for ($i = $headerLength; $i < $totalLength; $i += 4) { - $pixel = substr($data, $i, 4); - $count = & $counts[$pixel]; - $count += 1; - } - $colorCount = count($counts); - return $colorCount; -} - -function isImageCorrupted($image_path) { - $fsize = filesize($image_path); - if (strpos($image_path, 'thumbsSmall') !== false) { - if ($fsize < 1000) { - return true; - } - } else { - if ($fsize < 2000) { - return true; - } - } - - if (totalImageColors($image_path) === 1) { - return true; - } - - if (!isGoodImage($image_path)) { - return true; - } - return false; -} - -// detect partial grey immages -function isGoodImage($fn) { - list($w, $h) = getimagesize($fn); - $im = imagecreatefromstring(file_get_contents($fn)); - $grey = 0; - for ($i = 0; $i < 5; ++$i) { - for ($j = 0; $j < 5; ++$j) { - $x = $w - 5 + $i; - $y = $h - 5 + $j; - list($r, $g, $b) = array_values(imagecolorsforindex($im, imagecolorat($im, $x, $y))); - if ($r == $g && $g == $b && $b == 128) - ++$grey; - } - } - return $grey < 12; -} - -function defaultIsPortrait(){ - global $_defaultIsPortrait; - - if(!isset($_defaultIsPortrait)){ - $_defaultIsPortrait = false; - if($obj = AVideoPlugin::getDataObjectIfEnabled('YouPHPFlix2') && empty($obj->landscapePosters)){ - $_defaultIsPortrait = true; - } - } - - return $_defaultIsPortrait; -} + 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) +{ + if (!is_numeric($time)) { + $time = strtotime($time); + } + $time = secondsIntervalFromNow($time, $useDatabaseTime); + if (empty($time)) { + return __("Now"); + } elseif ($time > 0) { + return secondsToHumanTiming($time, $precision) . ' ' . __('Ago'); + } + 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 = [ + 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.3.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 isAPPInstalled($appName) +{ + $appName = preg_replace('/[^a-z0-9_-]/i', '', $appName); + return trim(shell_exec("which {$appName}")); +} + +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 = [ + '/[áàâãªä]/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 = []; + if (!User::isAdmin()) { + $id = User::getId(); + $sql .= " WHERE users_id = ? "; + $formats = "i"; + $values = [$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"] == "Test of comment" && User::isAdmin()) { + $mail->SMTPDebug = 3; + $mail->Debugoutput = function ($str, $level) { + _error_log("SMTP ERROR $level; message: $str", AVideoLog::$ERROR); + }; + } + $mail->SMTPOptions = [ + 'ssl' => [ + '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 = []; + $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 = [$to]; + } + + if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); + } + + $subject = UTF8encode($subject); + $message = UTF8encode($message); + $message = createEmailMessageFromTemplate($message); + _error_log("sendSiteEmail [" . count($to) . "] {$subject}"); + global $config, $global; + //require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; + $contactEmail = $config->getContactEmail(); + $webSiteTitle = $config->getWebSiteTitle(); + try { + if (!is_array($to)) { + $mail = new \PHPMailer\PHPMailer\PHPMailer(); + setSiteSendMessage($mail); + $mail->setFrom($contactEmail, $webSiteTitle); + $mail->Subject = $subject . " - " . $webSiteTitle; + $mail->msgHTML($message); + + $mail->addAddress($to); + + $resp = $mail->send(); + if (!$resp) { + _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); + } else { + _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); + } + } else { + $size = intval(@$advancedCustom->splitBulkEmailSend); + if (empty($size)) { + $size = 90; + } + + $to = array_iunique($to); + $pieces = partition($to, $size); + foreach ($pieces as $piece) { + $mail = new \PHPMailer\PHPMailer\PHPMailer(); + setSiteSendMessage($mail); + $mail->setFrom($contactEmail, $webSiteTitle); + $mail->Subject = $subject . " - " . $webSiteTitle; + $mail->msgHTML($message); + $count = 0; + foreach ($piece as $value) { + $count++; + _error_log("sendSiteEmail::addBCC [{$count}] {$value}"); + $mail->addBCC($value); + } + + $resp = $mail->send(); + if (!$resp) { + _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); + } else { + _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); + } + } + } + //Set the subject line + return $resp; + } catch (phpmailerException $e) { + _error_log($e->errorMessage()); //Pretty error messages from PHPMailer + } catch (Exception $e) { + _error_log($e->getMessage()); //Boring error messages from anything else! + } +} + +function sendSiteEmailAsync($to, $subject, $message) +{ + global $global; + $content = ['to' => $to, 'subject' => $subject, 'message' => $message]; + $tmpFile = getTmpFile(); + file_put_contents($tmpFile, _json_encode($content)); + //outputAndContinueInBackground(); + $command = "php {$global['systemRootPath']}objects/sendSiteEmailAsync.php '$tmpFile'"; + + _error_log("sendSiteEmailAsync start ($command)"); + $pid = execAsync($command); + _error_log("sendSiteEmailAsync end {$pid}"); + return $pid; +} + +function createEmailMessageFromTemplate($message) +{ + + //check if the message already have a HTML body + if (preg_match("/html>/i", $message)) { + return $message; + } + + global $global, $config; + $text = file_get_contents("{$global['systemRootPath']}view/include/emailTemplate.html"); + $siteTitle = $config->getWebSiteTitle(); + $logo = "getLogo(true) . "\" alt=\"{$siteTitle}\">"; + + $words = [$logo, $message, $siteTitle]; + $replace = ['{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 = []; + 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 = []; + // 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 = []; + 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 = []; + +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 whether a file should recreate a cache, based on its time and the plugin's token expiration. + * @param type $filename + * @return boolean + */ +function recreateCache($filename) +{ + return (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()); +} + +function _getImagesURL($fileName, $type) +{ + global $global; + $files = []; + $source = Video::getSourceFile($fileName, ".jpg"); + $file1 = $source['path']; + if (file_exists($file1)) { + $files["jpg"] = [ + 'filename' => "{$fileName}.jpg", + 'path' => $file1, + 'url' => $source['url'], + 'type' => 'image', + ]; + } else { + unset($file1); + $files["jpg"] = [ + '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"] = [ + 'filename' => "{$fileName}_portrait.jpg", + 'path' => $file2, + 'url' => $source['url'], + 'type' => 'image', + ]; + } elseif ($type != 'image') { + if (!empty($file1)) { + $files["pjpg"] = $files["jpg"]; + } else { + $files["pjpg"] = [ + '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 []; + } + $time = microtime(); + $time = explode(' ', $time); + $time = $time[1] + $time[0]; + $start = $time; + + $source = Video::getSourceFile($fileName, ".pdf"); + $file = $source['path']; + $files["pdf"] = [ + '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 []; + } + $time = microtime(); + $time = explode(' ', $time); + $time = $time[1] + $time[0]; + $start = $time; + + $types = ['png', 'gif', 'webp', 'jpg']; + + foreach ($types as $value) { + $source = Video::getSourceFile($fileName, ".{$value}"); + $file = $source['path']; + $files["image"] = [ + '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 []; + } + $time = microtime(); + $time = explode(' ', $time); + $time = $time[1] + $time[0]; + $start = $time; + + $types = ['zip']; + + foreach ($types as $value) { + $source = Video::getSourceFile($fileName, ".{$value}"); + $file = $source['path']; + $files["zip"] = [ + '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 []; + } + $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 []; + } + $time = microtime(); + $time = explode(' ', $time); + $time = $time[1] + $time[0]; + $start = $time; + if ($fileNameisThePath) { + $filename = basename($fileName); + $path = Video::getPathToFile($filename); + if (filesize($path) < 20) { + $objCDNS = AVideoPlugin::getObjectDataIfEnabled('CDN'); + if (!empty($objCDNS) && $objCDNS->enable_storage) { + $url = CDNStorage::getURL("{$filename}"); + } + } + if (empty($url)) { + $url = Video::getURLToFile($filename); + } + + $files["mp3"] = [ + 'filename' => $filename, + 'path' => $path, + 'url' => $url, + 'url_noCDN' => $url, + 'type' => 'audio', + 'format' => 'mp3', + ]; + } else { + $source = Video::getSourceFile($fileName, ".mp3"); + $file = $source['path']; + $files["mp3"] = [ + 'filename' => "{$fileName}.mp3", + 'path' => $file, + 'url' => $source['url'], + 'url_noCDN' => @$source['url_noCDN'], + 'type' => 'audio', + 'format' => 'mp3', + ]; + } + + $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 []; +} + +function getVideosURLMP3Only($fileName) +{ + $allFiles = getVideosURL_V2($fileName); + if (is_array($allFiles)) { + foreach ($allFiles as $key => $value) { + if ($value['format'] !== 'mp3') { + unset($allFiles[$key]); + } + } + return $allFiles; + } + _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); + return []; +} + +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 []; +} + +function getVideosURLMP4WEBMOnly($fileName) +{ + return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName)); +} + +function getVideosURLMP4WEBMMP3Only($fileName) +{ + return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName), getVideosURLMP3Only($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 = []; + +function getVideosURL_V2($fileName, $recreateCache = false) +{ + global $global, $getVideosURL_V2Array; + if (empty($fileName)) { + return []; + } + //$recreateCache = true; + $cleanfilename = Video::getCleanFilenameFromFile($fileName); + + if (!empty($getVideosURL_V2Array[$cleanfilename])) { + return $getVideosURL_V2Array[$cleanfilename]; + } + + $paths = Video::getPaths($cleanfilename); + + $pdf = $paths['path'] . "{$cleanfilename}.pdf"; + $mp3 = $paths['path'] . "{$cleanfilename}.mp3"; + if (file_exists($pdf)) { + return getVideosURLPDF($fileName); + } elseif (file_exists($mp3)) { + return getVideosURLAudio($mp3, true); + } + $cacheName = "getVideosURL_V2$fileName"; + if (empty($recreateCache)) { + $lifetime = maxLifetime(); + + $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; + TimeLogStart($TimeLog1); + $files = object_to_array(ObjectYPT::getCache($cacheName, $lifetime, true)); + if (is_array($files)) { + //_error_log("getVideosURL_V2: do NOT recreate lifetime = {$lifetime}"); + $preg_match_url = addcslashes(getCDN(), "/") . "videos"; + foreach ($files as $value) { + // check if is a dummy file and the URL still wrong + $pathFilesize = filesize($value['path']); + if ( + $value['type'] === 'video' && // is a video + preg_match("/^{$preg_match_url}/", $value['url']) && // the URL is the same as the main domain + $pathFilesize < 20) { // file size is small + _error_log("getVideosURL_V2:: dummy file found, fix cache " . json_encode(["/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), $pathFilesize, $value])); + unset($files); + $video = Video::getVideoFromFileName($fileName, true, true); + Video::clearCache($video['id']); + break; + } else { + //_error_log("getVideosURL_V2:: NOT dummy file ". json_encode(array("/^{$preg_match_url}video/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']),filesize($value['path']),$value))); + } + } + //_error_log("getVideosURL_V2:: cachestill good ". json_encode($files)); + } else { + //_error_log("getVideosURL_V2:: cache not found ". json_encode($files)); + } + TimeLogEnd($TimeLog1, __LINE__); + } else { + _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + } + if (empty($files)) { + $files = []; + $plugin = AVideoPlugin::loadPlugin("VideoHLS"); + if (!empty($plugin)) { + $timeName = "getVideosURL_V2::VideoHLS::getSourceFile($fileName)"; + TimeLogStart($timeName); + $files = VideoHLS::getSourceFile($fileName, true); + TimeLogEnd($timeName, __LINE__); + } + $video = ['webm', 'mp4']; + $audio = ['mp3', 'ogg']; + $image = ['jpg', 'gif', 'webp']; + + $formats = array_merge($video, $audio, $image); + + //$globQuery = getVideosDir()."{$cleanfilename}*.{" . implode(",", $formats) . "}"; + //$filesInDir = glob($globQuery, GLOB_BRACE); + $timeName = "getVideosURL_V2::globVideosDir($cleanfilename)"; + TimeLogStart($timeName); + $filesInDir = globVideosDir($cleanfilename, true); + TimeLogEnd($timeName, __LINE__); + + $timeName = "getVideosURL_V2::foreach"; + TimeLogStart($timeName); + foreach ($filesInDir as $file) { + $parts = pathinfo($file); + + if ($parts['filename'] == 'index') { + $parts['filename'] = str_replace(Video::getPathToFile($parts['dirname']), '', $parts['dirname']); + } + + //$timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; + //TimeLogStart($timeName2); + $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); + //TimeLogEnd($timeName2, __LINE__); + if (empty($source)) { + continue; + } + if (in_array($parts['extension'], $image) && filesize($file) < 1000 && !preg_match("/Dummy File/i", file_get_contents($file))) { + continue; + } + + if (preg_match("/{$cleanfilename}(_.+)[.]{$parts['extension']}$/", $file, $matches)) { + $resolution = $matches[1]; + } else { + preg_match('/_([^_]{0,4}).' . $parts['extension'] . '$/', $file, $matches); + $resolution = @$matches[1]; + } + $type = 'video'; + if (in_array($parts['extension'], $video)) { + $type = 'video'; + } elseif (in_array($parts['extension'], $audio)) { + $type = 'audio'; + } elseif (in_array($parts['extension'], $image) || preg_match('/^(gif|jpg|webp|png|jpeg)/i', $parts['extension'])) { + $type = 'image'; + if (!preg_match('/(thumb|roku)/', $resolution)) { + $resolution = ''; + } + } + $files["{$parts['extension']}{$resolution}"] = [ + 'filename' => "{$parts['filename']}.{$parts['extension']}", + 'path' => $file, + 'url' => $source['url'], + 'url_noCDN' => @$source['url_noCDN'], + '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 = []; + } + + if (!empty($getResolutionFromFilenameArray[$filename])) { + return $getResolutionFromFilenameArray[$filename]; + } + + $res = Video::getResolutionFromFilename($filename); + if (empty($res)) { + if (preg_match('/[_\/]hd[.\/]/i', $filename)) { + $res = 720; + } elseif (preg_match('/[_\/]sd[.\/]/i', $filename)) { + $res = 480; + } elseif (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 = []; + } 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 = []; + 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 = []; + } + + $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 = []; + 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 = [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: ($file_src) " . $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); + if (empty($src)) { + return false; + } + $ws = imagesx($src); + $hs = imagesy($src); + + if ($ws < $wd) { + $dst_x = ($wd - $ws) / 2; + } else { + $dst_x = 0; + } + + if ($hs < $hd) { + $dst_y = ($hd - $hs) / 2; + } else { + $dst_y = 0; + } + + $mapImage = imagecreatetruecolor($wd, $hd); + $bgColor = imagecolorallocate($mapImage, 0, 0, 0); + imagefill($mapImage, 0, 0, $bgColor); + + $tileImg = imagecreatefromjpeg($file_dest); + imagecopy($mapImage, $tileImg, $dst_x, $dst_y, 0, 0, $ws, $hs); + + $saved = imagejpeg($mapImage, $file_dest, $q); + + return $saved; +} + +function im_resizePNG($file_src, $file_dest, $wd, $hd) +{ + $srcImage = imagecreatefrompng($file_src); + $ws = imagesx($srcImage); + $hs = imagesy($srcImage); + + $targetImage = imagecreatetruecolor($wd, $hd); + imagealphablending($targetImage, false); + imagesavealpha($targetImage, true); + + imagecopyresampled( + $targetImage, + $srcImage, + 0, + 0, + 0, + 0, + $wd, + $hd, + $ws, + $hs + ); + + $saved = imagepng($targetImage, $file_dest); + + return $saved; +} + +function im_resizeV3($file_src, $file_dest, $wd, $hd) +{ + return im_resizeV2($file_src, $file_dest, $wd, $hd); // ffmpeg disabled + + _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_gif($file_src, $file_dest, $max_width, $max_height) +{ + if (class_exists('Imagick')) { + $imagick = new Imagick($file_src); + + $format = $imagick->getImageFormat(); + if ($format == 'GIF') { + $imagick = $imagick->coalesceImages(); + do { + $imagick->resizeImage($max_width, $max_height, Imagick::FILTER_BOX, 1); + } while ($imagick->nextImage()); + $imagick = $imagick->deconstructImages(); + $imagick->writeImages($file_dest, true); + } + + $imagick->clear(); + $imagick->destroy(); + } else { + copy($file_src, $file_dest); + } +} + +function im_resize_max_size($file_src, $file_dest, $max_width, $max_height) +{ + $fn = $file_src; + + $extension = strtolower(pathinfo($file_dest, PATHINFO_EXTENSION)); + + if ($extension == 'gif') { + im_resize_gif($file_src, $file_dest, $max_width, $max_height); + @unlink($file_src); + return true; + } + + $tmpFile = getTmpFile() . ".{$extension}"; + 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)) { + //_error_log("convertImage: IMAGETYPE_JPEG"); + $imageTmp = imagecreatefromjpeg($originalImage); + } elseif ($imagetype == IMAGETYPE_PNG || preg_match('/png/i', $ext)) { + //_error_log("convertImage: IMAGETYPE_PNG"); + $imageTmp = imagecreatefrompng($originalImage); + } elseif ($imagetype == IMAGETYPE_GIF || preg_match('/gif/i', $ext)) { + //_error_log("convertImage: IMAGETYPE_GIF"); + $imageTmp = imagecreatefromgif($originalImage); + } elseif ($imagetype == IMAGETYPE_BMP || preg_match('/bmp/i', $ext)) { + //_error_log("convertImage: IMAGETYPE_BMP"); + $imageTmp = imagecreatefrombmp($originalImage); + } elseif ($imagetype == IMAGETYPE_WEBP || preg_match('/webp/i', $ext)) { + //_error_log("convertImage: IMAGETYPE_WEBP"); + $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 ($imageTmp===false) { + _error_log("convertImage: could not create a resource: $originalImage, $outputImage, $quality, $ext " . json_encode(debug_backtrace())); + 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"); + } + } elseif ($extOutput === 'png') { + if (function_exists('imagepng')) { + $response = imagepng($imageTmp, $outputImage, $quality / 10); + } else { + _error_log("convertImage ERROR: function imagepng does not exists"); + } + } elseif ($extOutput === 'webp') { + if (function_exists('imagewebp')) { + $response = imagewebp($imageTmp, $outputImage, $quality); + } else { + _error_log("convertImage ERROR: function imagewebp does not exists"); + } + } elseif ($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") +{ + if ($filename == '.zip') { + return false; + } + global $global; + $obj = new stdClass(); + $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); + $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); + $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); + $paths = Video::getPaths($filename, true); + $destinationFile = "{$paths['path']}{$filename}"; + //$destinationFile = getVideosDir() . "{$filename}"; + _error_log("decideMoveUploadedToVideos: {$filename}"); + $path_info = pathinfo($filename); + if ($type !== "zip" && $path_info['extension'] === 'zip') { + _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); + $paths = Video::getPaths($path_info['filename']); + $dir = $paths['path']; + unzipDirectory($tmp_name, $dir); // unzip it + cleanDirectory($dir); + if (!empty($aws_s3)) { + //$aws_s3->move_uploaded_file($tmp_name, $filename); + } elseif (!empty($bb_b2)) { + $bb_b2->move_uploaded_directory($dir); + } elseif (!empty($ftp)) { + //$ftp->move_uploaded_file($tmp_name, $filename); + } + } else { + _error_log("decideMoveUploadedToVideos: NOT ZIp file {$filename}"); + if (!empty($aws_s3)) { + _error_log("decideMoveUploadedToVideos: S3 {$filename}"); + $aws_s3->move_uploaded_file($tmp_name, $filename); + } elseif (!empty($bb_b2)) { + _error_log("decideMoveUploadedToVideos: B2 {$filename}"); + $bb_b2->move_uploaded_file($tmp_name, $filename); + } elseif (!empty($ftp)) { + _error_log("decideMoveUploadedToVideos: FTP {$filename}"); + $ftp->move_uploaded_file($tmp_name, $filename); + } else { + _error_log("decideMoveUploadedToVideos: Local {$filename}"); + if (!move_uploaded_file($tmp_name, $destinationFile)) { + if (!rename($tmp_name, $destinationFile)) { + if (!copy($tmp_name, $destinationFile)) { + $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, $destinationFile)"; + die(json_encode($obj)); + } + } + } + if (file_exists($destinationFile)) { + _error_log("decideMoveUploadedToVideos: SUCCESS Local {$destinationFile}"); + } else { + _error_log("decideMoveUploadedToVideos: ERROR Local {$destinationFile}"); + } + chmod($destinationFile, 0644); + } + } + sleep(1); + $fsize = @filesize($destinationFile); + _error_log("decideMoveUploadedToVideos: destinationFile {$destinationFile} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")"); + Video::clearCacheFromFilename($filename); + return $destinationFile; +} + +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) +{ + $created = false; + if (substr($path, -1) !== DIRECTORY_SEPARATOR) { + $path = pathinfo($path, PATHINFO_DIRNAME); + } + if (!is_dir($path)) { + //if(preg_match('/getvideoinfo/i', $path)){var_dump(debug_backtrace());} + $created = mkdir($path, 0755, true); + /* + if (!$created) { + _error_log('make_path: could not create the dir ' . json_encode($path) . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + } + */ + } else { + $created = true; + } + return $created; +} + +/** + * for security clean all non secure files from directory + * @param type $dir + * @param type $allowedExtensions + * @return type + */ +function cleanDirectory($dir, $allowedExtensions = ['key', 'm3u8', 'ts', 'vtt', 'jpg', 'gif', 'mp3', 'webm', 'webp']) +{ + $ffs = scandir($dir); + + unset($ffs[array_search('.', $ffs, true)]); + unset($ffs[array_search('..', $ffs, true)]); + + // prevent empty ordered elements + if (count($ffs) < 1) { + return; + } + + foreach ($ffs as $ff) { + $current = $dir . '/' . $ff; + if (is_dir($current)) { + cleanDirectory($current, $allowedExtensions); + } + $path_parts = pathinfo($current); + if (!empty($path_parts['extension']) && !in_array($path_parts['extension'], $allowedExtensions)) { + unlink($current); + } + } +} + +function decideFile_put_contentsToVideos($tmp_name, $filename) +{ + global $global; + $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); + $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); + $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); + if (!empty($bb_b2)) { + $bb_b2->move_uploaded_file($tmp_name, $filename); + } elseif (!empty($aws_s3)) { + $aws_s3->move_uploaded_file($tmp_name, $filename); + } elseif (!empty($ftp)) { + $ftp->move_uploaded_file($tmp_name, $filename); + } else { + $path = Video::getPathToFile($filename); + if (!move_uploaded_file($tmp_name, $path)) { + $obj->msg = "Error on move_uploaded_file({$tmp_name}, {$filename})"; + die(json_encode($obj)); + } + } +} + +function isAnyStorageEnabled() +{ + if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) { + return true; + } elseif ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { + return true; + } elseif ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { + return true; + } elseif ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { + return true; + } + return false; +} + +if (!function_exists('mime_content_type')) { + function mime_content_type($filename) + { + return mime_content_type_per_filename($filename); + } +} + +function fontAwesomeClassName($filename) +{ + $mime_type = mime_content_type_per_filename($filename); + // List of official MIME Types: http://www.iana.org/assignments/media-types/media-types.xhtml + $icon_classes = [ +// 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 = [ + 'txt' => 'text/plain', + 'htm' => 'text/html', + 'html' => 'text/html', + 'php' => 'text/html', + 'css' => 'text/css', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'xml' => 'application/xml', + 'swf' => 'application/x-shockwave-flash', + 'flv' => 'video/x-flv', + // images + 'png' => 'image/png', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'gif' => 'image/gif', + 'bmp' => 'image/bmp', + 'ico' => 'image/vnd.microsoft.icon', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + // archives + 'zip' => 'application/zip', + 'rar' => 'application/x-rar-compressed', + 'exe' => 'application/x-msdownload', + 'msi' => 'application/x-msdownload', + 'cab' => 'application/vnd.ms-cab-compressed', + // audio/video + 'mp3' => 'audio/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'mp4' => 'video/mp4', + 'avi' => 'video/avi', + 'mkv' => 'video/mkv', + 'wav' => 'audio/wav', + 'm4v' => 'video/mpeg', + 'webm' => 'video/webm', + 'wmv' => 'video/wmv', + 'mpg' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'f4v' => 'video/x-flv', + 'm4v' => 'video/m4v', + 'm4a' => 'video/quicktime', + 'm2p' => 'video/quicktime', + 'rm' => 'video/quicktime', + 'vob' => 'video/quicktime', + 'mkv' => 'video/quicktime', + '3gp' => 'video/quicktime', + 'm3u8' => 'application/x-mpegURL', + // adobe + 'pdf' => 'application/pdf', + 'psd' => 'image/vnd.adobe.photoshop', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + // ms office + 'doc' => 'application/msword', + 'rtf' => 'application/rtf', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + // open office + 'odt' => 'application/vnd.oasis.opendocument.text', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + ]; + if (filter_var($filename, FILTER_VALIDATE_URL) === false) { + $ext = pathinfo($filename, PATHINFO_EXTENSION); + } else { + $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION); + } + + if ($ext === 'mp4' || $ext === 'webm') { + $securePlugin = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); + if (!empty($securePlugin)) { + if (method_exists($securePlugin, "useEncoderWatrermarkFromFileName") && $securePlugin->useEncoderWatrermarkFromFileName($filename)) { + return "application/x-mpegURL"; + } + } + } + + if (array_key_exists($ext, $mime_types)) { + return $mime_types[$ext]; + } elseif (function_exists('finfo_open')) { + $finfo = finfo_open(FILEINFO_MIME); + $mimetype = finfo_file($finfo, $filename); + finfo_close($finfo); + return $mimetype; + } else { + return 'application/octet-stream'; + } +} + +function combineFiles($filesArray, $extension = "js") +{ + global $global, $advancedCustom; + + if ($extension == 'js' && isBot()) { + return getCDN() . 'view/js/empty.js'; + } + + $relativeDir = 'videos/cache/' . $extension . '/'; + $cacheDir = $global['systemRootPath'] . $relativeDir; + $str = ''; + $fileName = ''; + foreach ($filesArray as $value) { + $fileName .= $value . filectime($global['systemRootPath'] . $value) . filemtime($global['systemRootPath'] . $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, ['flaggedComments' => false]); + } + if (!is_dir($cacheDir)) { + make_path($cacheDir); + } + $bytes = _file_put_contents($cacheDir . $md5FileName, $str); + if (empty($bytes)) { + _error_log('combineFiles: error on save strlen=' . strlen($str) . ' ' . $cacheDir . $md5FileName . ' cacheDir=' . $cacheDir); + return false; + } + } + + return getURL($relativeDir . $md5FileName); +} + +function combineFilesHTML($filesArray, $extension = "js", $doNotCombine = false) +{ + if (empty($doNotCombine)) { + $jsURL = combineFiles($filesArray, $extension); + } + if ($extension == "js") { + if (empty($jsURL)) { + $str = ''; + foreach ($filesArray as $value) { + $jsURL = getURL($value); + $str .= ''; + } + return $str; + } else { + return ''; + } + } else { + if (empty($jsURL)) { + $str = ''; + foreach ($filesArray as $value) { + $jsURL = getURL($value); + $str .= ''; + } + return $str; + } else { + return ''; + } + } +} + +function local_get_contents($path) +{ + if (function_exists('fopen')) { + $myfile = fopen($path, "r") or die("Unable to open file! [{$path}]"); + $text = fread($myfile, filesize($path)); + fclose($myfile); + return $text; + } +} + +function getSelfUserAgent() +{ + global $global, $AVideoStreamer_UA; + $agent = $AVideoStreamer_UA . "_"; + $agent .= md5($global['salt']); + return $agent; +} + +function isValidM3U8Link($url, $timeout = 3) +{ + if (!isValidURL($url)) { + return false; + } + $content = url_get_contents($url, '', $timeout); + if (!empty($content)) { + if (preg_match('/EXTM3U/', $content)) { + return true; + } + } + return false; +} + +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(DEBUG_BACKTRACE_IGNORE_ARGS))); + } + $agent = getSelfUserAgent(); + + if (empty($ctx)) { + $opts = [ + 'http' => ['header' => "User-Agent: {$agent}\r\n"], + "ssl" => [ + "verify_peer" => false, + "verify_peer_name" => false, + "allow_self_signed" => true, + ], + ]; + if (!empty($timeout)) { + ini_set('default_socket_timeout', $timeout); + $opts['http'] = ['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 []; + } + $files1 = scandir($global['systemRootPath'] . "updatedb"); + $updateFiles = []; + foreach ($files1 as $value) { + preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); + if (!empty($match)) { + if ($config->currentVersionLowerThen($match[1])) { + $updateFiles[] = ['filename' => $match[0], 'version' => $match[1]]; + } + } + } + return $updateFiles; +} + +function thereIsAnyUpdate() +{ + if (!User::isAdmin()) { + return false; + } + $name = 'thereIsAnyUpdate'; + if (!isset($_SESSION['sessionCache'][$name])) { + $files = getUpdatesFilesArray(); + if (!empty($files)) { + _session_start(); + $_SESSION['sessionCache'][$name] = $files; + } + } + return @$_SESSION['sessionCache'][$name]; +} + +function thereIsAnyRemoteUpdate() +{ + if (!User::isAdmin()) { + return false; + } + global $config; + + $cacheName = '_thereIsAnyRemoteUpdate'; + $cache = ObjectYPT::getCache($cacheName, 86400); // 24 hours + if (!empty($cache)) { + return $cache; + } + + //$version = _json_decode(url_get_contents("https://tutorials.avideo.com/version")); + $version = _json_decode(url_get_contents("https://tutorialsavideo.b-cdn.net/version", "", 4)); + if (empty($version)) { + return false; + } + $name = 'thereIsAnyRemoteUpdate'; + if (!isset($_SESSION['sessionCache'][$name])) { + if (!empty($version)) { + _session_start(); + if (version_compare($config->getVersion(), $version->version) === -1) { + $_SESSION['sessionCache'][$name] = $version; + } else { + $_SESSION['sessionCache'][$name] = false; + } + } + } + ObjectYPT::setCache($cacheName, $_SESSION['sessionCache'][$name]); + return $_SESSION['sessionCache'][$name]; +} + +function UTF8encode($data) +{ + global $advancedCustom, $global; + + if (!empty($advancedCustom->utf8Encode)) { + return utf8_encode($data); + } + if (!empty($advancedCustom->utf8Decode)) { + return utf8_decode($data); + } + return $data; +} + +//detect search engine bots +function isBot() +{ + global $_isBot; + if (empty($_SERVER['HTTP_USER_AGENT'])) { + return true; + } + if (isAVideoEncoder()) { + return false; + } + if (isset($_isBot)) { + return $_isBot; + } + $_isBot = false; + // User lowercase string for comparison. + $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']); + // A list of some common words used only for bots and crawlers. + $bot_identifiers = [ + 'bot', + 'slurp', + 'crawler', + 'spider', + 'curl', + 'facebook', + 'fetch', + 'loader', + 'lighthouse', + 'pingdom', + 'gtmetrix', + 'ptst', + 'dmbrowser', + 'dareboost', + ]; + // See if one of the identifiers is in the UA string. + foreach ($bot_identifiers as $identifier) { + if (stripos($user_agent, $identifier) !== false) { + $_isBot = true; + break; + } + } + return $_isBot; +} + +/** + * A function that could get me the last N lines of a log file. + * @param type $filepath + * @param type $lines + * @param type $adaptive + * @return boolean + */ +function tail($filepath, $lines = 1, $adaptive = true, $returnArray = false) +{ + if (!function_exists('mb_strlen')) { + $msg = "AVideoLog::ERROR you need to install the mb_strlen function to make it work, please the command 'sudo apt install php-mbstring'"; + if ($returnArray) { + return [[$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 = []; + foreach ($array as $value) { + $newArray[] = [$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 encryptPasswordV2($uniqueSalt, $password, $noSalt = false) +{ + global $advancedCustom, $global, $advancedCustomUser; + if (!empty($advancedCustomUser->encryptPasswordsWithSalt) && !empty($global['salt']) && empty($noSalt)) { + $password .= $global['salt']; + } + $password .= md5($uniqueSalt); + return md5(hash("whirlpool", sha1($password))); +} + +function encryptPasswordVerifyV2($uniqueSalt, $password, $hash, $encodedPass = false) +{ + global $advancedCustom, $global; + if (!$encodedPass || $encodedPass === 'false') { + //_error_log("encryptPasswordVerify: encrypt"); + $passwordSalted = encryptPasswordV2($uniqueSalt, $password); + // in case you enable the salt later + $passwordUnSalted = encryptPasswordV2($uniqueSalt, $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 isChannelPage() +{ + return strpos($_SERVER["SCRIPT_NAME"], 'view/channel.php') !== false; +} + +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 = []; + + if (isset($parsedUrl['query'])) { + parse_str($parsedUrl['query'], $query); + unset($query[$varname]); + } + + $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 = []; + + if (isset($parsedUrl['query'])) { + parse_str($parsedUrl['query'], $query); + } + $query[$varname] = $value; + $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, $global; + $md5 = md5($global['salt']); + if (preg_match("/{$AVideoStreamer_UA}_{$md5}/", $_SERVER["HTTP_USER_AGENT"])) { + return true; + } + return false; +} + +function isAVideoUserAgent($user_agent = "") +{ + if (empty($user_agent)) { + $user_agent = @$_SERVER['HTTP_USER_AGENT']; + } + if (empty($user_agent)) { + return false; + } + global $AVideoMobileAPP_UA, $AVideoEncoder_UA, $AVideoStreamer_UA, $AVideoStorage_UA, $global; + + // Lavf = ffmpeg + $agents = [$AVideoMobileAPP_UA, $AVideoEncoder_UA, $AVideoStreamer_UA, $AVideoStorage_UA, 'Lavf']; + + foreach ($agents as $value) { + if (preg_match("/{$value}/", $_SERVER["HTTP_USER_AGENT"])) { + 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 = $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 verify($url) +{ + ini_set('default_socket_timeout', 5); + $cacheFile = sys_get_temp_dir() . "/" . md5($url) . "_verify.log"; + $lifetime = 86400; //24 hours + error_log("Verification Start {$url}"); + $verifyURL = "https://search.avideo.com/verify.php?url=" . urlencode($url); + if (!file_exists($cacheFile) || (time() > (filemtime($cacheFile) + $lifetime))) { + error_log("Verification Creating the Cache {$url}"); + $result = url_get_contents($verifyURL, '', 5); + file_put_contents($cacheFile, $result); + } else { + error_log("Verification GetFrom Cache {$url}"); + $result = file_get_contents($cacheFile); + } + error_log("Verification Response ($verifyURL): {$result}"); + return json_decode($result); +} + +function isVerified($url) +{ + $resultV = verify($url); + if (!empty($resultV) && !$resultV->verified) { + error_log("Error on Login not verified"); + return false; + } + return true; +} + +function siteMap() +{ + _error_log("siteMap: start"); + ini_set('memory_limit', '-1'); + ini_set('max_execution_time', 0); + @session_write_close(); + global $global, $advancedCustom; + $global['disableVideoTags'] = 1; + $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"; + TimeLogStart("siteMap getAllUsersThatHasVideos"); + $users = User::getAllUsersThatHasVideos(true); + _error_log("siteMap: getAllUsers " . count($users)); + foreach ($users as $value) { + $xml .= ' + + ' . User::getChannelLink($value['id']) . ' + ' . $date . ' + daily + 0.90 + + '; + } + TimeLogEnd("siteMap getAllUsersThatHasVideos", __LINE__, 0.5); + TimeLogStart("siteMap getAllCategories"); + $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 + + '; + } + TimeLogEnd("siteMap getAllCategories", __LINE__, 0.5); + TimeLogStart("siteMap getAllVideos"); + $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']; + + TimeLogStart("siteMap Video::getPoster $videos_id"); + $img = Video::getPoster($videos_id); + TimeLogEnd("siteMap Video::getPoster $videos_id", __LINE__, 0.5); + + $description = str_replace(['"', "\n", "\r"], ['', ' ', ' '], 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; + } + + TimeLogStart("siteMap Video::getLink $videos_id"); + $loc = Video::getLink($video['id'], $video['clean_title']); + TimeLogEnd("siteMap Video::getLink $videos_id", __LINE__, 0.5); + $title = strip_tags($video['title']); + $description = _substr(strip_tags(br2nl($description)), 0, 2048); + TimeLogStart("siteMap Video::getLinkToVideo $videos_id"); + $player_loc = Video::getLinkToVideo($video['id'], $video['clean_title'], true); + TimeLogEnd("siteMap Video::getLinkToVideo $videos_id", __LINE__, 0.5); + TimeLogStart("siteMap Video::isPublic $videos_id"); + $requires_subscription = Video::isPublic($video['id']) ? "no" : "yes"; + TimeLogEnd("siteMap Video::isPublic $videos_id", __LINE__, 0.5); + TimeLogStart("siteMap Video::getChannelLink $videos_id"); + $uploader_info = User::getChannelLink($video['users_id']); + TimeLogEnd("siteMap Video::getChannelLink $videos_id", __LINE__, 0.5); + TimeLogStart("siteMap Video::getNameIdentificationById $videos_id"); + $uploader = htmlentities(User::getNameIdentificationById($video['users_id'])); + TimeLogEnd("siteMap Video::getNameIdentificationById $videos_id", __LINE__, 0.5); + + $xml .= ' + + ' . $loc . ' + + ' . $img . ' + + + + ' . $duration . ' + ' . $video['views_count'] . ' + ' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00 + yes + ' . $requires_subscription . ' + ' . $uploader . ' + no + + + '; + } + TimeLogEnd("siteMap getAllVideos", __LINE__, 0.5); + $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; + cleanUpAccessControlHeader(); + 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 cleanUpAccessControlHeader() +{ + if (!headers_sent()) { + foreach (headers_list() as $header) { + if (preg_match('/Access-Control-Allow-Origin/i', $header)) { + $parts = explode(':', $header); + header_remove($parts[0]); + } + } + } +} + +function rrmdir($dir) +{ + //if(preg_match('/cache/i', $dir)){_error_log("rrmdir($dir) ". json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));exit;} + + $dir = str_replace(['//', '\\\\'], DIRECTORY_SEPARATOR, $dir); + //_error_log('rrmdir: ' . $dir); + if (empty($dir)) { + _error_log('rrmdir: the dir was empty'); + return false; + } + global $global; + $dir = fixPath($dir); + $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([$dir == getVideosDir(), $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR, preg_match($pattern, $dir)])); + return false; + } + rrmdirCommandLine($dir); + if (is_dir($dir)) { + //_error_log('rrmdir: The Directory was not deleted, trying again ' . $dir); + $objects = scandir($dir); + //_error_log('rrmdir: scandir ' . $dir . ' '. json_encode($objects)); + foreach ($objects as $object) { + if ($object != "." && $object != "..") { + if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) { + rrmdir($dir . DIRECTORY_SEPARATOR . $object); + } else { + unlink($dir . DIRECTORY_SEPARATOR . $object); + } + } + } + if (preg_match('/(\/|^)videos(\/cache)?\/?$/i', $dir)) { + _error_log('rrmdir: do not delete videos or cache folder ' . $dir); + // do not delete videos or cache folder + return false; + } + if (rmdir($dir)) { + return true; + } else { + _error_log('rrmdir: could not delete folder ' . $dir); + return false; + } + } else { + //_error_log('rrmdir: The Directory does not exists '.$dir); + return true; + } +} + +function rrmdirCommandLine($dir, $async = false) +{ + if (is_dir($dir)) { + if (isWindows()) { + $command = ('rd /s /q ' . $dir); + } else { + $command = ('rm -fR ' . $dir); + } + + if ($async) { + return execAsync($command); + } else { + return exec($command); + } + } +} + +/** + * 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 = [ + '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'] = []; + $_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']; + + $img = Video::getPoster($videos_id); + + $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']; + $img = Video::getPoster($videos_id); + + $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 = [ + '/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'] = []; + } + $global['start'][$name] = $time; + return $name; +} + +function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) +{ + global $global; + if (!empty($global['noDebug']) || empty($global['start'][$name])) { + return false; + } + if (!empty($global['TimeLogLimit'])) { + $TimeLogLimit = $global['TimeLogLimit']; + } + $time = microtime(); + $time = explode(' ', $time); + $time = $time[1] + $time[0]; + $finish = $time; + $total_time = round(($finish - $global['start'][$name]), 4); + if (empty($global['noDebugSlowProcess']) && $total_time > $TimeLogLimit) { + _error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}"); + } + TimeLogStart($name); +} + +class AVideoLog +{ + public static $DEBUG = 0; + public static $WARNING = 1; + public static $ERROR = 2; + public static $SECURITY = 3; + public static $SOCKET = 4; +} + +function _error_log_debug($message, $show_args = false) +{ + $array = debug_backtrace(); + $message .= PHP_EOL; + foreach ($array as $value) { + $message .= "function: {$value['function']} Line: {{$value['line']}} File: {{$value['file']}}" . PHP_EOL; + if ($show_args) { + $message .= print_r($value['args'], true) . PHP_EOL; + } + } + _error_log(PHP_EOL . '***' . PHP_EOL . $message . '***'); +} + +function _error_log($message, $type = 0, $doNotRepeat = false) +{ + if (empty($doNotRepeat)) { + // do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error + $doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']); + } + if ($doNotRepeat) { + return false; + } + global $global; + if (!empty($global['noDebug']) && $type == 0) { + return false; + } + if (!is_string($message)) { + $message = json_encode($message); + } + $prefix = "AVideoLog::"; + switch ($type) { + case AVideoLog::$DEBUG: + $prefix .= "DEBUG: "; + break; + case AVideoLog::$WARNING: + $prefix .= "WARNING: "; + break; + case AVideoLog::$ERROR: + $prefix .= "ERROR: "; + break; + case AVideoLog::$SECURITY: + $prefix .= "SECURITY: "; + break; + case AVideoLog::$SOCKET: + $prefix .= "SOCKET: "; + break; + } + error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}"); +} + +function postVariables($url, $array, $httpcodeOnly = true, $timeout = 10) +{ + if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { + return false; + } + $array = object_to_array($array); + $ch = curl_init($url); + if ($httpcodeOnly) { + @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers + @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body + } else { + curl_setopt($curl, CURLOPT_USERAGENT, getSelfUserAgent()); + } + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. + curl_setopt($ch, CURLOPT_TIMEOUT, $timeout + 1); //The maximum number of seconds to allow cURL functions to execute. + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $array); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + + // execute! + $response = curl_exec($ch); + if ($httpcodeOnly) { + $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + // close the connection, release resources used + curl_close($ch); + if ($httpcode == 200) { + return true; + } + return $httpcode; + } else { + curl_close($ch); + return $response; + } +} + +function _session_start(array $options = []) +{ + try { + if (!empty($_GET['PHPSESSID'])) { + if ($_GET['PHPSESSID'] !== session_id()) { + if (session_status() != PHP_SESSION_NONE) { + @session_write_close(); + } + session_id($_GET['PHPSESSID']); + //_error_log("captcha: session_id changed to " . $_GET['PHPSESSID']); + } + unset($_GET['PHPSESSID']); + return @session_start($options); + } elseif (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()) { + //_error_log('MySQL Connect '. json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $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()) { + //_error_log('MySQL Closed '. json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $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 (!empty($global['mysqli']) && 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; + $lockFile = getVideosDir() . '.clearCache.lock'; + if (file_exists($lockFile) && filectime($lockFile) > strtotime('-5 minutes')) { + _error_log('clearCache is in progress ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + return false; + } + $start = microtime(true); + _error_log('clearCache starts '); + file_put_contents($lockFile, time()); + + $dir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; + $tmpDir = ObjectYPT::getCacheDir('firstPage'); + $parts = explode('firstpage', $tmpDir); + + if ($firstPageOnly || !empty($_REQUEST['FirstPage'])) { + $tmpDir = $parts[0] . 'firstpage' . DIRECTORY_SEPARATOR; + //var_dump($tmpDir);exit; + $dir .= "firstPage" . DIRECTORY_SEPARATOR; + } else { + $tmpDir = $parts[0]; + } + + //_error_log('clearCache 1: '.$dir); + rrmdir($dir); + rrmdir($tmpDir); + ObjectYPT::deleteCache("getEncoderURL"); + unlink($lockFile); + $end = microtime(true) - $start; + _error_log("clearCache end in {$end} seconds"); + return true; +} + +function clearAllUsersSessionCache() +{ + sendSocketMessageToAll(time(), 'socketClearSessionCache'); +} + +function clearFirstPageCache() +{ + return clearCache(true); +} + +function getUsageFromFilename($filename, $dir = "") +{ + global $global; + + if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage + return 0; + } + + if (empty($dir)) { + $paths = Video::getPaths($filename); + $dir = $paths['path']; + } + $dir = addLastSlash($dir); + $totalSize = 0; + _error_log("getUsageFromFilename: start {$dir}{$filename} " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + //$files = glob("{$dir}{$filename}*"); + $paths = Video::getPaths($filename); + + if (is_dir($paths['path'])) { + $files = [$paths['path']]; + } else { + $files = globVideosDir($filename); + } + //var_dump($paths, $files, $filename);exit; + session_write_close(); + $filesProcessed = []; + if (empty($files)) { + _error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + make_path($dir); + file_put_contents("{$dir}{$filename}.notfound", time()); + $totalSize = 10; + } else { + foreach ($files as $f) { + if (strpos($f, '.size.lock') !== false) { + continue; + } + if (is_dir($f)) { + $dirSize = getDirSize($f, true); + _error_log("getUsageFromFilename: is Dir dirSize={$dirSize} " . humanFileSize($dirSize) . " {$f}"); + $totalSize += $dirSize; + $minDirSize = 4000000; + $isEnabled = AVideoPlugin::isEnabledByName('YPTStorage'); + $isEnabledCDN = AVideoPlugin::getObjectDataIfEnabled('CDN'); + $isEnabledS3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); + if (!empty($isEnabledCDN) && $isEnabledCDN->enable_storage) { + $v = Video::getVideoFromFileName($filename); + if (!empty($v)) { + $size = CDNStorage::getRemoteDirectorySize($v['id']); + _error_log("getUsageFromFilename: CDNStorage found $size " . humanFileSize($size)); + $totalSize += $size; + } + } + if ($dirSize < $minDirSize && $isEnabled) { + // probably the HLS file is hosted on the YPTStorage + $info = YPTStorage::getFileInfo($filename); + if (!empty($info->size)) { + _error_log("getUsageFromFilename: found info on the YPTStorage " . print_r($info, true)); + $totalSize += $info->size; + } else { + _error_log("getUsageFromFilename: there is no info on the YPTStorage " . print_r($info, true)); + } + } elseif ($dirSize < $minDirSize && $isEnabledS3) { + // probably the HLS file is hosted on the S3 + $size = $isEnabledS3->getFilesize($filename); + if (!empty($size)) { + _error_log("getUsageFromFilename: found info on the AWS_S3 {$filename} {$size}"); + $totalSize += $size; + } else { + _error_log("getUsageFromFilename: there is no info on the AWS_S3 {$filename} {$size}"); + } + } else { + if (!($dirSize < $minDirSize)) { + _error_log("getUsageFromFilename: does not have the size to process $dirSize < $minDirSize"); + } + if (!$isEnabled) { + _error_log("getUsageFromFilename: YPTStorage is disabled"); + } + if (!$isEnabledCDN) { + _error_log("getUsageFromFilename: CDN Storage is disabled"); + } + if (!$isEnabledS3) { + _error_log("getUsageFromFilename: S3 Storage is disabled"); + } + } + } 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, $forceNew = false) +{ + global $_getDirSize; + + if (!isset($_getDirSize)) { + $_getDirSize = []; + } + if (empty($forceNew) && isset($_getDirSize[$dir])) { + return $_getDirSize[$dir]; + } + + _error_log("getDirSize: start {$dir}"); + + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + $return = foldersize($dir); + $_getDirSize[$dir] = $return; + return $return; + } 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; + $_getDirSize[$dir] = $return; + return $return; + } 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]); + $_getDirSize[$dir] = $return; + return $return; + } + + _error_log("getDirSize: ERROR on pregmatch {$output[0]}"); + $return = 0; + $_getDirSize[$dir] = $return; + return $return; + } + } +} + +function foldersize($path) +{ + $total_size = 0; + $files = scandir($path); + $cleanPath = rtrim($path, '/') . '/'; + + foreach ($files as $t) { + if ($t <> "." && $t <> "..") { + $currentFile = $cleanPath . $t; + if (is_dir($currentFile)) { + $size = foldersize($currentFile); + $total_size += $size; + } else { + $size = filesize($currentFile); + $total_size += $size; + } + } + } + + return $total_size; +} + +function getDiskUsage() +{ + global $global; + $dir = getVideosDir() . ""; + $obj = new stdClass(); + $obj->disk_free_space = disk_free_space($dir); + $obj->disk_total_space = disk_total_space($dir); + $obj->videos_dir = getDirSize($dir); + $obj->disk_used = $obj->disk_total_space - $obj->disk_free_space; + $obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir; + $obj->disk_free_space_human = humanFileSize($obj->disk_free_space); + $obj->disk_total_space_human = humanFileSize($obj->disk_total_space); + $obj->videos_dir_human = humanFileSize($obj->videos_dir); + $obj->disk_used_human = humanFileSize($obj->disk_used); + $obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other); + // percentage of disk used + $obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100); + $obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100); + $obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100); + + return $obj; +} + +function unsetSearch() +{ + unset($_GET['searchPhrase'], $_POST['searchPhrase'], $_GET['search'], $_GET['q']); +} + +function encrypt_decrypt($string, $action) +{ + global $global; + $output = false; + + $encrypt_method = "AES-256-CBC"; + $secret_key = 'This is my secret key'; + $secret_iv = $global['systemRootPath']; + while (strlen($secret_iv) < 16) { + $secret_iv .= $global['systemRootPath']; + } + if (empty($secret_iv)) { + $secret_iv = '1234567890abcdef'; + } + // 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; + $obj->timezone = date_default_timezone_get(); + + 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; + } + $old_timezone = date_default_timezone_get(); + date_default_timezone_set($obj->timezone); + $time = time(); + date_default_timezone_set($old_timezone); + 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 = ['pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks']; + if (in_array($type, $notShowTo)) { + return false; + } else { + return true; + } +} + +function _dieAndLogObject($obj, $prefix = "") +{ + $objString = json_encode($obj); + _error_log($prefix . $objString); + die($objString); +} + +function isAVideoPlayer() +{ + if (isVideo() || isSerie()) { + return true; + } + return false; +} + +function isFirstPage() +{ + global $isFirstPage, $global; + return !empty($isFirstPage) || getSelfURI() === "{$global['webSiteRootURL']}view/"; +} + +function isVideo() +{ + global $isModeYouTube, $global; + if (!empty($global['doNotLoadPlayer'])) { + return false; + } + return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive(); +} + +function isVideoTypeEmbed() +{ + global $isVideoTypeEmbed; + + if (isVideo() && !empty($isVideoTypeEmbed) && $videos_id = getVideos_id()) { + return $videos_id; + } + + return false; +} + +function isAudio() +{ + global $isAudio; + return !empty($isAudio); +} + +function isSerie() +{ + return isPlayList(); +} + +function isPlayList() +{ + global $isPlayList, $isSerie; + return !empty($isSerie) || !empty($isPlayList); +} + +function isChannel() +{ + global $isChannel; + if (!empty($isChannel) && !isVideo()) { + $user_id = 0; + if (empty($_GET['channelName'])) { + if (User::isLogged()) { + $user_id = User::getId(); + } else { + return false; + } + } else { + $_GET['channelName'] = xss_esc($_GET['channelName']); + $user = User::getChannelOwner($_GET['channelName']); + if (!empty($user)) { + $user_id = $user['id']; + } else { + $user_id = $_GET['channelName']; + } + } + return $user_id; + } + return false; +} + +function isEmbed() +{ + global $isEmbed, $global; + if (!empty($global['doNotLoadPlayer'])) { + return false; + } + return !empty($isEmbed); +} + +function isWebRTC() +{ + global $isWebRTC, $global; + if (!empty($global['doNotLoadPlayer'])) { + return false; + } + return !empty($isWebRTC); +} + +function isLive() +{ + global $isLive, $global; + if (!empty($global['doNotLoadPlayer'])) { + return false; + } + if (class_exists('LiveTransmition') && class_exists('Live')) { + $livet = LiveTransmition::getFromRequest(); + if (!empty($livet)) { + setLiveKey($livet['key'], Live::getLiveServersIdRequest(), @$_REQUEST['live_index']); + $isLive = 1; + } + } + if (!empty($isLive)) { + $live = getLiveKey(); + if (empty($live)) { + $live = ['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 = ['key' => $key, 'live_servers_id' => intval($live_servers_id), 'live_index' => $live_index, 'cleanKey' => $cleanKey]; + return $getLiveKey; +} + +function isVideoPlayerHasProgressBar() +{ + if (isWebRTC()) { + return false; + } + if (isLive()) { + $obj = AVideoPlugin::getObjectData('Live'); + if (empty($obj->disableDVR)) { + return true; + } + } elseif (isAVideoPlayer()) { + return true; + } + return false; +} + +function isHLS() +{ + global $video, $global; + if (isLive()) { + return true; + } elseif (!empty($video) && $video['type'] == 'video' && file_exists(Video::getPathToFile("{$video['filename']}/index.m3u8"))) { + return true; + } + return false; +} + +function getRedirectUri() +{ + if (!empty($_GET['redirectUri'])) { + return $_GET['redirectUri']; + } + if (!empty($_SESSION['redirectUri'])) { + return $_SESSION['redirectUri']; + } + if (!empty($_SERVER["HTTP_REFERER"])) { + return $_SERVER["HTTP_REFERER"]; + } + return getRequestURI(); +} + +function setRedirectUri($redirectUri) +{ + _session_start(); + $_SESSION['redirectUri'] = $redirectUri; +} + +function redirectIfRedirectUriIsSet() +{ + $redirectUri = false; + if (!empty($_GET['redirectUri'])) { + if (isSameDomainAsMyAVideo($_GET['redirectUri'])) { + $redirectUri = $_GET['redirectUri']; + } + } + if (!empty($_SESSION['redirectUri'])) { + if (isSameDomainAsMyAVideo($_SESSION['redirectUri'])) { + $redirectUri = $_SESSION['redirectUri']; + } + _session_start(); + unset($_SESSION['redirectUri']); + } + + if (!empty($redirectUri)) { + header("Location: {$_SESSION['redirectUri']}"); + exit; + } +} + +function getRedirectToVideo($videos_id) +{ + $redirectUri = getRedirectUri(); + $isEmbed = 0; + if (stripos($redirectUri, "embed") !== false) { + $isEmbed = 1; + } + $video = Video::getVideoLight($videos_id); + if (empty($video)) { + return false; + } + return Video::getLink($videos_id, $video['clean_title'], $isEmbed); +} + +function getRequestURI() +{ + if (empty($_SERVER['REQUEST_URI'])) { + return ""; + } + return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; +} + +function getSelfURI() +{ + if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) { + return ""; + } + $queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']); + $phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']); + $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError"; + $url = rtrim($url, '?'); + return $url; +} + +function isSameVideoAsSelfURI($url) +{ + return URLsAreSameVideo($url, getSelfURI()); +} + +function URLsAreSameVideo($url1, $url2) +{ + $videos_id1 = getVideoIDFromURL($url1); + $videos_id2 = getVideoIDFromURL($url2); + if (empty($videos_id1) || empty($videos_id2)) { + return false; + } + return $videos_id1 === $videos_id2; +} + +function getVideos_id() +{ + global $_getVideos_id; + $videos_id = false; + if (isset($_getVideos_id) && is_int($_getVideos_id)) { + return $_getVideos_id; + } + if (isVideo()) { + $videos_id = getVideoIDFromURL(getSelfURI()); + if (empty($videos_id) && !empty($_REQUEST['videoName'])) { + $video = Video::getVideoFromCleanTitle($_REQUEST['videoName']); + if (!empty($video)) { + $videos_id = $video['id']; + } + } + setVideos_id($videos_id); + } + if (empty($videos_id) && !empty($_REQUEST['playlists_id'])) { + AVideoPlugin::loadPlugin('PlayLists'); + $video = PlayLists::isPlayListASerie($_REQUEST['playlists_id']); + if (!empty($video)) { + $videos_id = $video['id']; + } + } + + if (empty($videos_id) && !empty($_REQUEST['v'])) { + $videos_id = $_REQUEST['v']; + } + + $videos_id = videosHashToID($videos_id); + + return $videos_id; +} + +function setVideos_id($videos_id) +{ + global $_getVideos_id; + $_getVideos_id = $videos_id; +} + +function getPlaylists_id() +{ + global $_isPlayList; + if (!isset($_isPlayList)) { + $_isPlayList = false; + if (isPlayList()) { + $_isPlayList = intval(@$_GET['playlists_id']); + if (empty($_isPlayList)) { + $videos_id = getVideos_id(); + if (empty($videos_id)) { + $_isPlayList = false; + } else { + $v = Video::getVideoLight($videos_id); + if (empty($v) || empty($v['serie_playlists_id'])) { + $_isPlayList = false; + } else { + $_isPlayList = $v['serie_playlists_id']; + } + } + } + } + } + return $_isPlayList; +} + +function isVideoOrAudioNotEmbed() +{ + if (!isVideo()) { + return false; + } + $videos_id = getVideos_id(); + if (empty($videos_id)) { + return false; + } + $v = Video::getVideoLight($videos_id); + if (empty($v)) { + return false; + } + $types = ['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|videoEmbed|v|vEmbed|article|articleEmbed)\/([0-9]+)/', $url, $matches)) { + if (is_numeric($matches[1])) { + return intval($matches[1]); + } elseif (is_numeric($matches[2])) { + return intval($matches[2]); + } + } + 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']; + } + } + } + if (preg_match("/v=(\.[0-9a-zA-Z_-]+)/", $url, $matches)) { + return hashToID($matches[1]); + } + if (preg_match('/\/(video|videoEmbed|v|vEmbed|article|articleEmbed)\/(\.[0-9a-zA-Z_-]+)/', $url, $matches)) { + return hashToID($matches[2]); + } + 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 (['\'', '-'] 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 = []) +{ + global $config; + + $allowedTypes = $parameters["allowedTypes"] ?? null; + $addAutoPrefix = $parameters["addAutoPrefix"] ?? true; + $addCategory = $parameters["addCategory"] ?? true; + + $parts = []; + + 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 = ['q', 'searchPhrase', 'search']; + foreach ($searchIdex as $value) { + unset($_REQUEST[$value], $_POST[$value], $_GET[$value]); + } +} + +function reloadSearchVar() +{ + global $cleanSearchHistory; + $_REQUEST['search'] = $cleanSearchHistory; + if (empty($_GET['search'])) { + $_GET['search'] = $cleanSearchHistory; + } + if (empty($_POST['search'])) { + $_POST['search'] = $cleanSearchHistory; + } +} + +function wget($url, $filename, $debug = false) +{ + if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) { + return false; + } + if (wgetIsLocked($url)) { + if ($debug) { + _error_log("wget: ERROR the url is already downloading $url, $filename"); + } + return false; + } + wgetLock($url); + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + $content = @file_get_contents($url); + if (!empty($content) && file_put_contents($filename, $content) > 100) { + wgetRemoveLock($url); + return true; + } + wgetRemoveLock($url); + return false; + } + $cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate"; + if ($debug) { + _error_log("wget Start ({$cmd}) "); + } + //echo $cmd; + exec($cmd); + wgetRemoveLock($url); + if (!file_exists($filename)) { + _error_log("wget: ERROR the url does not download $url, $filename"); + return false; + } + if ($_SERVER['SCRIPT_NAME'] !== '/plugin/Live/m3u8.php' && empty(filesize($filename))) { + _error_log("wget: ERROR the url download but is empty $url, $filename"); + return true; + } + return false; +} + +/** + * Copy remote file over HTTP one small chunk at a time. + * + * @param $infile The full URL to the remote file + * @param $outfile The path where to save the file + */ +function copyfile_chunked($infile, $outfile) +{ + $chunksize = 10 * (1024 * 1024); // 10 Megs + + /** + * parse_url breaks a part a URL into it's parts, i.e. host, path, + * query string, etc. + */ + $parts = parse_url($infile); + $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5); + $o_handle = fopen($outfile, 'wb'); + + if ($i_handle == false || $o_handle == false) { + return false; + } + + if (!empty($parts['query'])) { + $parts['path'] .= '?' . $parts['query']; + } + + /** + * Send the request to the server for the file + */ + $request = "GET {$parts['path']} HTTP/1.1\r\n"; + $request .= "Host: {$parts['host']}\r\n"; + $request .= "User-Agent: Mozilla/5.0\r\n"; + $request .= "Keep-Alive: 115\r\n"; + $request .= "Connection: keep-alive\r\n\r\n"; + fwrite($i_handle, $request); + + /** + * Now read the headers from the remote server. We'll need + * to get the content length. + */ + $headers = []; + 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'] = []; + } + if (empty($_SESSION['getTmpDir'][$subdir . "_"])) { + if (empty($global['tmpDir'])) { + $tmpDir = sys_get_temp_dir(); + if (empty($tmpDir) || !_isWritable($tmpDir)) { + $tmpDir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; + } + $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $tmpDir = "{$tmpDir}{$subdir}"; + } else { + $tmpDir = $global['tmpDir']; + } + $tmpDir = addLastSlash($tmpDir); + if (!is_dir($tmpDir)) { + mkdir($tmpDir, 0755, true); + } + _session_start(); + $_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir; + } else { + $tmpDir = $_SESSION['getTmpDir'][$subdir . "_"]; + } + return $tmpDir; +} + +function getTmpFile() +{ + return getTmpDir("tmpFiles") . uniqid(); +} + +function getMySQLDate() +{ + global $global; + $sql = "SELECT now() as time FROM configurations LIMIT 1"; + // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about + $res = sqlDAL::readSql($sql); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + $row = $data['time']; + } else { + $row = false; + } + return $row; +} + +function _file_put_contents($filename, $data, $flags = 0, $context = null) +{ + make_path($filename); + return file_put_contents($filename, $data, $flags, $context); +} + +function html2plainText($html) +{ + $text = strip_tags($html); + $text = str_replace(['\\', "\n", "\r", '"'], ['', ' ', ' ', ''], 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 (empty($json) && json_last_error()) { + //_error_log("_json_encode: Error 1 Found: " . json_last_error_msg()); + $object = object_to_array($object); + $json = json_encode($object); + if (empty($json) && 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: {$object} " . json_last_error_msg() . PHP_EOL . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $objectEncoded = $object; + array_walk_recursive($objectEncoded, function (&$item) { + if (is_string($item)) { + $item = utf8_encode($item); + } + }); + $json = json_encode($objectEncoded); + if (empty($json) && 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 (empty($json) && 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(["\r", "\n"], ['\r', '\n'], $object); + return json_decode($object); + } else { + return $json; + } +} + +// this will make sure the strring will fits in the database field +function _substr($string, $start, $length = null) +{ + // make sure the name is not chunked in case of multibyte string + if (function_exists("mb_strcut")) { + return mb_strcut($string, $start, $length, "UTF-8"); + } else { + return substr($string, $start, $length); + } +} + +function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") +{ + global $global, $advancedCustom; + if ($total < 2) { + return ''; + } + + if (empty($page)) { + $page = getCurrentPage(); + } + + $isInfiniteScroll = !empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector); + + $uid = md5($link); + + if ($total < $maxVisible) { + $maxVisible = $total; + } + if (empty($link)) { + $link = getSelfURI(); + if (preg_match("/(current=[0-9]+)/i", $link, $match)) { + $link = str_replace($match[1], "current={page}", $link); + } else { + //$link = addQueryStringParameter($link, 'current', '{page}'); + $link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}'; + } + } + + $class = ''; + if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) { + $class = "infiniteScrollPagination{$uid} hidden"; + } + + if ($isInfiniteScroll && $page > 1) { + if (preg_match("/\{page\}/", $link, $match)) { + $pageForwardLink = str_replace("{page}", $page + 1, $link); + } else { + $pageForwardLink = addQueryStringParameter($link, 'current', $page + 1); + } + + return ""; + } + + $pag = ' '; + + if ($isInfiniteScroll) { + $content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php'); + $pag .= str_replace( + ['$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'], + [$uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector], + $content + ); + } + + return $pag; +} + +function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv", $videoLengthInSeconds = 0) +{ + 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, $unlockPassword='', $namespace='') +{ + global $global; + if (!empty($unlockPassword)) { + if (empty($namespace)) { + $namespace = $_SERVER["SCRIPT_FILENAME"]; + } + if (!empty($_REQUEST['unlockPassword'])) { + if ($_REQUEST['unlockPassword'] == $unlockPassword) { + _session_start(); + if (!isset($_SESSION['user']['forbiddenPage'])) { + $_SESSION['user']['forbiddenPage'] = []; + } + $_SESSION['user']['forbiddenPage'][$namespace] = $_REQUEST['unlockPassword']; + } + } + if (!empty($_SESSION['user']['forbiddenPage'][$namespace]) && $unlockPassword === $_SESSION['user']['forbiddenPage'][$namespace]) { + return true; + } + } + $_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)) { + var_dump($error); + _error_log($error, AVideoLog::$ERROR); + header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); + if (!User::isAdmin()) { + if (!preg_match('/json\.php$/i', $_SERVER['PHP_SELF'])) { + echo '' . PHP_EOL; + include $global['systemRootPath'] . 'view/maintanance.html'; + } else { + $o = new stdClass(); + $o->error = true; + $o->msg = __('Under Maintanance'); + echo json_encode($o); + } + } else { + echo '
';
+            var_dump($error);
+            var_dump(debug_backtrace());
+            echo '
'; + } + 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() +{ + return ''; //TODO check why it is slowing down + 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; + $domain = preg_replace('/:[0-9]+$/', '', $domain); + $_getDomain = $domain; + return $domain; +} + +function getHostOnlyFromURL($url) +{ + $parse = parse_url($url); + $domain = $parse['host']; + $domain = str_replace("www.", "", $domain); + $domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain; + $domain = preg_replace('/:[0-9]+$/', '', $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( + ['[', ']', ' '], + ['', '', '_'], + $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 = [ + 'expires' => $expires, + 'path' => '/', + 'domain' => getDomain(), + 'secure' => true, + 'httponly' => false, + 'samesite' => 'None', ]; + return setcookie($cookieName, $value, $cookie_options); + } else { + return setcookie($cookieName, $value, (int) $expires, "/", getDomain()); + } +} + +function _unsetcookie($cookieName) +{ + $domain = getDomain(); + $expires = strtotime("-10 years"); + $value = ''; + _setcookie($cookieName, $value, $expires); + setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires); + setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain)); + setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain); + setcookie($cookieName, $value, (int) $expires, "/", "." . $domain); + setcookie($cookieName, $value, (int) $expires, "/", $domain); + setcookie($cookieName, $value, (int) $expires, "/"); + setcookie($cookieName, $value, (int) $expires); + unset($_COOKIE[$cookieName]); +} + +/** + * This function is not 100% but try to tell if the site is in an iFrame + * @global type $global + * @return boolean + */ +function isIframeInDifferentDomain() +{ + global $global; + if (!isIframe()) { + return false; + } + return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']); +} + +function isIframe() +{ + global $global; + if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') { + return true; + } + if (empty($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == $global['webSiteRootURL'] || str_replace('view/', '', getSelfURI()) == $global['webSiteRootURL']) { + return false; + } + return true; +} + +function getCredentialsURL() +{ + global $global; + return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1"; +} + +function gotToLoginAndComeBackHere($msg) +{ + global $global; + if (User::isLogged()) { + forbiddenPage($msg); + exit; + } + if (!empty($_GET['comebackhere'])) { + return false; + } + header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1"); + exit; +} + +function setAlertMessage($msg, $type = "msg") +{ + _session_start(); + $_SESSION['YPTalertMessage'][] = [$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]] = []; + } + $_GET[$value[1]][] = $value[0]; + } + } + _session_start(); + unset($_SESSION['YPTalertMessage']); + } + + $joinString = ['error', 'msg', 'success']; + foreach ($joinString as $value) { + if (!empty($_GET[$value]) && is_array($_GET[$value])) { + $_GET[$value] = array_unique($_GET[$value]); + $newStr = []; + foreach ($_GET[$value] as $value2) { + if (!empty($value2)) { + $newStr[] = $value2; + } + } + $_GET[$value] = implode("
", $newStr); + } + } + + $check = ['error', 'msg', 'success', 'toast']; + foreach ($check as $value) { + if (!empty($_GET[$value])) { + if (is_array($_GET[$value])) { + $newStr = []; + 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'] = [$_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) +{ + $res = intval($res); + if ($res >= 720 && $res < 1080) { + return "HD"; + } elseif ($res >= 1080 && $res < 1440) { + return "FHD"; + } elseif ($res >= 1440 && $res < 2160) { + return "FHD+"; + } elseif ($res >= 2160 && $res < 4320) { + return "4K"; + } elseif ($res >= 4320) { + return "8K"; + } else { + return ''; + } +} + +function getResolutionTextRoku($res) +{ + $res = intval($res); + if ($res >= 720 && $res < 1080) { + return "HD"; + } elseif ($res >= 1080 && $res < 2160) { + return "FHD"; + } elseif ($res >= 2160) { + return "UHD"; + } else { + return 'SD'; + } +} + +// just realize the readdir is a lot faster then glob +function _glob($dir, $pattern) +{ + global $_glob; + if (empty($dir)) { + return []; + } + if (empty($_glob)) { + $_glob = []; + } + $name = md5($dir . $pattern); + if (isset($_glob[$name])) { + return $_glob[$name]; + } + $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $array = []; + if (is_dir($dir) && $handle = opendir($dir)) { + $count = 0; + while (false !== ($file_name = readdir($handle))) { + if ($file_name == '.' || $file_name == '..') { + continue; + } + //_error_log("_glob: {$dir}{$file_name} [$pattern]"); + //var_dump($pattern, $file_name, preg_match($pattern, $file_name)); + if (preg_match($pattern, $file_name)) { + $array[] = "{$dir}{$file_name}"; + } + } + closedir($handle); + } + $_glob[$name] = $array; + return $array; +} + +function globVideosDir($filename, $filesOnly = false) +{ + global $global; + if (empty($filename)) { + return []; + } + $cleanfilename = Video::getCleanFilenameFromFile($filename); + $paths = Video::getPaths($filename); + + $dir = $paths['path']; + + if (is_dir($dir . $filename)) { + $dir = $dir . $filename; + $cleanfilename = ''; + } + + $pattern = "/{$cleanfilename}.*"; + if (!empty($filesOnly)) { + $formats = getValidFormats(); + $pattern .= ".(" . implode("|", $formats) . ")"; + } + $pattern .= "/"; + //var_dump($dir, $pattern); + return _glob($dir, $pattern); +} + +function getValidFormats() +{ + $video = ['webm', 'mp4', 'm3u8']; + $audio = ['mp3', 'ogg']; + $image = ['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['error'])) { + $msg = 'downloadHLS was not possible'; + if (User::isAdmin()) { + $msg .= '
' . "m3u8ToMP4($filepath) return empty
" . nl2br($output['msg']); + } + _error_log("downloadHLS: m3u8ToMP4($filepath) return empty"); + die($msg); + } + + $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['error'])) { + $msg = 'playHLSasMP4 was not possible'; + if (User::isAdmin()) { + $msg .= '
' . "m3u8ToMP4($filepath) return empty
" . nl2br($output['msg']); + } + die($msg); + } + + $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}"; + $msg = ''; + $error = true; + make_path($outputpath); + if (empty($outputfilename)) { + $msg = "downloadHLS: empty outputfilename {$outputfilename}"; + _error_log($msg); + return ['error' => $error, 'msg' => $msg]; + } + _error_log("downloadHLS: m3u8ToMP4($input)"); + //var_dump(!preg_match('/^http/i', $input), filesize($input), preg_match('/.m3u8$/i', $input)); + $ism3u8 = preg_match('/.m3u8$/i', $input); + if (!preg_match('/^http/i', $input) && (filesize($input) <= 10 || $ism3u8)) { // dummy file + $filepath = escapeshellcmd(pathToRemoteURL($input, true, true)); + if ($ism3u8 && !preg_match('/.m3u8$/i', $filepath)) { + $filepath = addLastSlash($filepath) . 'index.m3u8'; + } + + $token = getToken(60); + $filepath = addQueryStringParameter($filepath, 'globalToken', $token); + } else { + $filepath = escapeshellcmd($input); + } + + if (is_dir($filepath)) { + $filepath = addLastSlash($filepath) . 'index.m3u8'; + } + + $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}"; + $msg1 = "downloadHLS: Exec Command ({$command})"; + _error_log($msg1); + //var_dump($outputfilename, $command, $_GET, $filepath);exit; + exec($command . " 2>&1", $output, $return); + if (!empty($return)) { + $msg2 = "downloadHLS: ERROR 1 " . implode(PHP_EOL, $output); + _error_log($msg2); + + $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);exit; + exec($command . " 2>&1", $output, $return); + if (!empty($return)) { + $msg3 = "downloadHLS: ERROR 2 " . implode(PHP_EOL, $output); + $finalMsg = $msg1 . PHP_EOL . $msg2 . PHP_EOL . $msg3; + _error_log($msg3); + return ['error' => $error, 'msg' => $finalMsg]; + } + } + } else { + $msg = "downloadHLS: outputpath already exists ({$outputpath})"; + _error_log($msg); + } + $error = false; + return ['error' => $error, 'msg' => $msg, '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 [ + "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($destination) || empty($_POST[$postIndex])) { + return false; + } + $fileData = base64DataToImage($_POST[$postIndex]); + + $path_parts = pathinfo($destination); + $tmpDestination = $destination; + $extension = strtolower($path_parts['extension']); + if ($extension!=='png') { + $tmpDestination = $destination.'.png'; + } + + $saved = _file_put_contents($tmpDestination, $fileData); + + if ($saved) { + if ($extension!=='png') { + convertImage($tmpDestination, $destination, 100); + unlink($tmpDestination); + } + } + //var_dump($saved, $tmpDestination, $destination, $extension);exit; + return $saved; +} + +function get_ffmpeg($ignoreGPU = false) +{ + global $global; + $complement = ''; + //$complement = ' -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 . $complement; +} + +function isHTMLPage($url) +{ + if (preg_match('/https?:\/\/(www\.)?(youtu.be|youtube.com|vimeo.com|bitchute.com)\//i', $url)) { + return true; + } elseif ($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, $simpleMode = false) +{ + global $global; + ob_start(); + include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php'; + $contents = ob_get_contents(); + ob_end_clean(); + return $contents; +} + +function pathToRemoteURL($filename, $forceHTTP = false, $ignoreCDN = false) +{ + global $pathToRemoteURL, $global; + if (!isset($pathToRemoteURL)) { + $pathToRemoteURL = []; + } + + 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']; + } elseif (!preg_match('/index.m3u8$/', $filename)) { + if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { + $source = $aws_s3->getAddress("{$fileName}"); + $url = $source['url']; + if (empty($ignoreCDN)) { + $url = replaceCDNIfNeed($url, 'CDN_S3'); + } elseif (!empty($source['url_noCDN'])) { + $url = $source['url_noCDN']; + } + } elseif ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { + $source = $bb_b2->getAddress("{$fileName}"); + $url = $source['url']; + if (empty($ignoreCDN)) { + $url = replaceCDNIfNeed($url, 'CDN_B2'); + } elseif (!empty($source['url_noCDN'])) { + $url = $source['url_noCDN']; + } + } elseif ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { + $source = $ftp->getAddress("{$fileName}"); + $url = $source['url']; + if (empty($ignoreCDN)) { + $url = replaceCDNIfNeed($url, 'CDN_FTP'); + } elseif (!empty($source['url_noCDN'])) { + $url = $source['url_noCDN']; + } + } + } + } + if (empty($url)) { + if ($forceHTTP) { + $paths = Video::getPaths($filename); + //$url = str_replace(getVideosDir(), getCDN() . "videos/", $filename); + if (empty($ignoreCDN)) { + $url = getCDN() . "{$paths['relative']}"; + } else { + $url = "{$global['webSiteRootURL']}{$paths['relative']}"; + } + if (preg_match('/index.m3u8$/', $filename) && !preg_match('/index.m3u8$/', $url)) { + $url .= 'index.m3u8'; + } + } else { + $url = $filename; + } + } + + //$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url); + + $pathToRemoteURL[$filename] = $url; + return $url; +} + +function getFilenameFromPath($path) +{ + global $global; + $fileName = Video::getCleanFilenameFromFile($path); + 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 = []; + foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) { + $fileEx = basename($filename, ".css"); + $_getThemes[] = $fileEx; + } + return $_getThemes; +} + +function getCurrentTheme() +{ + global $config; + if (!empty($_REQUEST['customCSS'])) { + _setcookie('customCSS', $_REQUEST['customCSS']); + return $_REQUEST['customCSS']; + } + if (!empty($_COOKIE['customCSS'])) { + return $_COOKIE['customCSS']; + } + return $config->getTheme(); +} + +/* + * $users_id="" or 0 means send messages to all users + * $users_id="-1" means send to no one + */ + +function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern = "") +{ + if (AVideoPlugin::isEnabledByName('YPTSocket')) { + if (!is_string($msg)) { + $msg = json_encode($msg); + } + $obj = YPTSocket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern); + if ($obj->error && !empty($obj->msg)) { + _error_log("sendSocketMessage " . $obj->msg); + } + return $obj; + } + return false; +} + +function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") +{ + _error_log("sendSocketMessageToUsers_id start " . json_encode($users_id)); + if (!is_array($users_id)) { + $users_id = [$users_id]; + } + + $resp = []; + foreach ($users_id as $value) { + $resp[] = sendSocketMessage($msg, $callbackJSFunction, $value); + } + + return $resp; +} + +function sendSocketErrorMessageToUsers_id($msg, $users_id, $callbackJSFunction = "avideoResponse") +{ + $newMessage = new stdClass(); + $newMessage->error = true; + $newMessage->msg = $msg; + return sendSocketMessageToUsers_id($newMessage, $users_id, $callbackJSFunction); +} + +function sendSocketSuccessMessageToUsers_id($msg, $users_id, $callbackJSFunction = "avideoResponse") +{ + $newMessage = new stdClass(); + $newMessage->error = false; + $newMessage->msg = $msg; + return sendSocketMessageToUsers_id($newMessage, $users_id, $callbackJSFunction); +} + +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 (isWindows()) { + //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 (isWindows()) { + exec("taskkill /F /PID $pid"); + } else { + exec("kill -9 $pid"); + } + return true; +} + +function isWindows() +{ + return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; +} + +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 = [$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('isURL200Clear: ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + rrmdir($cacheDir); +} + +function deleteStatsNotifications() +{ + Live::deleteStatsCache(); + $cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications"; + ObjectYPT::deleteCache($cacheName); +} + +function getStatsNotifications($force_recreate = false) +{ + $cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications"; + unset($_POST['sort']); + if ($force_recreate) { + Live::deleteStatsCache(); + } else { + $json = ObjectYPT::getCache($cacheName, 0, true); + } + if (empty($json) || !empty($json->error) || !isset($json->error)) { + //_error_log('getStatsNotifications: 1 ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); + $json = Live::getStats(); + $json = object_to_array($json); + + if (empty($json['applications']) && is_array($json)) { + $oldjson = $json; + $json = []; + $json['applications'] = []; + foreach ($oldjson 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 = []; + } + $json['error'] = false; + if (empty($json['msg'])) { + $json['msg'] = "OFFLINE"; + } + $json['nclients'] = count($appArray); + if (empty($json['applications'])) { + $json['applications'] = []; + } + $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['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); + } + if (empty($json['countLiveStream']) || $json['countLiveStream'] < $json['total']) { + $json['countLiveStream'] = $json['total']; + } + 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); + } elseif (!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 = []; + } + $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($msg = '') +{ + 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(); + echo $msg; + @header("Connection: close"); + @header("Content-Length: " . ob_get_length()); + @header("HTTP/1.1 200 OK"); + ob_end_flush(); + flush(); +} + +function cleanUpRowFromDatabase($row) +{ + if (is_array($row)) { + foreach ($row as $key => $value) { + if (preg_match('/pass/i', $key)) { + unset($row[$key]); + } + } + } + return $row; +} + +function getImageTransparent1pxURL() +{ + global $global; + return getCDN() . "view/img/transparent1px.png"; +} + +function getDatabaseTime() +{ + global $global, $_getDatabaseTime; + if (isset($_getDatabaseTime)) { + return $_getDatabaseTime; + } + $sql = "SELECT CURRENT_TIMESTAMP"; + $res = sqlDAL::readSql($sql); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + $row = $data; + } else { + $row = false; + } + $_getDatabaseTime = strtotime($row['CURRENT_TIMESTAMP']); + return $_getDatabaseTime; +} + +function get_js_availableLangs() +{ + global $global; + if (empty($global['js_availableLangs'])) { + include_once $global['systemRootPath'] . 'objects/bcp47.php'; + } + return $global['js_availableLangs']; +} + +function listAllWordsToTranslate() +{ + global $global; + $cacheName = 'listAllWordsToTranslate'; + $cache = ObjectYPT::getCache($cacheName, 0); + if (!empty($cache)) { + return object_to_array($cache); + } + ini_set('max_execution_time', 300); + + function listAll($dir) + { + $vars = []; + if (preg_match('/vendor.*$/', $dir)) { + return $vars; + } + 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_numeric($time1)) { + $time1 = strtotime($time1); + } + if (!is_numeric($time2)) { + $time2 = strtotime($time2); + } + + return $time1 - $time2; +} + +function secondsIntervalHuman($time, $useDatabaseTime = true) +{ + $dif = secondsIntervalFromNow($time, $useDatabaseTime); + if ($dif < 0) { + return humanTimingAfterwards($time, 0, $useDatabaseTime); + } else { + return humanTimingAgo($time, 0, $useDatabaseTime); + } +} + +function isTimeForFuture($time, $useDatabaseTime = true) +{ + $dif = secondsIntervalFromNow($time, $useDatabaseTime); + if ($dif < 0) { + return true; + } else { + return false; + } +} + +function secondsIntervalFromNow($time, $useDatabaseTimeOrTimezoneString = true) +{ + $timeNow = time(); + //var_dump($time, $useDatabaseTimeOrTimezoneString); + if (!empty($useDatabaseTimeOrTimezoneString)) { + if (is_numeric($useDatabaseTimeOrTimezoneString) || is_bool($useDatabaseTimeOrTimezoneString)) { + //echo $time . '-' . __LINE__ . '=>'; + $timeNow = getDatabaseTime(); + } elseif (is_string($useDatabaseTimeOrTimezoneString)) { + //echo '-' . __LINE__ . PHP_EOL . PHP_EOL; + $timeNow = getTimeInTimezone($timeNow, $useDatabaseTimeOrTimezoneString); + } + } + return secondsInterval($timeNow, $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 (isWindows()) { + $path = str_replace('/', DIRECTORY_SEPARATOR, $path); + $path = str_replace('\\\\\\', DIRECTORY_SEPARATOR, $path); + } else { + $path = str_replace('\\', DIRECTORY_SEPARATOR, $path); + } + if ($addLastSlash) { + $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + } + return $path; +} + +function idToHash($id) +{ + global $global, $_idToHash; + + if (!isset($_idToHash)) { + $_idToHash = []; + } + + if (!empty($_idToHash[$id])) { + return $_idToHash[$id]; + } + + if (!empty($global['useLongHash'])) { + $base = 2; + $cipher_algo = 'des'; + } else { + $base = 32; + $cipher_algo = 'rc4'; + } + if (empty($global['salt'])) { + $global['salt'] = '11234567890abcdef'; + } + $idConverted = base_convert($id, 10, $base); + $hash = (@openssl_encrypt($idConverted, $cipher_algo, $global['salt'])); + //$hash = preg_replace('/^([+]+)/', '', $hash); + $hash = preg_replace('/(=+)$/', '', $hash); + $hash = str_replace(['/', '+', '='], ['_', '-', '.'], $hash); + //return base64_encode($hash); + $_idToHash[$id] = $hash; + return $hash; +} + +function hashToID($hash) +{ + global $global; + if (!empty($global['useLongHash'])) { + $base = 2; + $cipher_algo = 'des'; + } else { + $base = 32; + $cipher_algo = 'rc4'; + } + //$hash = str_pad($hash, 4, "="); + $hash = str_replace(['_', '-', '.'], ['/', '+', '='], $hash); + //$hash = base64_decode($hash); + $decrypt = openssl_decrypt(($hash), $cipher_algo, $global['salt']); + $decrypt = base_convert($decrypt, $base, 10); + return intval($decrypt); +} + +function videosHashToID($hash_of_videos_id) +{ + if (is_int($hash_of_videos_id)) { + return $hash_of_videos_id; + } + if (!is_string($hash_of_videos_id) && !is_numeric($hash_of_videos_id)) { + if (is_array($hash_of_videos_id)) { + return $hash_of_videos_id; + } else { + 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 = []; + } + 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']; + } elseif (!empty($advancedCustom) && isValidURL($advancedCustom->videosCDN)) { + $_getCDNURL[$index] = addLastSlash($advancedCustom->videosCDN); + } elseif (empty($_getCDNURL[$index])) { + $_getCDNURL[$index] = $global['webSiteRootURL']; + } + } + //var_dump($type, $id, $_getCDNURL[$index]); + return empty($_getCDNURL[$index]) ? false : $_getCDNURL[$index]; +} + +function getURL($relativePath) +{ + global $global; + if (!isset($_SESSION['user']['sessionCache']['getURL'])) { + $_SESSION['user']['sessionCache']['getURL'] = []; + } + if (!empty($_SESSION['user']['sessionCache']['getURL'][$relativePath])) { + return $_SESSION['user']['sessionCache']['getURL'][$relativePath]; + } + + $file = "{$global['systemRootPath']}{$relativePath}"; + $url = getCDN() . $relativePath; + if (file_exists($file)) { + $cache = @filemtime($file) . '_' . @filectime($file); + $url = addQueryStringParameter($url, 'cache', $cache); + $_SESSION['user']['sessionCache']['getURL'][$relativePath] = $url; + } else { + $url = addQueryStringParameter($url, 'cache', 'not_found'); + } + + return $url; +} + +function getCDNOrURL($url, $type = 'CDN', $id = 0) +{ + if (!preg_match('/^http/i', $url)) { + return $url; + } + $cdn = getCDN($type, $id); + if (!empty($cdn)) { + return $cdn; + } + return addLastSlash($url); +} + +function replaceCDNIfNeed($url, $type = 'CDN', $id = 0) +{ + $cdn = getCDN($type, $id); + if (empty($cdn)) { + return $url; + } + + return str_replace(parse_url($url, PHP_URL_HOST), parse_url($cdn, PHP_URL_HOST), $url); +} + +function isIPPrivate($ip) +{ + if ($ip == '192.168.1.4') { + return false; + } + if (!filter_var($ip, FILTER_VALIDATE_IP)) { + return false; + } + $result = filter_var( + $ip, + FILTER_VALIDATE_IP, + FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE + ); + if (empty($result)) { + return true; + } + return false; +} + +function countDownPage($toTime, $message, $image, $bgImage) +{ + global $global; + include $global['systemRootPath'] . 'objects/functionCountDownPage.php'; + exit; +} + +function inputToRequest() +{ + $content = file_get_contents("php://input"); + if (!empty($content)) { + $json = json_decode($content); + if (empty($json)) { + return false; + } + foreach ($json as $key => $value) { + if (!isset($_REQUEST[$key])) { + $_REQUEST[$key] = $value; + } + } + } +} + +function useVideoHashOrLogin() +{ + if (!empty($_REQUEST['video_id_hash'])) { + $videos_id = Video::getVideoIdFromHash($_REQUEST['video_id_hash']); + if (!empty($videos_id)) { + $users_id = Video::getOwner($videos_id); + $user = new User($users_id); + _error_log("useVideoHashOrLogin: $users_id, $videos_id"); + return $user->login(true); + } + } + return User::loginFromRequest(); +} + +function strip_specific_tags($string, $tags_to_strip = ['script', 'style', 'iframe', 'object', 'applet', 'link']) +{ + foreach ($tags_to_strip as $tag) { + $string = preg_replace('/<' . $tag . '[^>]*>(.*?)<\/' . $tag . '>/s', '$1', $string); + } + return $string; +} + +function strip_render_blocking_resources($string) +{ + $tags_to_strip = ['link', 'style']; + $head = preg_match('/(.*)<\/head>/s', $string, $matches); + $string = str_replace($matches[0], '{_head_}', $string); + foreach ($tags_to_strip as $tag) { + $string = preg_replace('/<' . $tag . '[^>]*>(.*?)<\/' . $tag . '>/s', '', $string); + $string = preg_replace('/<' . $tag . '[^>]*\/>/s', '', $string); + } + $string = str_replace('{_head_}', $matches[0], $string); + return $string; +} + +function optimizeHTMLTags($html) +{ + return $html; + //$html = optimizeCSS($html); + //$html = optimizeJS($html); + return $html . '<--! optimized -->'; +} + +function optimizeCSS($html) +{ + global $global; + $css = ''; + $cacheDir = getVideosDir() . 'cache/'; + $cacheName = md5(getSelfURI() . User::getId()) . '.css'; + $filename = "{$cacheDir}{$cacheName}"; + $urlname = "{$global['webSiteRootURL']}videos/cache/{$cacheName}"; + $HTMLTag = ""; + $fileExists = file_exists($filename); + //$fileExists = false; + // get link tags + $pattern = '/((<(link)[^>]*(stylesheet|css)[^>]*\/>)|(<(style)[^>]*>([^<]+)<\/style>))/i'; + preg_match_all($pattern, $html, $matches); + foreach ($matches[3] as $key => $type) { + if (strtolower($type) == 'link') { + $linkTag = $matches[0][$key]; + $pattern = '/href=.(http[^"\']+)/i'; + preg_match($pattern, $linkTag, $href); + if (empty($href)) { + continue; + } + if (!$fileExists) { + $content = url_get_contents($href[1]); + if (empty($content)) { + continue; + } + $css .= PHP_EOL . " /* link {$href[1]} */ " . $content; + } + $html = str_replace($linkTag, '', $html); + } else { + if (!$fileExists) { + $css .= PHP_EOL . ' /* style */ ' . $matches[7][$key]; + } + $html = str_replace($matches[1][$key], '', $html); + } + } + if (!$fileExists) { + _file_put_contents($filename, $css); + } + return str_replace('', '' . PHP_EOL . $HTMLTag . PHP_EOL . '', $html); +} + +function optimizeJS($html) +{ + global $global; + $js = ''; + $cacheDir = getVideosDir() . 'cache/'; + $cacheName = md5(getSelfURI() . User::getId()) . '.js'; + $filename = "{$cacheDir}{$cacheName}"; + $urlname = "{$global['webSiteRootURL']}videos/cache/{$cacheName}"; + $HTMLTag = ""; + $fileExists = file_exists($filename); + $fileExists = false; + // get link tags + $pattern = '/((]+(src=[^ ]+)[^>]*>( *)<\/script>)|(]*>([^<]+)<\/script>))/si'; + preg_match_all($pattern, $html, $matches); + foreach ($matches[2] as $key => $type) { + if (empty($type)) { + if (preg_match('/application_ld_json/i', $matches[1][$key])) { + continue; + } + $js .= PHP_EOL . " /* js */ " . $matches[6][$key]; + $html = str_replace($matches[1][$key], '', $html); + } else { + $pattern = '/src=.(http[^"\']+)/i'; + preg_match($pattern, $type, $href); + if (empty($href)) { + continue; + } + if (preg_match('/(jquery|video-js|videojs)/i', $href[1])) { + continue; + } + if (!$fileExists) { + $content = url_get_contents($href[1]); + if (empty($content)) { + continue; + } + $js .= PHP_EOL . " /* js link {$href[1]} */ " . $content; + } + $html = str_replace($type, '', $html); + } + } + if (!$fileExists) { + _file_put_contents($filename, $js); + } + return str_replace('', '' . PHP_EOL . $HTMLTag . PHP_EOL . '', $html); +} + +function mysqlBeginTransaction() +{ + global $global; + _error_log('Begin transaction ' . getSelfURI()); + $global['mysqli']->autocommit(false); +} + +function mysqlRollback() +{ + global $global; + _error_log('Rollback transaction ' . getSelfURI(), AVideoLog::$ERROR); + $global['mysqli']->rollback(); + $global['mysqli']->autocommit(true); +} + +function mysqlCommit() +{ + global $global; + _error_log('Commit transaction ' . getSelfURI()); + $global['mysqli']->commit(); + $global['mysqli']->autocommit(true); +} + +function number_format_short($n, $precision = 1) +{ + $n = floatval($n); + if ($n < 900) { + // 0 - 900 + $n_format = number_format($n, $precision); + $suffix = ''; + } elseif ($n < 900000) { + // 0.9k-850k + $n_format = number_format($n / 1000, $precision); + $suffix = 'K'; + } elseif ($n < 900000000) { + // 0.9m-850m + $n_format = number_format($n / 1000000, $precision); + $suffix = 'M'; + } elseif ($n < 900000000000) { + // 0.9b-850b + $n_format = number_format($n / 1000000000, $precision); + $suffix = 'B'; + } else { + // 0.9t+ + $n_format = number_format($n / 1000000000000, $precision); + $suffix = 'T'; + } + + // Remove unnecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1" + // Intentionally does not affect partials, eg "1.50" -> "1.50" + if ($precision > 0) { + $dotzero = '.' . str_repeat('0', $precision); + $n_format = str_replace($dotzero, '', $n_format); + } + + return $n_format . $suffix; +} + +function seconds2human($ss) +{ + $s = $ss % 60; + $m = floor(($ss % 3600) / 60); + $h = floor(($ss % 86400) / 3600); + $d = floor(($ss % 2592000) / 86400); + $M = floor($ss / 2592000); + + $times = []; + + if (!empty($M)) { + $times[] = "$M " . __('m'); + } + if (!empty($d)) { + $times[] = "$d " . __('d'); + } + if (!empty($h)) { + $times[] = "$h " . __('h'); + } + if (!empty($m)) { + $times[] = "$m " . __('min'); + } + if (!empty($s)) { + $times[] = "$s " . __('sec'); + } + + return implode(', ', $times); +} + +/** + * convert a time in a timezone into my time + * @param type $time + * @param type $timezone + * @return type + */ +function getTimeInTimezone($time, $timezone) +{ + if (!is_numeric($time)) { + $time = strtotime($time); + } + if (empty($timezone) || empty(date_default_timezone_get()) || $timezone == date_default_timezone_get()) { + return $time; + } + $date = new DateTime(date('Y-m-d H:i:s', $time)); + $date->setTimezone(new DateTimeZone($timezone)); + //$date->setTimezone(date_default_timezone_get()); + $dateString = $date->format('Y-m-d H:i:s'); + return strtotime($dateString); +} + +function listFolderFiles($dir) +{ + if (empty($dir)) { + return []; + } + $ffs = scandir($dir); + + unset($ffs[array_search('.', $ffs, true)]); + unset($ffs[array_search('..', $ffs, true)]); + + $files = []; + // prevent empty ordered elements + if (count($ffs) >= 1) { + foreach ($ffs as $ff) { + $dir = rtrim($dir, DIRECTORY_SEPARATOR); + $file = $dir . DIRECTORY_SEPARATOR . $ff; + if (is_dir($file)) { + $files[] = listFolderFiles($file); + } else { + $files[] = $file; + } + } + } + return $files; +} + +function convertToMyTimezone($date, $fromTimezone) +{ + $time = getTimestampFromTimezone($date, $fromTimezone); + return date('Y-m-d H:i:s', $time); +} + +function getTimestampFromTimezone($date, $fromTimezone) +{ + $date = new DateTime($date, new DateTimeZone($fromTimezone)); + return $date->getTimestamp(); +} + +function getCSSAnimation($type = 'animate__flipInX', $loaderSequenceName = 'default', $delay = 0.1) +{ + global $_getCSSAnimationClassDelay; + getCSSAnimationClassAndStyleAddWait($delay, $loaderSequenceName); + return ['class' => 'animate__animated ' . $type, 'style' => "-webkit-animation-delay: {$_getCSSAnimationClassDelay[$loaderSequenceName]}s; animation-delay: {$_getCSSAnimationClassDelay[$loaderSequenceName]}s;"]; +} + +function getCSSAnimationClassAndStyleAddWait($delay, $loaderSequenceName = 'default') +{ + global $_getCSSAnimationClassDelay; + if (!isset($_getCSSAnimationClassDelay)) { + $_getCSSAnimationClassDelay = []; + } + if (empty($_getCSSAnimationClassDelay[$loaderSequenceName])) { + $_getCSSAnimationClassDelay[$loaderSequenceName] = 0; + } + $_getCSSAnimationClassDelay[$loaderSequenceName] += $delay; +} + +function getCSSAnimationClassAndStyle($type = 'animate__flipInX', $loaderSequenceName = 'default', $delay = 0.1) +{ + $array = getCSSAnimation($type, $loaderSequenceName, $delay); + return "{$array['class']}\" style=\"{$array['style']}"; +} + +function isImage($file) +{ + [$width, $height, $type, $attr] = getimagesize($file); + if ($type == IMAGETYPE_PNG) { + return 'png'; + } + if ($type == IMAGETYPE_JPEG) { + return 'jpg'; + } + if ($type == IMAGETYPE_GIF) { + return 'gif'; + } + return false; +} + +function isHTMLEmpty($html_string) +{ + return empty(trim(strip_specific_tags($html_string, ['br', 'p']))); +} + +function totalImageColors($image_path) +{ + $img = imagecreatefromjpeg($image_path); + $w = imagesx($img); + $h = imagesy($img); + + // capture the raw data of the image + ob_start(); + imagegd2($img, null, $w); + $data = ob_get_clean(); + $totalLength = strlen($data); + + // calculate the length of the actual pixel data + // from that we can derive the header size + $pixelDataLength = $w * $h * 4; + $headerLength = $totalLength - $pixelDataLength; + + // use each four-byte segment as the key to a hash table + $counts = []; + for ($i = $headerLength; $i < $totalLength; $i += 4) { + $pixel = substr($data, $i, 4); + $count = & $counts[$pixel]; + $count += 1; + } + $colorCount = count($counts); + return $colorCount; +} + +function isImageCorrupted($image_path) +{ + $fsize = filesize($image_path); + if (strpos($image_path, 'thumbsSmall') !== false) { + if ($fsize < 1000) { + return true; + } + } else { + if ($fsize < 2000) { + return true; + } + } + + if (totalImageColors($image_path) === 1) { + return true; + } + + if (!isGoodImage($image_path)) { + return true; + } + return false; +} + +// detect partial grey immages +function isGoodImage($fn) +{ + [$w, $h] = getimagesize($fn); + $im = imagecreatefromstring(file_get_contents($fn)); + $grey = 0; + for ($i = 0; $i < 5; ++$i) { + for ($j = 0; $j < 5; ++$j) { + $x = $w - 5 + $i; + $y = $h - 5 + $j; + [$r, $g, $b] = array_values(imagecolorsforindex($im, imagecolorat($im, $x, $y))); + if ($r == $g && $g == $b && $b == 128) { + ++$grey; + } + } + } + return $grey < 12; +} + +function defaultIsPortrait() +{ + global $_defaultIsPortrait; + + if (!isset($_defaultIsPortrait)) { + $_defaultIsPortrait = false; + if ($obj = AVideoPlugin::getDataObjectIfEnabled('YouPHPFlix2') && empty($obj->landscapePosters)) { + $_defaultIsPortrait = true; + } + } + + return $_defaultIsPortrait; +} diff --git a/objects/functionsGetTinyMCE.php b/objects/functionsGetTinyMCE.php index 35389385ff..10fbe610f2 100644 --- a/objects/functionsGetTinyMCE.php +++ b/objects/functionsGetTinyMCE.php @@ -1,83 +1,80 @@ -disableHTMLDescription)) { - global $tinyMCELibs; - if (empty($tinyMCELibs)) { - $tinyMCELibs = 1; - ?> - - - - - disableHTMLDescription)) { + global $tinyMCELibs; + if (empty($tinyMCELibs)) { + $tinyMCELibs = 1; ?> + + + + + query($sql)) { - while ($p = $result->fetch_assoc()) { - $groups = UserGroups::getUserGroups($p['id']); - $groupsName = array(); - foreach ($groups as $value) { - $groupsName[] = $value['group_name']; - } - $p['groups'] = implode(', ', $groupsName); - $users[] = $p; - } -} -$output = fopen("php://output", 'w') or die("Can't open php://output"); -header("Content-Type:application/csv"); -header("Content-Disposition:attachment;filename=email.csv"); -fputcsv($output, array('id', 'user', 'name', 'email', 'status', 'created', 'isAdmin', 'Groups')); -foreach ($users as $user) { - fputcsv($output, $user); -} -fclose($output) or die("Can't close php://output"); +query($sql)) { + while ($p = $result->fetch_assoc()) { + $groups = UserGroups::getUserGroups($p['id']); + $groupsName = []; + foreach ($groups as $value) { + $groupsName[] = $value['group_name']; + } + $p['groups'] = implode(', ', $groupsName); + $users[] = $p; + } +} +$output = fopen("php://output", 'w') or die("Can't open php://output"); +header("Content-Type:application/csv"); +header("Content-Disposition:attachment;filename=email.csv"); +fputcsv($output, ['id', 'user', 'name', 'email', 'status', 'created', 'isAdmin', 'Groups']); +foreach ($users as $user) { + fputcsv($output, $user); +} +fclose($output) or die("Can't close php://output"); diff --git a/objects/getAllVideosAsync.php b/objects/getAllVideosAsync.php index f8a0d80ce1..e4a2dcd393 100644 --- a/objects/getAllVideosAsync.php +++ b/objects/getAllVideosAsync.php @@ -1,26 +1,25 @@ -getCaptchaImage(); +getCaptchaImage(); diff --git a/objects/getImageFromFilenameAsync.php b/objects/getImageFromFilenameAsync.php index ee1b6e2480..0ffbd6201a 100644 --- a/objects/getImageFromFilenameAsync.php +++ b/objects/getImageFromFilenameAsync.php @@ -1,22 +1,22 @@ -_serverTime = time(); -$obj->_serverDBTime = getDatabaseTime(); -$obj->_serverTimeString = date('Y-m-d H:i:s'); -$obj->_serverDBTimeString = date('Y-m-d H:i:s', getDatabaseTime()); -$obj->_serverTimezone = date_default_timezone_get(); - -die(json_encode($obj)); +_serverTime = time(); +$obj->_serverDBTime = getDatabaseTime(); +$obj->_serverTimeString = date('Y-m-d H:i:s'); +$obj->_serverDBTimeString = date('Y-m-d H:i:s', getDatabaseTime()); +$obj->_serverTimezone = date_default_timezone_get(); + +die(json_encode($obj)); diff --git a/objects/getTotalLastDaysAsync.php b/objects/getTotalLastDaysAsync.php index fa14d73c4d..775b025480 100644 --- a/objects/getTotalLastDaysAsync.php +++ b/objects/getTotalLastDaysAsync.php @@ -1,17 +1,17 @@ -fileURI = pathinfo($_POST['fileURI']); //get description $filename = $obj->fileURI['dirname'] . DIRECTORY_SEPARATOR . $obj->fileURI['filename']; -$extensions = array('txt', 'html', 'htm'); +$extensions = ['txt', 'html', 'htm']; $length = intval($_POST['length']); if (empty($length) || $length>100) { @@ -29,11 +29,11 @@ if (empty($length) || $length>100) { } foreach ($extensions as $value) { - $_POST['description'] = ""; - $_POST['title'] = ""; + $_POST['description'] = ''; + $_POST['title'] = ''; if (file_exists("{$filename}.{$value}")) { $html = file_get_contents("{$filename}.{$value}"); - $breaks = array("
","
","
"); + $breaks = ["
","
","
"]; $html = str_ireplace($breaks, "\r\n", $html); $_POST['description'] = $html; $cleanHTML = strip_tags($html); diff --git a/objects/include_config.php b/objects/include_config.php index 0a9d05f2aa..b90061a3ac 100644 --- a/objects/include_config.php +++ b/objects/include_config.php @@ -1,211 +1,210 @@ - $value2) { - if (stripos($_SERVER['HTTP_USER_AGENT'], $value2) !== false) { - break 2; - } - } - } - die('Bot Found ' . $_SERVER['HTTP_USER_AGENT']); - } - } -} - -$global['avideoStartMicrotime'] = microtime(true); - -try { - ini_set('display_errors', 1); - ini_set('display_startup_errors', 1); - error_reporting(E_ALL); - require_once __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php'; - ini_set('display_errors', 0); - ini_set('display_startup_errors', 0); - error_reporting(0); -} catch (Exception $exc) { - echo $exc->getTraceAsString(); -} - -$global['webSiteRootURL'] .= (substr($global['webSiteRootURL'], -1) == '/' ? '' : '/'); -$global['systemRootPath'] .= (substr($global['systemRootPath'], -1) == '/' ? '' : '/'); -$global['session_name'] = md5($global['systemRootPath']); - -session_name($global['session_name']); - -if (empty($global['logfile'])) { - $global['logfile'] = $global['systemRootPath'] . 'videos/avideo.log'; -} - -ini_set('error_log', $global['logfile']); -global $global, $config, $advancedCustom, $advancedCustomUser; - -if (empty($doNotConnectDatabaseIncludeConfig)) { - $global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort); - - if ($global['mysqli'] === false || !empty($global['mysqli']->connect_errno)) { - error_log("MySQL connect_errno[{$global['mysqli']->connect_errno}] {$global['mysqli']->connect_error}"); - include $global['systemRootPath'] . 'view/include/offlinePage.php'; - exit; - } - - // if you set it on configuration file it will help you to encode - if (!empty($global['mysqli_charset'])) { - $global['mysqli']->set_charset($global['mysqli_charset']); - } -} else { - $mysql_connect_was_closed = 1; -} -require_once $global['systemRootPath'] . 'objects/mysql_dal.php'; -require_once $global['systemRootPath'] . 'objects/configuration.php'; -require_once $global['systemRootPath'] . 'objects/security.php'; - -// for update config from old versions 2020-05-11 -if (empty($global['webSiteRootPath']) || $global['configurationVersion'] < 3.1) { - Configuration::rewriteConfigFile(); -} - -$global['dont_show_us_flag'] = false; -// this is for old versions - -if (empty($doNotStartSessionbaseIncludeConfig)) { - $config = new Configuration(); - session_write_close(); - - // server should keep session data for AT LEAST 1 hour - ini_set('session.gc_maxlifetime', $config->getSession_timeout()); - - // each client should remember their session id for EXACTLY 1 hour - session_set_cookie_params($config->getSession_timeout()); - - //Fix “set SameSite cookie to none” warning - if (version_compare(PHP_VERSION, '7.3.0') >= 0) { - setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]); - } else { - header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure'); - setcookie('key', 'value', time() + $config->getSession_timeout(), '/; SameSite=None; Secure'); - } - - session_start(); -} -// DDOS protection can be disabled in video/configuration.php -if (!empty($global['enableDDOSprotection'])) { - ddosProtection(); -} - -// set the referrer for aVideo -$url1['host'] = ''; -$global['HTTP_REFERER'] = ''; -if (!empty($_SERVER['HTTP_REFERER'])) { - if (( - strpos($_SERVER['HTTP_REFERER'], '/video/') !== false || strpos($_SERVER['HTTP_REFERER'], '/v/') !== false - ) && - !empty($_SESSION['LAST_HTTP_REFERER'])) { - if (strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/css/') !== false || - strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/js/') !== false || - strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/img/') !== false) { - $_SESSION['LAST_HTTP_REFERER'] = $global['webSiteRootURL']; - } - $global['HTTP_REFERER'] = $_SESSION['LAST_HTTP_REFERER']; - $url1 = parse_url($global['HTTP_REFERER']); - } else { - $global['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; - $url1 = parse_url($global['HTTP_REFERER']); - } -} -//var_dump($global['HTTP_REFERER']);exit; -if (!isset($_POST['redirectUri'])) { - $_POST['redirectUri'] = ''; -} - -if (!empty($_POST['redirectUri']) && strpos($_POST['redirectUri'], 'logoff.php') !== false) { - $_POST['redirectUri'] = ''; -} -if (!empty($_GET['redirectUri']) && strpos($_GET['redirectUri'], 'logoff.php') !== false) { - $_GET['redirectUri'] = ''; -} - -$url2 = parse_url($global['webSiteRootURL']); -if (!empty($url1['host']) && !empty($url2['host']) && $url1['host'] !== $url2['host']) { - $global['HTTP_REFERER'] = $global['webSiteRootURL']; -} -$_SESSION['LAST_HTTP_REFERER'] = $global['HTTP_REFERER']; -//var_dump($global['HTTP_REFERER'], $url1);exit; - -$output = ob_get_clean(); -ob_start('ob_gzhandler'); -echo $output; -$_SESSION['lastUpdate'] = time(); -$_SESSION['savedQuerys'] = 0; -require_once $global['systemRootPath'] . 'objects/Object.php'; -require_once $global['systemRootPath'] . 'locale/function.php'; -require_once $global['systemRootPath'] . 'objects/plugin.php'; -require_once $global['systemRootPath'] . 'objects/user.php'; -require_once $global['systemRootPath'] . 'objects/video.php'; -require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; - -setSiteLang(); -fixSystemPath(); -ObjectYPT::checkSessionCacheBasedOnLastDeleteALLCacheTime(); -getDeviceID(); -allowOrigin(); - -$baseName = basename($_SERVER['SCRIPT_FILENAME']); -if (empty($doNotConnectDatabaseIncludeConfig) && $baseName !== 'xsendfile.php' && class_exists('Plugin')) { - AVideoPlugin::getStart(); -} elseif (empty($doNotConnectDatabaseIncludeConfig) && $baseName !== 'xsendfile.php') { - _error_log("Class Plugin Not found: {$_SERVER['REQUEST_URI']}"); -} -if (empty($global['bodyClass'])) { - $global['bodyClass'] = ''; -} -$global['allowedExtension'] = array('gif', 'jpg', 'mp4', 'webm', 'mp3', 'm4a', 'ogg', 'zip', 'm3u8'); - -if (empty($global['avideo_resolutions'])) { - $global['avideo_resolutions'] = array(240, 360, 480, 540, 720, 1080, 1440, 2160); -} - -sort($global['avideo_resolutions']); -if (!empty($doNotConnectDatabaseIncludeConfig)) { - return false; -} -$advancedCustom = AVideoPlugin::getObjectData('CustomizeAdvanced'); - -if (empty($global['disableTimeFix'])) { - /* - $now = new DateTime(); - $mins = $now->getOffset() / 60; - $sgn = ($mins < 0 ? -1 : 1); - $mins = abs($mins); - $hrs = floor($mins / 60); - $mins -= $hrs * 60; - $offset = sprintf('%+d:%02d', $hrs * $sgn, $mins); - $global['mysqli']->query("SET time_zone='$offset';"); - */ - ObjectYPT::setGlobalTimeZone(); -} - -$avideoLayout = AVideoPlugin::getObjectData('Layout'); -$avideoCustomizeUser = $advancedCustomUser = AVideoPlugin::getObjectData('CustomizeUser'); -$avideoCustomize = $customizePlugin = AVideoPlugin::getObjectData('Customize'); -$avideoPermissions = $permissionsPlugin = AVideoPlugin::getObjectData('Permissions'); -$avideoPlayerSkins = AVideoPlugin::getObjectData('PlayerSkins'); - -if (!empty($_GET['type'])) { - $metaDescription = " {$_GET['type']}"; -} elseif (!empty($_GET['showOnly'])) { - $metaDescription = " {$_GET['showOnly']}"; -} + $value2) { + if (stripos($_SERVER['HTTP_USER_AGENT'], $value2) !== false) { + break 2; + } + } + } + die('Bot Found ' . $_SERVER['HTTP_USER_AGENT']); + } + } +} + +$global['avideoStartMicrotime'] = microtime(true); + +try { + ini_set('display_errors', 1); + ini_set('display_startup_errors', 1); + error_reporting(E_ALL); + require_once __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php'; + ini_set('display_errors', 0); + ini_set('display_startup_errors', 0); + error_reporting(0); +} catch (Exception $exc) { + echo $exc->getTraceAsString(); +} + +$global['webSiteRootURL'] .= (substr($global['webSiteRootURL'], -1) == '/' ? '' : '/'); +$global['systemRootPath'] .= (substr($global['systemRootPath'], -1) == '/' ? '' : '/'); +$global['session_name'] = md5($global['systemRootPath']); + +session_name($global['session_name']); + +if (empty($global['logfile'])) { + $global['logfile'] = $global['systemRootPath'] . 'videos/avideo.log'; +} + +ini_set('error_log', $global['logfile']); +global $global, $config, $advancedCustom, $advancedCustomUser; + +if (empty($doNotConnectDatabaseIncludeConfig)) { + $global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort); + + if ($global['mysqli'] === false || !empty($global['mysqli']->connect_errno)) { + error_log("MySQL connect_errno[{$global['mysqli']->connect_errno}] {$global['mysqli']->connect_error}"); + include $global['systemRootPath'] . 'view/include/offlinePage.php'; + exit; + } + + // if you set it on configuration file it will help you to encode + if (!empty($global['mysqli_charset'])) { + $global['mysqli']->set_charset($global['mysqli_charset']); + } +} else { + $mysql_connect_was_closed = 1; +} +require_once $global['systemRootPath'] . 'objects/mysql_dal.php'; +require_once $global['systemRootPath'] . 'objects/configuration.php'; +require_once $global['systemRootPath'] . 'objects/security.php'; + +// for update config from old versions 2020-05-11 +if (empty($global['webSiteRootPath']) || $global['configurationVersion'] < 3.1) { + Configuration::rewriteConfigFile(); +} + +$global['dont_show_us_flag'] = false; +// this is for old versions + +if (empty($doNotStartSessionbaseIncludeConfig)) { + $config = new Configuration(); + session_write_close(); + + // server should keep session data for AT LEAST 1 hour + ini_set('session.gc_maxlifetime', $config->getSession_timeout()); + + // each client should remember their session id for EXACTLY 1 hour + session_set_cookie_params($config->getSession_timeout()); + + //Fix “set SameSite cookie to none” warning + if (version_compare(PHP_VERSION, '7.3.0') >= 0) { + setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]); + } else { + header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure'); + setcookie('key', 'value', time() + $config->getSession_timeout(), '/; SameSite=None; Secure'); + } + + session_start(); +} +// DDOS protection can be disabled in video/configuration.php +if (!empty($global['enableDDOSprotection'])) { + ddosProtection(); +} + +// set the referrer for aVideo +$url1['host'] = ''; +$global['HTTP_REFERER'] = ''; +if (!empty($_SERVER['HTTP_REFERER'])) { + if (( + strpos($_SERVER['HTTP_REFERER'], '/video/') !== false || strpos($_SERVER['HTTP_REFERER'], '/v/') !== false + ) && + !empty($_SESSION['LAST_HTTP_REFERER'])) { + if (strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/css/') !== false || + strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/js/') !== false || + strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/img/') !== false) { + $_SESSION['LAST_HTTP_REFERER'] = $global['webSiteRootURL']; + } + $global['HTTP_REFERER'] = $_SESSION['LAST_HTTP_REFERER']; + $url1 = parse_url($global['HTTP_REFERER']); + } else { + $global['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; + $url1 = parse_url($global['HTTP_REFERER']); + } +} +//var_dump($global['HTTP_REFERER']);exit; +if (!isset($_POST['redirectUri'])) { + $_POST['redirectUri'] = ''; +} + +if (!empty($_POST['redirectUri']) && strpos($_POST['redirectUri'], 'logoff.php') !== false) { + $_POST['redirectUri'] = ''; +} +if (!empty($_GET['redirectUri']) && strpos($_GET['redirectUri'], 'logoff.php') !== false) { + $_GET['redirectUri'] = ''; +} + +$url2 = parse_url($global['webSiteRootURL']); +if (!empty($url1['host']) && !empty($url2['host']) && $url1['host'] !== $url2['host']) { + $global['HTTP_REFERER'] = $global['webSiteRootURL']; +} +$_SESSION['LAST_HTTP_REFERER'] = $global['HTTP_REFERER']; +//var_dump($global['HTTP_REFERER'], $url1);exit; + +$output = ob_get_clean(); +ob_start('ob_gzhandler'); +echo $output; +$_SESSION['lastUpdate'] = time(); +$_SESSION['savedQuerys'] = 0; +require_once $global['systemRootPath'] . 'objects/Object.php'; +require_once $global['systemRootPath'] . 'locale/function.php'; +require_once $global['systemRootPath'] . 'objects/plugin.php'; +require_once $global['systemRootPath'] . 'objects/user.php'; +require_once $global['systemRootPath'] . 'objects/video.php'; +require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; + +setSiteLang(); +fixSystemPath(); +ObjectYPT::checkSessionCacheBasedOnLastDeleteALLCacheTime(); +getDeviceID(); +allowOrigin(); + +$baseName = basename($_SERVER['SCRIPT_FILENAME']); +if (empty($doNotConnectDatabaseIncludeConfig) && $baseName !== 'xsendfile.php' && class_exists('Plugin')) { + AVideoPlugin::getStart(); +} elseif (empty($doNotConnectDatabaseIncludeConfig) && $baseName !== 'xsendfile.php') { + _error_log("Class Plugin Not found: {$_SERVER['REQUEST_URI']}"); +} +if (empty($global['bodyClass'])) { + $global['bodyClass'] = ''; +} +$global['allowedExtension'] = ['gif', 'jpg', 'mp4', 'webm', 'mp3', 'm4a', 'ogg', 'zip', 'm3u8']; + +if (empty($global['avideo_resolutions'])) { + $global['avideo_resolutions'] = [240, 360, 480, 540, 720, 1080, 1440, 2160]; +} + +sort($global['avideo_resolutions']); +if (!empty($doNotConnectDatabaseIncludeConfig)) { + return false; +} +$advancedCustom = AVideoPlugin::getObjectData('CustomizeAdvanced'); + +if (empty($global['disableTimeFix'])) { + /* + $now = new DateTime(); + $mins = $now->getOffset() / 60; + $sgn = ($mins < 0 ? -1 : 1); + $mins = abs($mins); + $hrs = floor($mins / 60); + $mins -= $hrs * 60; + $offset = sprintf('%+d:%02d', $hrs * $sgn, $mins); + $global['mysqli']->query("SET time_zone='$offset';"); + */ + ObjectYPT::setGlobalTimeZone(); +} + +$avideoLayout = AVideoPlugin::getObjectData('Layout'); +$avideoCustomizeUser = $advancedCustomUser = AVideoPlugin::getObjectData('CustomizeUser'); +$avideoCustomize = $customizePlugin = AVideoPlugin::getObjectData('Customize'); +$avideoPermissions = $permissionsPlugin = AVideoPlugin::getObjectData('Permissions'); +$avideoPlayerSkins = AVideoPlugin::getObjectData('PlayerSkins'); + +if (!empty($_GET['type'])) { + $metaDescription = " {$_GET['type']}"; +} elseif (!empty($_GET['showOnly'])) { + $metaDescription = " {$_GET['showOnly']}"; +} diff --git a/objects/include_end.php b/objects/include_end.php index a0b6529bb9..3f0015393a 100644 --- a/objects/include_end.php +++ b/objects/include_end.php @@ -1,4 +1,6 @@ - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/** - * JShrink - * - * - * @package JShrink - * @author Robert Hafner - */ - -namespace JShrink; - -/** - * Minifier - * - * Usage - Minifier::minify($js); - * Usage - Minifier::minify($js, $options); - * Usage - Minifier::minify($js, array('flaggedComments' => false)); - * - * @package JShrink - * @author Robert Hafner - * @license http://www.opensource.org/licenses/bsd-license.php BSD License - */ -class Minifier -{ - /** - * The input javascript to be minified. - * - * @var string - */ - protected $input; - - /** - * Length of input javascript. - * - * @var int - */ - protected $len = 0; - - /** - * The location of the character (in the input string) that is next to be - * processed. - * - * @var int - */ - protected $index = 0; - - /** - * The first of the characters currently being looked at. - * - * @var string - */ - protected $a = ''; - - /** - * The next character being looked at (after a); - * - * @var string - */ - protected $b = ''; - - /** - * This character is only active when certain look ahead actions take place. - * - * @var string - */ - protected $c; - - /** - * Contains the options for the current minification process. - * - * @var array - */ - protected $options; - - /** - * These characters are used to define strings. - */ - protected $stringDelimiters = ['\'' => true, '"' => true, '`' => true]; - - /** - * Contains the default options for minification. This array is merged with - * the one passed in by the user to create the request specific set of - * options (stored in the $options attribute). - * - * @var array - */ - protected static $defaultOptions = ['flaggedComments' => true]; - - /** - * Contains lock ids which are used to replace certain code patterns and - * prevent them from being minified - * - * @var array - */ - protected $locks = []; - - /** - * Takes a string containing javascript and removes unneeded characters in - * order to shrink the code without altering it's functionality. - * - * @param string $js The raw javascript to be minified - * @param array $options Various runtime options in an associative array - * @throws \Exception - * @return bool|string - */ - public static function minify($js, $options = []) - { - try { - ob_start(); - - $jshrink = new Minifier(); - $js = $jshrink->lock($js); - $jshrink->minifyDirectToOutput($js, $options); - - // Sometimes there's a leading new line, so we trim that out here. - $js = ltrim(ob_get_clean()); - $js = $jshrink->unlock($js); - unset($jshrink); - - return $js; - } catch (\Exception $e) { - if (isset($jshrink)) { - // Since the breakdownScript function probably wasn't finished - // we clean it out before discarding it. - $jshrink->clean(); - unset($jshrink); - } - - // without this call things get weird, with partially outputted js. - ob_end_clean(); - throw $e; - } - } - - /** - * Processes a javascript string and outputs only the required characters, - * stripping out all unneeded characters. - * - * @param string $js The raw javascript to be minified - * @param array $options Various runtime options in an associative array - */ - protected function minifyDirectToOutput($js, $options) - { - $this->initialize($js, $options); - $this->loop(); - $this->clean(); - } - - /** - * Initializes internal variables, normalizes new lines, - * - * @param string $js The raw javascript to be minified - * @param array $options Various runtime options in an associative array - */ - protected function initialize($js, $options) - { - $this->options = array_merge(static::$defaultOptions, $options); - $this->input = str_replace(["\r\n", '/**/', "\r"], ["\n", "", "\n"], $js); - - // We add a newline to the end of the script to make it easier to deal - // with comments at the bottom of the script- this prevents the unclosed - // comment error that can otherwise occur. - $this->input .= PHP_EOL; - - // save input length to skip calculation every time - $this->len = strlen($this->input); - - // Populate "a" with a new line, "b" with the first character, before - // entering the loop - $this->a = "\n"; - $this->b = $this->getReal(); - } - - /** - * Characters that can't stand alone preserve the newline. - * - * @var array - */ - protected $noNewLineCharacters = [ - '(' => true, - '-' => true, - '+' => true, - '[' => true, - '@' => true]; - - /** - * The primary action occurs here. This function loops through the input string, - * outputting anything that's relevant and discarding anything that is not. - */ - protected function loop() - { - while ($this->a !== false && !is_null($this->a) && $this->a !== '') { - switch ($this->a) { - // new lines - case "\n": - // if the next line is something that can't stand alone preserve the newline - if ($this->b !== false && isset($this->noNewLineCharacters[$this->b])) { - echo $this->a; - $this->saveString(); - break; - } - - // if B is a space we skip the rest of the switch block and go down to the - // string/regex check below, resetting $this->b with getReal - if ($this->b === ' ') { - break; - } - - // otherwise we treat the newline like a space - - // no break - case ' ': - if (static::isAlphaNumeric($this->b)) { - echo $this->a; - } - - $this->saveString(); - break; - - default: - switch ($this->b) { - case "\n": - if (strpos('}])+-"\'', $this->a) !== false) { - echo $this->a; - $this->saveString(); - break; - } else { - if (static::isAlphaNumeric($this->a)) { - echo $this->a; - $this->saveString(); - } - } - break; - - case ' ': - if (!static::isAlphaNumeric($this->a)) { - break; - } - - // no break - default: - // check for some regex that breaks stuff - if ($this->a === '/' && ($this->b === '\'' || $this->b === '"')) { - $this->saveRegex(); - continue 3; - } - - echo $this->a; - $this->saveString(); - break; - } - } - - // do reg check of doom - $this->b = $this->getReal(); - - if (($this->b == '/' && strpos('(,=:[!&|?', $this->a) !== false)) { - $this->saveRegex(); - } - } - } - - /** - * Resets attributes that do not need to be stored between requests so that - * the next request is ready to go. Another reason for this is to make sure - * the variables are cleared and are not taking up memory. - */ - protected function clean() - { - unset($this->input); - $this->len = 0; - $this->index = 0; - $this->a = $this->b = ''; - unset($this->c); - unset($this->options); - } - - /** - * Returns the next string for processing based off of the current index. - * - * @return string - */ - protected function getChar() - { - // Check to see if we had anything in the look ahead buffer and use that. - if (isset($this->c)) { - $char = $this->c; - unset($this->c); - } else { - // Otherwise we start pulling from the input. - $char = $this->index < $this->len ? $this->input[$this->index] : false; - - // If the next character doesn't exist return false. - if (isset($char) && $char === false) { - return false; - } - - // Otherwise increment the pointer and use this char. - $this->index++; - } - - // Normalize all whitespace except for the newline character into a - // standard space. - if ($char !== "\n" && $char < "\x20") { - return ' '; - } - - return $char; - } - - /** - * This function gets the next "real" character. It is essentially a wrapper - * around the getChar function that skips comments. This has significant - * performance benefits as the skipping is done using native functions (ie, - * c code) rather than in script php. - * - * - * @return string Next 'real' character to be processed. - * @throws \RuntimeException - */ - protected function getReal() - { - $startIndex = $this->index; - $char = $this->getChar(); - - // Check to see if we're potentially in a comment - if ($char !== '/') { - return $char; - } - - $this->c = $this->getChar(); - - if ($this->c === '/') { - $this->processOneLineComments($startIndex); - - return $this->getReal(); - } elseif ($this->c === '*') { - $this->processMultiLineComments($startIndex); - - return $this->getReal(); - } - - return $char; - } - - /** - * Removed one line comments, with the exception of some very specific types of - * conditional comments. - * - * @param int $startIndex The index point where "getReal" function started - * @return void - */ - protected function processOneLineComments($startIndex) - { - $thirdCommentString = $this->index < $this->len ? $this->input[$this->index] : false; - - // kill rest of line - $this->getNext("\n"); - - unset($this->c); - - if ($thirdCommentString == '@') { - $endPoint = $this->index - $startIndex; - $this->c = "\n" . substr($this->input, $startIndex, $endPoint); - } - } - - /** - * Skips multiline comments where appropriate, and includes them where needed. - * Conditional comments and "license" style blocks are preserved. - * - * @param int $startIndex The index point where "getReal" function started - * @return void - * @throws \RuntimeException Unclosed comments will throw an error - */ - protected function processMultiLineComments($startIndex) - { - $this->getChar(); // current C - $thirdCommentString = $this->getChar(); - - // kill everything up to the next */ if it's there - if ($this->getNext('*/')) { - $this->getChar(); // get * - $this->getChar(); // get / - $char = $this->getChar(); // get next real character - - // Now we reinsert conditional comments and YUI-style licensing comments - if (($this->options['flaggedComments'] && $thirdCommentString === '!') - || ($thirdCommentString === '@')) { - - // If conditional comments or flagged comments are not the first thing in the script - // we need to echo a and fill it with a space before moving on. - if ($startIndex > 0) { - echo $this->a; - $this->a = " "; - - // If the comment started on a new line we let it stay on the new line - if ($this->input[($startIndex - 1)] === "\n") { - echo "\n"; - } - } - - $endPoint = ($this->index - 1) - $startIndex; - echo substr($this->input, $startIndex, $endPoint); - - $this->c = $char; - - return; - } - } else { - $char = false; - } - - if ($char === false) { - throw new \RuntimeException('Unclosed multiline comment at position: ' . ($this->index - 2)); - } - - // if we're here c is part of the comment and therefore tossed - $this->c = $char; - } - - /** - * Pushes the index ahead to the next instance of the supplied string. If it - * is found the first character of the string is returned and the index is set - * to it's position. - * - * @param string $string - * @return string|false Returns the first character of the string or false. - */ - protected function getNext($string) - { - // Find the next occurrence of "string" after the current position. - $pos = strpos($this->input, $string, $this->index); - - // If it's not there return false. - if ($pos === false) { - return false; - } - - // Adjust position of index to jump ahead to the asked for string - $this->index = $pos; - - // Return the first character of that string. - return $this->index < $this->len ? $this->input[$this->index] : false; - } - - /** - * When a javascript string is detected this function crawls for the end of - * it and saves the whole string. - * - * @throws \RuntimeException Unclosed strings will throw an error - */ - protected function saveString() - { - $startpos = $this->index; - - // saveString is always called after a gets cleared, so we push b into - // that spot. - $this->a = $this->b; - - // If this isn't a string we don't need to do anything. - if (!isset($this->stringDelimiters[$this->a])) { - return; - } - - // String type is the quote used, " or ' - $stringType = $this->a; - - // Echo out that starting quote - echo $this->a; - - // Loop until the string is done - // Grab the very next character and load it into a - while (($this->a = $this->getChar()) !== false) { - switch ($this->a) { - - // If the string opener (single or double quote) is used - // output it and break out of the while loop- - // The string is finished! - case $stringType: - break 2; - - // New lines in strings without line delimiters are bad- actual - // new lines will be represented by the string \n and not the actual - // character, so those will be treated just fine using the switch - // block below. - case "\n": - if ($stringType === '`') { - echo $this->a; - } else { - throw new \RuntimeException('Unclosed string at position: ' . $startpos); - } - break; - - // Escaped characters get picked up here. If it's an escaped new line it's not really needed - case '\\': - - // a is a slash. We want to keep it, and the next character, - // unless it's a new line. New lines as actual strings will be - // preserved, but escaped new lines should be reduced. - $this->b = $this->getChar(); - - // If b is a new line we discard a and b and restart the loop. - if ($this->b === "\n") { - break; - } - - // echo out the escaped character and restart the loop. - echo $this->a . $this->b; - break; - - - // Since we're not dealing with any special cases we simply - // output the character and continue our loop. - default: - echo $this->a; - } - } - } - - /** - * When a regular expression is detected this function crawls for the end of - * it and saves the whole regex. - * - * @throws \RuntimeException Unclosed regex will throw an error - */ - protected function saveRegex() - { - echo $this->a . $this->b; - - while (($this->a = $this->getChar()) !== false) { - if ($this->a === '/') { - break; - } - - if ($this->a === '\\') { - echo $this->a; - $this->a = $this->getChar(); - } - - if ($this->a === "\n") { - throw new \RuntimeException('Unclosed regex pattern at position: ' . $this->index); - } - - echo $this->a; - } - $this->b = $this->getReal(); - } - - /** - * Checks to see if a character is alphanumeric. - * - * @param string $char Just one character - * @return bool - */ - protected static function isAlphaNumeric($char) - { - return preg_match('/^[\w\$\pL]$/', $char) === 1 || $char == '/'; - } - - /** - * Replace patterns in the given string and store the replacement - * - * @param string $js The string to lock - * @return bool - */ - protected function lock($js) - { - /* lock things like "asd" + ++x; */ - $lock = '"LOCK---' . crc32(time()) . '"'; - - $matches = []; - preg_match('/([+-])(\s+)([+-])/S', $js, $matches); - if (empty($matches)) { - return $js; - } - - $this->locks[$lock] = $matches[2]; - - $js = preg_replace('/([+-])\s+([+-])/S', "$1{$lock}$2", $js); - /* -- */ - - return $js; - } - - /** - * Replace "locks" with the original characters - * - * @param string $js The string to unlock - * @return bool - */ - protected function unlock($js) - { - if (empty($this->locks)) { - return $js; - } - - foreach ($this->locks as $lock => $replacement) { - $js = str_replace($lock, $replacement, $js); - } - - return $js; - } -} + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * JShrink + * + * + * @package JShrink + * @author Robert Hafner + */ + +namespace JShrink; + +/** + * Minifier + * + * Usage - Minifier::minify($js); + * Usage - Minifier::minify($js, $options); + * Usage - Minifier::minify($js, array('flaggedComments' => false)); + * + * @package JShrink + * @author Robert Hafner + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + */ +class Minifier +{ + /** + * The input javascript to be minified. + * + * @var string + */ + protected $input; + + /** + * Length of input javascript. + * + * @var int + */ + protected $len = 0; + + /** + * The location of the character (in the input string) that is next to be + * processed. + * + * @var int + */ + protected $index = 0; + + /** + * The first of the characters currently being looked at. + * + * @var string + */ + protected $a = ''; + + /** + * The next character being looked at (after a); + * + * @var string + */ + protected $b = ''; + + /** + * This character is only active when certain look ahead actions take place. + * + * @var string + */ + protected $c; + + /** + * Contains the options for the current minification process. + * + * @var array + */ + protected $options; + + /** + * These characters are used to define strings. + */ + protected $stringDelimiters = ['\'' => true, '"' => true, '`' => true]; + + /** + * Contains the default options for minification. This array is merged with + * the one passed in by the user to create the request specific set of + * options (stored in the $options attribute). + * + * @var array + */ + protected static $defaultOptions = ['flaggedComments' => true]; + + /** + * Contains lock ids which are used to replace certain code patterns and + * prevent them from being minified + * + * @var array + */ + protected $locks = []; + + /** + * Takes a string containing javascript and removes unneeded characters in + * order to shrink the code without altering it's functionality. + * + * @param string $js The raw javascript to be minified + * @param array $options Various runtime options in an associative array + * @throws \Exception + * @return bool|string + */ + public static function minify($js, $options = []) + { + try { + ob_start(); + + $jshrink = new Minifier(); + $js = $jshrink->lock($js); + $jshrink->minifyDirectToOutput($js, $options); + + // Sometimes there's a leading new line, so we trim that out here. + $js = ltrim(ob_get_clean()); + $js = $jshrink->unlock($js); + unset($jshrink); + + return $js; + } catch (\Exception $e) { + if (isset($jshrink)) { + // Since the breakdownScript function probably wasn't finished + // we clean it out before discarding it. + $jshrink->clean(); + unset($jshrink); + } + + // without this call things get weird, with partially outputted js. + ob_end_clean(); + throw $e; + } + } + + /** + * Processes a javascript string and outputs only the required characters, + * stripping out all unneeded characters. + * + * @param string $js The raw javascript to be minified + * @param array $options Various runtime options in an associative array + */ + protected function minifyDirectToOutput($js, $options) + { + $this->initialize($js, $options); + $this->loop(); + $this->clean(); + } + + /** + * Initializes internal variables, normalizes new lines, + * + * @param string $js The raw javascript to be minified + * @param array $options Various runtime options in an associative array + */ + protected function initialize($js, $options) + { + $this->options = array_merge(static::$defaultOptions, $options); + $this->input = str_replace(["\r\n", '/**/', "\r"], ["\n", "", "\n"], $js); + + // We add a newline to the end of the script to make it easier to deal + // with comments at the bottom of the script- this prevents the unclosed + // comment error that can otherwise occur. + $this->input .= PHP_EOL; + + // save input length to skip calculation every time + $this->len = strlen($this->input); + + // Populate "a" with a new line, "b" with the first character, before + // entering the loop + $this->a = "\n"; + $this->b = $this->getReal(); + } + + /** + * Characters that can't stand alone preserve the newline. + * + * @var array + */ + protected $noNewLineCharacters = [ + '(' => true, + '-' => true, + '+' => true, + '[' => true, + '@' => true, ]; + + /** + * The primary action occurs here. This function loops through the input string, + * outputting anything that's relevant and discarding anything that is not. + */ + protected function loop() + { + while ($this->a !== false && !is_null($this->a) && $this->a !== '') { + switch ($this->a) { + // new lines + case "\n": + // if the next line is something that can't stand alone preserve the newline + if ($this->b !== false && isset($this->noNewLineCharacters[$this->b])) { + echo $this->a; + $this->saveString(); + break; + } + + // if B is a space we skip the rest of the switch block and go down to the + // string/regex check below, resetting $this->b with getReal + if ($this->b === ' ') { + break; + } + + // otherwise we treat the newline like a space + + // no break + case ' ': + if (static::isAlphaNumeric($this->b)) { + echo $this->a; + } + + $this->saveString(); + break; + + default: + switch ($this->b) { + case "\n": + if (strpos('}])+-"\'', $this->a) !== false) { + echo $this->a; + $this->saveString(); + break; + } else { + if (static::isAlphaNumeric($this->a)) { + echo $this->a; + $this->saveString(); + } + } + break; + + case ' ': + if (!static::isAlphaNumeric($this->a)) { + break; + } + + // no break + default: + // check for some regex that breaks stuff + if ($this->a === '/' && ($this->b === '\'' || $this->b === '"')) { + $this->saveRegex(); + continue 3; + } + + echo $this->a; + $this->saveString(); + break; + } + } + + // do reg check of doom + $this->b = $this->getReal(); + + if (($this->b == '/' && strpos('(,=:[!&|?', $this->a) !== false)) { + $this->saveRegex(); + } + } + } + + /** + * Resets attributes that do not need to be stored between requests so that + * the next request is ready to go. Another reason for this is to make sure + * the variables are cleared and are not taking up memory. + */ + protected function clean() + { + unset($this->input); + $this->len = 0; + $this->index = 0; + $this->a = $this->b = ''; + unset($this->c); + unset($this->options); + } + + /** + * Returns the next string for processing based off of the current index. + * + * @return string + */ + protected function getChar() + { + // Check to see if we had anything in the look ahead buffer and use that. + if (isset($this->c)) { + $char = $this->c; + unset($this->c); + } else { + // Otherwise we start pulling from the input. + $char = $this->index < $this->len ? $this->input[$this->index] : false; + + // If the next character doesn't exist return false. + if (isset($char) && $char === false) { + return false; + } + + // Otherwise increment the pointer and use this char. + $this->index++; + } + + // Normalize all whitespace except for the newline character into a + // standard space. + if ($char !== "\n" && $char < "\x20") { + return ' '; + } + + return $char; + } + + /** + * This function gets the next "real" character. It is essentially a wrapper + * around the getChar function that skips comments. This has significant + * performance benefits as the skipping is done using native functions (ie, + * c code) rather than in script php. + * + * + * @return string Next 'real' character to be processed. + * @throws \RuntimeException + */ + protected function getReal() + { + $startIndex = $this->index; + $char = $this->getChar(); + + // Check to see if we're potentially in a comment + if ($char !== '/') { + return $char; + } + + $this->c = $this->getChar(); + + if ($this->c === '/') { + $this->processOneLineComments($startIndex); + + return $this->getReal(); + } elseif ($this->c === '*') { + $this->processMultiLineComments($startIndex); + + return $this->getReal(); + } + + return $char; + } + + /** + * Removed one line comments, with the exception of some very specific types of + * conditional comments. + * + * @param int $startIndex The index point where "getReal" function started + * @return void + */ + protected function processOneLineComments($startIndex) + { + $thirdCommentString = $this->index < $this->len ? $this->input[$this->index] : false; + + // kill rest of line + $this->getNext("\n"); + + unset($this->c); + + if ($thirdCommentString == '@') { + $endPoint = $this->index - $startIndex; + $this->c = "\n" . substr($this->input, $startIndex, $endPoint); + } + } + + /** + * Skips multiline comments where appropriate, and includes them where needed. + * Conditional comments and "license" style blocks are preserved. + * + * @param int $startIndex The index point where "getReal" function started + * @return void + * @throws \RuntimeException Unclosed comments will throw an error + */ + protected function processMultiLineComments($startIndex) + { + $this->getChar(); // current C + $thirdCommentString = $this->getChar(); + + // kill everything up to the next */ if it's there + if ($this->getNext('*/')) { + $this->getChar(); // get * + $this->getChar(); // get / + $char = $this->getChar(); // get next real character + + // Now we reinsert conditional comments and YUI-style licensing comments + if (($this->options['flaggedComments'] && $thirdCommentString === '!') + || ($thirdCommentString === '@')) { + + // If conditional comments or flagged comments are not the first thing in the script + // we need to echo a and fill it with a space before moving on. + if ($startIndex > 0) { + echo $this->a; + $this->a = " "; + + // If the comment started on a new line we let it stay on the new line + if ($this->input[($startIndex - 1)] === "\n") { + echo "\n"; + } + } + + $endPoint = ($this->index - 1) - $startIndex; + echo substr($this->input, $startIndex, $endPoint); + + $this->c = $char; + + return; + } + } else { + $char = false; + } + + if ($char === false) { + throw new \RuntimeException('Unclosed multiline comment at position: ' . ($this->index - 2)); + } + + // if we're here c is part of the comment and therefore tossed + $this->c = $char; + } + + /** + * Pushes the index ahead to the next instance of the supplied string. If it + * is found the first character of the string is returned and the index is set + * to it's position. + * + * @param string $string + * @return string|false Returns the first character of the string or false. + */ + protected function getNext($string) + { + // Find the next occurrence of "string" after the current position. + $pos = strpos($this->input, $string, $this->index); + + // If it's not there return false. + if ($pos === false) { + return false; + } + + // Adjust position of index to jump ahead to the asked for string + $this->index = $pos; + + // Return the first character of that string. + return $this->index < $this->len ? $this->input[$this->index] : false; + } + + /** + * When a javascript string is detected this function crawls for the end of + * it and saves the whole string. + * + * @throws \RuntimeException Unclosed strings will throw an error + */ + protected function saveString() + { + $startpos = $this->index; + + // saveString is always called after a gets cleared, so we push b into + // that spot. + $this->a = $this->b; + + // If this isn't a string we don't need to do anything. + if (!isset($this->stringDelimiters[$this->a])) { + return; + } + + // String type is the quote used, " or ' + $stringType = $this->a; + + // Echo out that starting quote + echo $this->a; + + // Loop until the string is done + // Grab the very next character and load it into a + while (($this->a = $this->getChar()) !== false) { + switch ($this->a) { + + // If the string opener (single or double quote) is used + // output it and break out of the while loop- + // The string is finished! + case $stringType: + break 2; + + // New lines in strings without line delimiters are bad- actual + // new lines will be represented by the string \n and not the actual + // character, so those will be treated just fine using the switch + // block below. + case "\n": + if ($stringType === '`') { + echo $this->a; + } else { + throw new \RuntimeException('Unclosed string at position: ' . $startpos); + } + break; + + // Escaped characters get picked up here. If it's an escaped new line it's not really needed + case '\\': + + // a is a slash. We want to keep it, and the next character, + // unless it's a new line. New lines as actual strings will be + // preserved, but escaped new lines should be reduced. + $this->b = $this->getChar(); + + // If b is a new line we discard a and b and restart the loop. + if ($this->b === "\n") { + break; + } + + // echo out the escaped character and restart the loop. + echo $this->a . $this->b; + break; + + + // Since we're not dealing with any special cases we simply + // output the character and continue our loop. + default: + echo $this->a; + } + } + } + + /** + * When a regular expression is detected this function crawls for the end of + * it and saves the whole regex. + * + * @throws \RuntimeException Unclosed regex will throw an error + */ + protected function saveRegex() + { + echo $this->a . $this->b; + + while (($this->a = $this->getChar()) !== false) { + if ($this->a === '/') { + break; + } + + if ($this->a === '\\') { + echo $this->a; + $this->a = $this->getChar(); + } + + if ($this->a === "\n") { + throw new \RuntimeException('Unclosed regex pattern at position: ' . $this->index); + } + + echo $this->a; + } + $this->b = $this->getReal(); + } + + /** + * Checks to see if a character is alphanumeric. + * + * @param string $char Just one character + * @return bool + */ + protected static function isAlphaNumeric($char) + { + return preg_match('/^[\w\$\pL]$/', $char) === 1 || $char == '/'; + } + + /** + * Replace patterns in the given string and store the replacement + * + * @param string $js The string to lock + * @return bool + */ + protected function lock($js) + { + /* lock things like "asd" + ++x; */ + $lock = '"LOCK---' . crc32(time()) . '"'; + + $matches = []; + preg_match('/([+-])(\s+)([+-])/S', $js, $matches); + if (empty($matches)) { + return $js; + } + + $this->locks[$lock] = $matches[2]; + + $js = preg_replace('/([+-])\s+([+-])/S', "$1{$lock}$2", $js); + /* -- */ + + return $js; + } + + /** + * Replace "locks" with the original characters + * + * @param string $js The string to unlock + * @return bool + */ + protected function unlock($js) + { + if (empty($this->locks)) { + return $js; + } + + foreach ($this->locks as $lock => $replacement) { + $js = str_replace($lock, $replacement, $js); + } + + return $js; + } +} diff --git a/objects/like.json.php b/objects/like.json.php index 126c237278..fcc6627bf3 100644 --- a/objects/like.json.php +++ b/objects/like.json.php @@ -1,19 +1,19 @@ -login(false, true); -} -if(empty($_POST['videos_id']) && !empty($_GET['videos_id'])){ - $_POST['videos_id'] = $_GET['videos_id']; -} - -$like = new Like($_GET['like'], $_POST['videos_id']); -echo json_encode(Video::getVideoLikes($_POST['videos_id'])); +login(false, true); +} +if (empty($_POST['videos_id']) && !empty($_GET['videos_id'])) { + $_POST['videos_id'] = $_GET['videos_id']; +} + +$like = new Like($_GET['like'], $_POST['videos_id']); +echo json_encode(Video::getVideoLikes($_POST['videos_id'])); diff --git a/objects/like.php b/objects/like.php index 9a58dad42a..5633ae6f53 100644 --- a/objects/like.php +++ b/objects/like.php @@ -1,192 +1,193 @@ -videos_id = $videos_id; - $this->users_id = User::getId(); - $this->load(); - // if click again in the same vote, remove the vote - if ($this->like == $like) { - $like = 0; - if($this->like==1){ - Video::updateLikesDislikes($videos_id, 'likes', '-1'); - }else if($this->like==-1){ - Video::updateLikesDislikes($videos_id, 'dislikes', '-1'); - } - }else{ - if(!empty($this->like)){ - // need to remove some like or dislike - if($like==1){ - Video::updateLikesDislikes($videos_id, 'dislikes', '-1'); - }else if($like==-1){ - Video::updateLikesDislikes($videos_id, 'likes', '-1'); - } - } - if($like==1){ - Video::updateLikesDislikes($videos_id, 'likes', '+1'); - }else if($like==-1){ - Video::updateLikesDislikes($videos_id, 'dislikes', '+1'); - } - } - //exit; - $this->setLike($like); - $saved = $this->save(); - } - - private function setLike($like) - { - $like = intval($like); - if (!in_array($like, array(0,1,-1))) { - $like = 0; - } - $this->like = $like; - } - - private function load() - { - $like = $this->getLike(); - if (empty($like)) { - return false; - } - foreach ($like as $key => $value) { - $this->$key = $value; - } - } - - private function getLike() - { - global $global; - if (empty($this->users_id) || empty($this->videos_id)) { - header('Content-Type: application/json'); - die('{"error":"You must have user and videos set to get a like"}'); - } - $sql = "SELECT * FROM likes WHERE users_id = ? AND videos_id = ".$this->videos_id." LIMIT 1;"; - $res = sqlDAL::readSql($sql, "i", array($this->users_id)); - $dbLike = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return $dbLike; - } - - private function save() - { - global $global; - if (!User::isLogged()) { - header('Content-Type: application/json'); - die('{"error":"'.__("Permission denied").'"}'); - } - if (!empty($this->id)) { - $sql = "UPDATE likes SET `like` = ?, modified = now() WHERE id = ?;"; - $res = sqlDAL::writeSql($sql, "ii", array($this->like, $this->id)); - } else { - $sql = "INSERT INTO likes (`like`,users_id, videos_id, created, modified) VALUES (?, ?, ?, now(), now());"; - $res = sqlDAL::writeSql($sql, "iii", array($this->like, $this->users_id, $this->videos_id)); - } - //echo $sql; - if ($global['mysqli']->errno!=0) { - die('Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $res; - } - - public static function getLikes($videos_id){ - global $global, $_getLikes; - - if(!isset($_getLikes)){ - $_getLikes = array(); - } - - if(!empty($_getLikes[$videos_id])){ - return $_getLikes[$videos_id]; - } - - $obj = new stdClass(); - $obj->videos_id = $videos_id; - $obj->likes = 0; - $obj->dislikes = 0; - $obj->myVote = self::getMyVote($videos_id); - - $sql = "SELECT count(*) as total FROM likes WHERE videos_id = ? AND `like` = 1 "; // like - $res = sqlDAL::readSql($sql, "i", array($videos_id)); - $row = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($global['mysqli']->errno!=0) { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->likes = intval($row['total']); - - $sql = "SELECT count(*) as total FROM likes WHERE videos_id = ? AND `like` = -1 "; // dislike - - $res = sqlDAL::readSql($sql, "i", array($videos_id)); - $row = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($global['mysqli']->errno!=0) { - die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->dislikes = intval($row['total']); - $_getLikes[$videos_id] = $obj; - return $obj; - } - - public static function getTotalLikes() - { - global $global; - - $obj = new stdClass(); - $obj->likes = 0; - $obj->dislikes = 0; - - $sql = "SELECT count(*) as total FROM likes WHERE `like` = 1 "; // like - $res = sqlDAL::readSql($sql); - $row = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!$res) { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->likes = intval($row['total']); - - $sql = "SELECT count(*) as total FROM likes WHERE `like` = -1 "; // dislike - $res = sqlDAL::readSql($sql); - $row = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!$res) { - die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $obj->dislikes = intval($row['total']); - return $obj; - } - - public static function getMyVote($videos_id) - { - global $global; - if (!User::isLogged()) { - return 0; - } - $id = User::getId(); - $sql = "SELECT `like` FROM likes WHERE videos_id = ? AND users_id = ? "; // like - - $res = sqlDAL::readSql($sql, "ii", array($videos_id,$id)); - $dbLike = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($dbLike!=false) { - return intval($dbLike['like']); - } - return 0; - } -} +videos_id = $videos_id; + $this->users_id = User::getId(); + $this->load(); + // if click again in the same vote, remove the vote + if ($this->like == $like) { + $like = 0; + if ($this->like==1) { + Video::updateLikesDislikes($videos_id, 'likes', '-1'); + } elseif ($this->like==-1) { + Video::updateLikesDislikes($videos_id, 'dislikes', '-1'); + } + } else { + if (!empty($this->like)) { + // need to remove some like or dislike + if ($like==1) { + Video::updateLikesDislikes($videos_id, 'dislikes', '-1'); + } elseif ($like==-1) { + Video::updateLikesDislikes($videos_id, 'likes', '-1'); + } + } + if ($like==1) { + Video::updateLikesDislikes($videos_id, 'likes', '+1'); + } elseif ($like==-1) { + Video::updateLikesDislikes($videos_id, 'dislikes', '+1'); + } + } + //exit; + $this->setLike($like); + $saved = $this->save(); + } + + private function setLike($like) + { + $like = intval($like); + if (!in_array($like, [0,1,-1])) { + $like = 0; + } + $this->like = $like; + } + + private function load() + { + $like = $this->getLike(); + if (empty($like)) { + return false; + } + foreach ($like as $key => $value) { + $this->$key = $value; + } + } + + private function getLike() + { + global $global; + if (empty($this->users_id) || empty($this->videos_id)) { + header('Content-Type: application/json'); + die('{"error":"You must have user and videos set to get a like"}'); + } + $sql = "SELECT * FROM likes WHERE users_id = ? AND videos_id = ".$this->videos_id." LIMIT 1;"; + $res = sqlDAL::readSql($sql, "i", [$this->users_id]); + $dbLike = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return $dbLike; + } + + private function save() + { + global $global; + if (!User::isLogged()) { + header('Content-Type: application/json'); + die('{"error":"'.__("Permission denied").'"}'); + } + if (!empty($this->id)) { + $sql = "UPDATE likes SET `like` = ?, modified = now() WHERE id = ?;"; + $res = sqlDAL::writeSql($sql, "ii", [$this->like, $this->id]); + } else { + $sql = "INSERT INTO likes (`like`,users_id, videos_id, created, modified) VALUES (?, ?, ?, now(), now());"; + $res = sqlDAL::writeSql($sql, "iii", [$this->like, $this->users_id, $this->videos_id]); + } + //echo $sql; + if ($global['mysqli']->errno!=0) { + die('Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $res; + } + + public static function getLikes($videos_id) + { + global $global, $_getLikes; + + if (!isset($_getLikes)) { + $_getLikes = []; + } + + if (!empty($_getLikes[$videos_id])) { + return $_getLikes[$videos_id]; + } + + $obj = new stdClass(); + $obj->videos_id = $videos_id; + $obj->likes = 0; + $obj->dislikes = 0; + $obj->myVote = self::getMyVote($videos_id); + + $sql = "SELECT count(*) as total FROM likes WHERE videos_id = ? AND `like` = 1 "; // like + $res = sqlDAL::readSql($sql, "i", [$videos_id]); + $row = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($global['mysqli']->errno!=0) { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->likes = intval($row['total']); + + $sql = "SELECT count(*) as total FROM likes WHERE videos_id = ? AND `like` = -1 "; // dislike + + $res = sqlDAL::readSql($sql, "i", [$videos_id]); + $row = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($global['mysqli']->errno!=0) { + die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->dislikes = intval($row['total']); + $_getLikes[$videos_id] = $obj; + return $obj; + } + + public static function getTotalLikes() + { + global $global; + + $obj = new stdClass(); + $obj->likes = 0; + $obj->dislikes = 0; + + $sql = "SELECT count(*) as total FROM likes WHERE `like` = 1 "; // like + $res = sqlDAL::readSql($sql); + $row = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!$res) { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->likes = intval($row['total']); + + $sql = "SELECT count(*) as total FROM likes WHERE `like` = -1 "; // dislike + $res = sqlDAL::readSql($sql); + $row = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!$res) { + die($sql.'\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $obj->dislikes = intval($row['total']); + return $obj; + } + + public static function getMyVote($videos_id) + { + global $global; + if (!User::isLogged()) { + return 0; + } + $id = User::getId(); + $sql = "SELECT `like` FROM likes WHERE videos_id = ? AND users_id = ? "; // like + + $res = sqlDAL::readSql($sql, "ii", [$videos_id,$id]); + $dbLike = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($dbLike!=false) { + return intval($dbLike['like']); + } + return 0; + } +} diff --git a/objects/likes.edit.json.php b/objects/likes.edit.json.php index 4dc6af3fcc..7859038085 100644 --- a/objects/likes.edit.json.php +++ b/objects/likes.edit.json.php @@ -1,5 +1,4 @@ doNotShowImportMP4Button)) { - return false; -} -$global['allowed'] = array('mp4'); -$files = array(); -if (!empty($_POST['path'])) { - $path = $_POST['path']; - if (substr($path, -1) !== '/') { - $path .= "/"; - } - - if (file_exists($path)) { - $filesStr = "{*." . implode(",*.", $global['allowed']) . "}"; - - //echo $files; - $video_array = glob($path . $filesStr, GLOB_BRACE); - - $id = 0; - foreach ($video_array as $key => $value) { - $path_parts = pathinfo($value); - $obj = new stdClass(); - $obj->id = $id++; - $obj->path = mb_convert_encoding($value, 'UTF-8'); - $obj->name = mb_convert_encoding($path_parts['basename'], 'UTF-8'); - $files[] = $obj; - } - } -} -echo json_encode($files); +doNotShowImportMP4Button)) { + return false; +} +$global['allowed'] = ['mp4']; +$files = []; +if (!empty($_POST['path'])) { + $path = $_POST['path']; + if (substr($path, -1) !== '/') { + $path .= "/"; + } + + if (file_exists($path)) { + $filesStr = "{*." . implode(",*.", $global['allowed']) . "}"; + + //echo $files; + $video_array = glob($path . $filesStr, GLOB_BRACE); + + $id = 0; + foreach ($video_array as $key => $value) { + $path_parts = pathinfo($value); + $obj = new stdClass(); + $obj->id = $id++; + $obj->path = mb_convert_encoding($value, 'UTF-8'); + $obj->name = mb_convert_encoding($path_parts['basename'], 'UTF-8'); + $files[] = $obj; + } + } +} +echo json_encode($files); diff --git a/objects/login.json.php b/objects/login.json.php index 409a13b8ca..87d75e2468 100644 --- a/objects/login.json.php +++ b/objects/login.json.php @@ -1,330 +1,329 @@ - $value) { - $_POST[$key] = $value; - } -} - -TimeLogEnd($timeLog, __LINE__); - -require_once $global['systemRootPath'] . 'videos/configuration.php'; -require_once $global['systemRootPath'] . 'objects/user.php'; -require_once $global['systemRootPath'] . 'objects/category.php'; - -Category::clearCacheCount(); -TimeLogEnd($timeLog, __LINE__); - -if (!preg_match("|^" . $global['webSiteRootURL'] . "|", $_POST['redirectUri'])) { - $_POST['redirectUri'] = $global['webSiteRootURL']; -} -_error_log("Start Login Request redirectUri=" . $_POST['redirectUri']); - -use Hybridauth\Hybridauth; -use Hybridauth\HttpClient; - -TimeLogEnd($timeLog, __LINE__); -if (!empty($_GET['type'])) { - if (!empty($_GET['redirectUri'])) { - _session_start(); - $_SESSION['redirectUri'] = getRedirectUri(); - } - if ($_GET['type'] === "Apple") { - $obj = AVideoPlugin::getDataObjectIfEnabled('LoginApple'); - if (empty($obj)) { - die('Apple Login is disabled'); - } - $config = [ - 'callback' => HttpClient\Util::getCurrentUrl() . "?type={$_GET['type']}", - 'providers' => [ - $_GET['type'] => [ - "enabled" => true, - "keys" => [ - "id" => trim($obj->id), - "team_id" => trim($obj->team_id), - "key_id" => trim($obj->key_id), - "key_content" => trim($obj->key_content->value) - ], - "scope" => "name email", - "verifyTokenSignature" => true - ] - ], - /* optional : set debug mode - 'debug_mode' => true, - // Path to file writable by the web server. Required if 'debug_mode' is not false - 'debug_file' => __FILE__ . '.log', */ - ]; - } else { - $login = AVideoPlugin::getLogin(); - foreach ($login as $value) { - $obj = $value['loginObject']->getDataObject(); - if ($value['parameters']->type === $_GET['type']) { - $id = $obj->id; - $key = $obj->key; - break; - } - } - if (empty($id)) { - die(sprintf(__("%s ERROR: You must set an ID on config"), $_GET['type'])); - } - - if (empty($key)) { - die(sprintf(__("%s ERROR: You must set a KEY on config"), $_GET['type'])); - } - $scope = 'email'; - if ($_GET['type'] === "Yahoo") { - $scope = 'sdpp-w'; - } - if ($_GET['type'] === 'LinkedIn') { - $scope = ("r_liteprofile r_emailaddress w_member_social"); - } - - $config = [ - 'callback' => HttpClient\Util::getCurrentUrl() . "?type={$_GET['type']}", - 'providers' => [ - $_GET['type'] => [ - 'enabled' => true, - 'keys' => ['id' => $id, 'secret' => $key, 'key' => $id], - "includeEmail" => true, - 'scope' => $scope, - 'trustForwarded' => false - ] - ], - /* optional : set debug mode - 'debug_mode' => true, - // Path to file writeable by the web server. Required if 'debug_mode' is not false - 'debug_file' => __FILE__ . '.log', */ - ]; - } - try { - $hybridauth = new Hybridauth($config); - - $adapter = $hybridauth->authenticate($_GET['type']); - - $tokens = $adapter->getAccessToken(); - $userProfile = $adapter->getUserProfile(); - - //print_r($tokens); - //print_r($userProfile); - if (!empty($userProfile->email)) { - $user = $userProfile->email; - } else { - $user = $userProfile->displayName; - } - $name = $userProfile->displayName; - $photoURL = $userProfile->photoURL; - $email = $userProfile->email; - $pass = rand(); - //createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false); - User::createUserIfNotExists($user, $pass, $name, $email, $photoURL, false, true); - $userObject = new User(0, $user, $pass); - $userObject->login(true); - $adapter->disconnect(); - - if (!empty($_SESSION['redirectUri'])) { - _session_start(); - $location = $_SESSION['redirectUri']; - //header("Location: {$_SESSION['redirectUri']}"); - $_SESSION['redirectUri'] = ""; - unset($_SESSION['redirectUri']); - } else { - $location = $global['webSiteRootURL']; - //header("Location: {$global['webSiteRootURL']}"); - } - } catch (\Exception $e) { - $location = "{$global['webSiteRootURL']}user?error=" . urlencode($e->getMessage()); - //header("Location: {$global['webSiteRootURL']}user?error=" . urlencode($e->getMessage())); - //echo $e->getMessage(); - } - if(!isSameDomainAsMyAVideo($location)){ - $location = $global['webSiteRootURL']; - } - header('Content-Type: text/html'); - ?> - - error = __("User and Password can not be blank"); - die(json_encode($object)); -} -$user = new User(0, $_POST['user'], $_POST['pass']); - -_error_log("login.json.php trying to login"); -$resp = $user->login(false, @$_POST['encodedPass']); -_error_log("login.json.php login respond something"); -TimeLogEnd($timeLog, __LINE__); -$object->isCaptchaNeed = User::isCaptchaNeed(); -if ($resp === User::USER_NOT_VERIFIED) { - _error_log("login.json.php User not verified"); - $object->error = __("Your user is not verified, we sent you a new e-mail"); - die(json_encode($object)); -} - -if ($resp === User::CAPTCHA_ERROR) { - _error_log("login.json.php invalid captcha"); - $object->error = __("Invalid Captcha"); - die(json_encode($object)); -} - -if ($resp === User::REQUIRE2FA) { - _error_log("login.json.php 2fa login is required"); - $object->error = __("2FA login is required"); - die(json_encode($object)); -} - -//_error_log("login.json.php setup object"); -$object->siteLogo = $global['webSiteRootURL'] . $config->getLogo(); -$object->id = User::getId(); -$object->user = User::getUserName(); -$object->donationLink = User::donationLink(); -$object->name = User::getName(); -//_error_log("login.json.php get name identification"); -$object->nameIdentification = User::getNameIdentification(); -$object->pass = User::getUserPass(); -$object->email = User::getMail(); -//_error_log("login.json.php get channel name"); -$object->channelName = User::_getChannelName($object->id); -$object->photo = User::getPhoto(); -$object->backgroundURL = User::getBackground($object->id); -$object->isLogged = User::isLogged(); -$object->isAdmin = User::isAdmin(); -$object->canUpload = User::canUpload(); -$object->canComment = User::canComment(); -$object->canMeet = AVideoPlugin::isEnabledByName('Meet'); -$object->canCreateCategory = Category::canCreateCategory(); -$object->theme = getCurrentTheme(); -$object->canStream = User::canStream(); -$object->redirectUri = @$_POST['redirectUri']; -$object->embedChatUrl = ''; -$object->embedChatUrlMobile = ''; -if (AVideoPlugin::isEnabledByName('Chat2') && method_exists('Chat2', 'getChatRoomLink')) { - $object->embedChatUrl = Chat2::getChatRoomLink(User::getId(), 1, 1, 0, true); - $object->embedChatUrlMobile = addQueryStringParameter($object->embedChatUrl, 'mobileMode', 1); - $object->embedChatUrlMobile = addQueryStringParameter($object->embedChatUrlMobile, 'user', $object->user); - $object->embedChatUrlMobile = addQueryStringParameter($object->embedChatUrlMobile, 'pass', $object->pass); -} -//_error_log("login.json.php setup object done"); - -if ((empty($object->redirectUri) || $object->redirectUri === $global['webSiteRootURL'])) { - if (!empty($advancedCustomUser->afterLoginGoToMyChannel)) { - $object->redirectUri = User::getChannelLink(); - } elseif (!empty($advancedCustomUser->afterLoginGoToURL)) { - $object->redirectUri = $advancedCustomUser->afterLoginGoToURL; - } -} - -if (empty($advancedCustomUser->userCanNotChangeCategory) || User::isAdmin()) { - //_error_log("login.json.php get categories"); - $object->categories = Category::getAllCategories(true); - if (is_array($object->categories)) { - array_multisort(array_column($object->categories, 'hierarchyAndName'), SORT_ASC, $object->categories); - } -} else { - $object->categories = array(); -} -//_error_log("login.json.php get user groups"); -TimeLogEnd($timeLog, __LINE__); -$object->userGroups = UserGroups::getAllUsersGroups(); -TimeLogEnd($timeLog, __LINE__); -$object->streamServerURL = ""; -$object->streamKey = ""; -if ($object->isLogged) { - $timeLog2 = __FILE__ . "::Is Logged "; - TimeLogStart($timeLog2); - - //_error_log("login.json.php get Live"); - $p = AVideoPlugin::loadPluginIfEnabled("Live"); - if (!empty($p)) { - require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php'; - $trasnmition = LiveTransmition::createTransmitionIfNeed(User::getId()); - if (!empty($trasnmition)) { - $object->streamServerURL = $p->getServer() . "?p=" . User::getUserPass(); - $object->streamKey = $trasnmition['key']; - } else { - _error_log('login.json.php transmissionKey is empty [' . User::getId() . ']'); - } - } else { - _error_log('login.json.php live plugin is disabled'); - } - TimeLogEnd($timeLog2, __LINE__); - //_error_log("login.json.php get MobileManager"); - $p = AVideoPlugin::loadPluginIfEnabled("MobileManager"); - if (!empty($p)) { - $object->streamer = _json_decode(url_get_contents($global['webSiteRootURL'] . "objects/status.json.php")); - $object->plugin = $p->getDataObject(); - $object->encoder = $config->getEncoderURL(); - } - TimeLogEnd($timeLog2, __LINE__); - //_error_log("login.json.php get VideoHLS"); - $p = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); - if (!empty($p)) { - $object->videoHLS = true; - } - TimeLogEnd($timeLog2, __LINE__); - //_error_log("login.json.php get Subscriptions"); - $p = AVideoPlugin::loadPluginIfEnabled("Subscription"); - if (!empty($p)) { - $object->Subscription = Subscription::getAllFromUser($object->id); - } - TimeLogEnd($timeLog2, __LINE__); - //_error_log("login.json.php get PayPerView"); - $p = AVideoPlugin::loadPluginIfEnabled("PayPerView"); - if (!empty($p) && class_exists('PayPerView')) { - $object->PayPerView = PayPerView::getAllPPVFromUser($object->id); - } - TimeLogEnd($timeLog2, __LINE__); -} else { - _error_log('login.json.php is not logged'); -} - -$object->PHPSESSID = session_id(); - -TimeLogEnd($timeLog, __LINE__); -//_error_log("login.json.php almost complete"); -$json = _json_encode($object); -//_error_log("login.json.php complete"); -//header("Content-length: " . strlen($json)); -_error_log('login.json.php is done'); -echo $json; + $value) { + $_POST[$key] = $value; + } +} + +TimeLogEnd($timeLog, __LINE__); + +require_once $global['systemRootPath'] . 'videos/configuration.php'; +require_once $global['systemRootPath'] . 'objects/user.php'; +require_once $global['systemRootPath'] . 'objects/category.php'; + +Category::clearCacheCount(); +TimeLogEnd($timeLog, __LINE__); + +if (!preg_match("|^" . $global['webSiteRootURL'] . "|", $_POST['redirectUri'])) { + $_POST['redirectUri'] = $global['webSiteRootURL']; +} +_error_log("Start Login Request redirectUri=" . $_POST['redirectUri']); + +use Hybridauth\Hybridauth; +use Hybridauth\HttpClient; + +TimeLogEnd($timeLog, __LINE__); +if (!empty($_GET['type'])) { + if (!empty($_GET['redirectUri'])) { + _session_start(); + $_SESSION['redirectUri'] = getRedirectUri(); + } + if ($_GET['type'] === "Apple") { + $obj = AVideoPlugin::getDataObjectIfEnabled('LoginApple'); + if (empty($obj)) { + die('Apple Login is disabled'); + } + $config = [ + 'callback' => HttpClient\Util::getCurrentUrl() . "?type={$_GET['type']}", + 'providers' => [ + $_GET['type'] => [ + "enabled" => true, + "keys" => [ + "id" => trim($obj->id), + "team_id" => trim($obj->team_id), + "key_id" => trim($obj->key_id), + "key_content" => trim($obj->key_content->value), + ], + "scope" => "name email", + "verifyTokenSignature" => true, + ], + ], + /* optional : set debug mode + 'debug_mode' => true, + // Path to file writable by the web server. Required if 'debug_mode' is not false + 'debug_file' => __FILE__ . '.log', */ + ]; + } else { + $login = AVideoPlugin::getLogin(); + foreach ($login as $value) { + $obj = $value['loginObject']->getDataObject(); + if ($value['parameters']->type === $_GET['type']) { + $id = $obj->id; + $key = $obj->key; + break; + } + } + if (empty($id)) { + die(sprintf(__("%s ERROR: You must set an ID on config"), $_GET['type'])); + } + + if (empty($key)) { + die(sprintf(__("%s ERROR: You must set a KEY on config"), $_GET['type'])); + } + $scope = 'email'; + if ($_GET['type'] === "Yahoo") { + $scope = 'sdpp-w'; + } + if ($_GET['type'] === 'LinkedIn') { + $scope = ("r_liteprofile r_emailaddress w_member_social"); + } + + $config = [ + 'callback' => HttpClient\Util::getCurrentUrl() . "?type={$_GET['type']}", + 'providers' => [ + $_GET['type'] => [ + 'enabled' => true, + 'keys' => ['id' => $id, 'secret' => $key, 'key' => $id], + "includeEmail" => true, + 'scope' => $scope, + 'trustForwarded' => false, + ], + ], + /* optional : set debug mode + 'debug_mode' => true, + // Path to file writeable by the web server. Required if 'debug_mode' is not false + 'debug_file' => __FILE__ . '.log', */ + ]; + } + try { + $hybridauth = new Hybridauth($config); + + $adapter = $hybridauth->authenticate($_GET['type']); + + $tokens = $adapter->getAccessToken(); + $userProfile = $adapter->getUserProfile(); + + //print_r($tokens); + //print_r($userProfile); + if (!empty($userProfile->email)) { + $user = $userProfile->email; + } else { + $user = $userProfile->displayName; + } + $name = $userProfile->displayName; + $photoURL = $userProfile->photoURL; + $email = $userProfile->email; + $pass = rand(); + //createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false); + User::createUserIfNotExists($user, $pass, $name, $email, $photoURL, false, true); + $userObject = new User(0, $user, $pass); + $userObject->login(true); + $adapter->disconnect(); + + if (!empty($_SESSION['redirectUri'])) { + _session_start(); + $location = $_SESSION['redirectUri']; + //header("Location: {$_SESSION['redirectUri']}"); + $_SESSION['redirectUri'] = ''; + unset($_SESSION['redirectUri']); + } else { + $location = $global['webSiteRootURL']; + //header("Location: {$global['webSiteRootURL']}"); + } + } catch (\Exception $e) { + $location = "{$global['webSiteRootURL']}user?error=" . urlencode($e->getMessage()); + //header("Location: {$global['webSiteRootURL']}user?error=" . urlencode($e->getMessage())); + //echo $e->getMessage(); + } + if (!isSameDomainAsMyAVideo($location)) { + $location = $global['webSiteRootURL']; + } + header('Content-Type: text/html'); ?> + + error = __("User and Password can not be blank"); + die(json_encode($object)); +} +$user = new User(0, $_POST['user'], $_POST['pass']); + +_error_log("login.json.php trying to login"); +$resp = $user->login(false, @$_POST['encodedPass']); +_error_log("login.json.php login respond something"); +TimeLogEnd($timeLog, __LINE__); +$object->isCaptchaNeed = User::isCaptchaNeed(); +if ($resp === User::USER_NOT_VERIFIED) { + _error_log("login.json.php User not verified"); + $object->error = __("Your user is not verified, we sent you a new e-mail"); + die(json_encode($object)); +} + +if ($resp === User::CAPTCHA_ERROR) { + _error_log("login.json.php invalid captcha"); + $object->error = __("Invalid Captcha"); + die(json_encode($object)); +} + +if ($resp === User::REQUIRE2FA) { + _error_log("login.json.php 2fa login is required"); + $object->error = __("2FA login is required"); + die(json_encode($object)); +} + +//_error_log("login.json.php setup object"); +$object->siteLogo = $global['webSiteRootURL'] . $config->getLogo(); +$object->id = User::getId(); +$object->user = User::getUserName(); +$object->donationLink = User::donationLink(); +$object->name = User::getName(); +//_error_log("login.json.php get name identification"); +$object->nameIdentification = User::getNameIdentification(); +$object->pass = User::getUserPass(); +$object->email = User::getMail(); +//_error_log("login.json.php get channel name"); +$object->channelName = User::_getChannelName($object->id); +$object->photo = User::getPhoto(); +$object->backgroundURL = User::getBackground($object->id); +$object->isLogged = User::isLogged(); +$object->isAdmin = User::isAdmin(); +$object->canUpload = User::canUpload(); +$object->canComment = User::canComment(); +$object->canMeet = AVideoPlugin::isEnabledByName('Meet'); +$object->canCreateCategory = Category::canCreateCategory(); +$object->theme = getCurrentTheme(); +$object->canStream = User::canStream(); +$object->redirectUri = @$_POST['redirectUri']; +$object->embedChatUrl = ''; +$object->embedChatUrlMobile = ''; +if (AVideoPlugin::isEnabledByName('Chat2') && method_exists('Chat2', 'getChatRoomLink')) { + $object->embedChatUrl = Chat2::getChatRoomLink(User::getId(), 1, 1, 0, true); + $object->embedChatUrlMobile = addQueryStringParameter($object->embedChatUrl, 'mobileMode', 1); + $object->embedChatUrlMobile = addQueryStringParameter($object->embedChatUrlMobile, 'user', $object->user); + $object->embedChatUrlMobile = addQueryStringParameter($object->embedChatUrlMobile, 'pass', $object->pass); +} +//_error_log("login.json.php setup object done"); + +if ((empty($object->redirectUri) || $object->redirectUri === $global['webSiteRootURL'])) { + if (!empty($advancedCustomUser->afterLoginGoToMyChannel)) { + $object->redirectUri = User::getChannelLink(); + } elseif (!empty($advancedCustomUser->afterLoginGoToURL)) { + $object->redirectUri = $advancedCustomUser->afterLoginGoToURL; + } +} + +if (empty($advancedCustomUser->userCanNotChangeCategory) || User::isAdmin()) { + //_error_log("login.json.php get categories"); + $object->categories = Category::getAllCategories(true); + if (is_array($object->categories)) { + array_multisort(array_column($object->categories, 'hierarchyAndName'), SORT_ASC, $object->categories); + } +} else { + $object->categories = []; +} +//_error_log("login.json.php get user groups"); +TimeLogEnd($timeLog, __LINE__); +$object->userGroups = UserGroups::getAllUsersGroups(); +TimeLogEnd($timeLog, __LINE__); +$object->streamServerURL = ''; +$object->streamKey = ''; +if ($object->isLogged) { + $timeLog2 = __FILE__ . "::Is Logged "; + TimeLogStart($timeLog2); + + //_error_log("login.json.php get Live"); + $p = AVideoPlugin::loadPluginIfEnabled("Live"); + if (!empty($p)) { + require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php'; + $trasnmition = LiveTransmition::createTransmitionIfNeed(User::getId()); + if (!empty($trasnmition)) { + $object->streamServerURL = $p->getServer() . "?p=" . User::getUserPass(); + $object->streamKey = $trasnmition['key']; + } else { + _error_log('login.json.php transmissionKey is empty [' . User::getId() . ']'); + } + } else { + _error_log('login.json.php live plugin is disabled'); + } + TimeLogEnd($timeLog2, __LINE__); + //_error_log("login.json.php get MobileManager"); + $p = AVideoPlugin::loadPluginIfEnabled("MobileManager"); + if (!empty($p)) { + $object->streamer = _json_decode(url_get_contents($global['webSiteRootURL'] . "objects/status.json.php")); + $object->plugin = $p->getDataObject(); + $object->encoder = $config->getEncoderURL(); + } + TimeLogEnd($timeLog2, __LINE__); + //_error_log("login.json.php get VideoHLS"); + $p = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); + if (!empty($p)) { + $object->videoHLS = true; + } + TimeLogEnd($timeLog2, __LINE__); + //_error_log("login.json.php get Subscriptions"); + $p = AVideoPlugin::loadPluginIfEnabled("Subscription"); + if (!empty($p)) { + $object->Subscription = Subscription::getAllFromUser($object->id); + } + TimeLogEnd($timeLog2, __LINE__); + //_error_log("login.json.php get PayPerView"); + $p = AVideoPlugin::loadPluginIfEnabled("PayPerView"); + if (!empty($p) && class_exists('PayPerView')) { + $object->PayPerView = PayPerView::getAllPPVFromUser($object->id); + } + TimeLogEnd($timeLog2, __LINE__); +} else { + _error_log('login.json.php is not logged'); +} + +$object->PHPSESSID = session_id(); + +TimeLogEnd($timeLog, __LINE__); +//_error_log("login.json.php almost complete"); +$json = _json_encode($object); +//_error_log("login.json.php complete"); +//header("Content-length: " . strlen($json)); +_error_log('login.json.php is done'); +echo $json; diff --git a/objects/logoff.php b/objects/logoff.php index 64b89538c6..9172225ff5 100644 --- a/objects/logoff.php +++ b/objects/logoff.php @@ -1,19 +1,19 @@ -afterLogoffGoToMyChannel)) { - $redirectUri = User::getChannelLink(); -}else if (!empty($advancedCustomUser->afterLogoffGoToURL)) { - $redirectUri = $advancedCustomUser->afterLogoffGoToURL; -}else{ - $redirectUri = $global['webSiteRootURL']; -} - -User::logoff(); -Category::clearCacheCount(); -header("location: {$redirectUri}"); -exit; +afterLogoffGoToMyChannel)) { + $redirectUri = User::getChannelLink(); +} elseif (!empty($advancedCustomUser->afterLogoffGoToURL)) { + $redirectUri = $advancedCustomUser->afterLogoffGoToURL; +} else { + $redirectUri = $global['webSiteRootURL']; +} + +User::logoff(); +Category::clearCacheCount(); +header("location: {$redirectUri}"); +exit; diff --git a/objects/mainObject.php b/objects/mainObject.php index e034d84bdf..98615245a3 100644 --- a/objects/mainObject.php +++ b/objects/mainObject.php @@ -1,48 +1,51 @@ - 2) { // if there is hour - $parts2 = explode(" ", $parts[2]); - $day = $parts2[0]; - $hour = " " . $parts2[1]; - } else { - $day = $parts[2]; - $hour = ""; - } - return "{$day}/{$parts[1]}/{$parts[0]}{$hour}"; - } - } - - /** - * receive a DD/MM/YYYY - * @param type $mySqlDate - * @return String YYYY-mm-dd - */ - static public function dateBrStringToMySQL($date) { - $parts = explode("/", $date); - //switch month and day - if (empty($parts[2])) { - return $date; - } else { - if (strlen($parts[2]) > 4) { // if there is hour - $parts2 = explode(" ", $parts[2]); - $year = $parts2[0]; - $hour = " " . $parts2[1]; - } else { - $year = $parts[2]; - $hour = ""; - } - return "{$year}-{$parts[1]}-{$parts[0]}{$hour}"; - } - } -} + 2) { // if there is hour + $parts2 = explode(" ", $parts[2]); + $day = $parts2[0]; + $hour = " " . $parts2[1]; + } else { + $day = $parts[2]; + $hour = ''; + } + return "{$day}/{$parts[1]}/{$parts[0]}{$hour}"; + } + } + + /** + * receive a DD/MM/YYYY + * @param type $mySqlDate + * @return String YYYY-mm-dd + */ + public static function dateBrStringToMySQL($date) + { + $parts = explode("/", $date); + //switch month and day + if (empty($parts[2])) { + return $date; + } else { + if (strlen($parts[2]) > 4) { // if there is hour + $parts2 = explode(" ", $parts[2]); + $year = $parts2[0]; + $hour = " " . $parts2[1]; + } else { + $year = $parts[2]; + $hour = ''; + } + return "{$year}-{$parts[1]}-{$parts[0]}{$hour}"; + } + } +} diff --git a/objects/mysql_dal.php b/objects/mysql_dal.php index 0028750fcf..4e52d97e56 100644 --- a/objects/mysql_dal.php +++ b/objects/mysql_dal.php @@ -1,454 +1,468 @@ -"; - } - - OR - - while($row = sqlDAL::fetchAssoc($result)){ - echo $row['user']."
"; - } - */ - -/* - * Internal used class - */ - -class iimysqli_result { - - public $stmt, $nCols, $fields; - -} - -global $disableMysqlNdMethods; -// this is only to test both methods more easy. -$disableMysqlNdMethods = false; - -/* - * This class exists for making servers avaible, which have no mysqlnd, withouth cause a performance-issue for those who have the driver. - * It wouldn't be possible without Daan on https://stackoverflow.com/questions/31562359/workaround-for-mysqlnd-missing-driver - */ - -class sqlDAL { - - static function executeFile($filename) { - global $global; - $templine = ''; - // Read in entire file - $lines = file($filename); - // Loop through each line - 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 - if (!$global['mysqli']->query($templine)) { - _error_log('sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

', AVideoLog::$ERROR); - } - // Reset temp variable to empty - $templine = ''; - } - } - } - - /* - * For Sql like INSERT and UPDATE. The special point about this method: You do not need to close it (more direct). - * @param string $preparedStatement The Sql-command - * @param string $formats i=int,d=doube,s=string,b=blob (http://www.php.net/manual/en/mysqli-stmt.bind-param.php) - * @param array $values A array, containing the values for the prepared statement. - * @return boolean true on success, false on fail - */ - - static function writeSql($preparedStatement, $formats = "", $values = array()) { - global $global, $disableMysqlNdMethods; - if(empty($preparedStatement)){ - return false; - } - // make sure it does not store autid transactions - $debug = debug_backtrace(); - if (empty($debug[2]['class']) || $debug[2]['class'] !== "AuditTable") { - $audit = AVideoPlugin::loadPluginIfEnabled('Audit'); - if (!empty($audit)) { - try { - $audit->exec(@$debug[1]['function'], @$debug[1]['class'], $preparedStatement, $formats, json_encode($values), User::getId()); - } catch (Exception $exc) { - echo log_error($exc->getTraceAsString()); - } - } - } - - if(!is_object($global['mysqli'])){ - _mysql_connect(); - } - - if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { - log_error("[sqlDAL::writeSql] Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement})"); - return false; - } - if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { - log_error("[sqlDAL::writeSql] eval_mysql_bind failed: values and params in stmt don't match ({$preparedStatement}) with formats ({$formats})"); - return false; - } - $stmt->execute(); - if ($stmt->errno != 0) { - log_error('Error in writeSql : (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); - $stmt->close(); - return false; - } - $iid = @$global['mysqli']->insert_id; - //$global['mysqli']->affected_rows = $stmt->affected_rows; - //$stmt->commit(); - $stmt->close(); - if(!empty($iid)){ - return $iid; - }else{ - return true; - } - } - - /* - * For Sql like SELECT. This method needs to be closed anyway. If you start another readSql, while the old is open, it will fail. - * @param string $preparedStatement The Sql-command - * @param string $formats i=int,d=doube,s=string,b=blob (http://www.php.net/manual/en/mysqli-stmt.bind-param.php) - * @param array $values A array, containing the values for the prepared statement. - * @return Object Depend if mysqlnd is active or not, a object, but always false on fail - */ - - static function readSql($preparedStatement, $formats = "", $values = array(), $refreshCache = false) { - // $refreshCache = true; - global $global, $disableMysqlNdMethods, $readSqlCached, $crc; - // need to add dechex because some times it return an negative value and make it fails on javascript playlists - $crc = (md5($preparedStatement . implode($values))); - - if (!isset($readSqlCached)) { - $readSqlCached = array(); - } - if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { - - // Mysqlnd enabled - - if ((!isset($readSqlCached[$crc])) || ($refreshCache)) { - - // When not cached - - $readSqlCached[$crc] = "false"; - _mysql_connect(); - - if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { - log_error("[sqlDAL::readSql] (mysqlnd) Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement}) - format=({$formats}) values=" . json_encode($values)); - //log_error("[sqlDAL::readSql] trying close and reconnect"); - _mysql_close(); - _mysql_connect(); - if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { - log_error("[sqlDAL::readSql] (mysqlnd) Prepare failed again return false"); - return false; - }else{ - log_error("[sqlDAL::readSql] SUCCESS close and reconnect works!"); - } - } - if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { - log_error("[sqlDAL::readSql] (mysqlnd) eval_mysql_bind failed: values and params in stmt don't match {$preparedStatement} with formats {$formats}"); - return false; - } - $TimeLog = "[$preparedStatement], $formats, " . json_encode($values) . ", $refreshCache"; - TimeLogStart($TimeLog); - $stmt->execute(); - $readSqlCached[$crc] = $stmt->get_result(); - if ($stmt->errno != 0) { - log_error('Error in readSql (mysqlnd): (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); - $stmt->close(); - $disableMysqlNdMethods = true; - // try again with noMysqlND - $read = self::readSql($preparedStatement, $formats, $values, $refreshCache); - TimeLogEnd($TimeLog, "mysql_dal", 0.5); - return $read; - } - TimeLogEnd($TimeLog, "mysql_dal", 0.5); - $stmt->close(); - } else if (is_object($readSqlCached[$crc])) { - - // When cached - // reset the stmt for fetch. this solves objects/video.php line 550 - $readSqlCached[$crc]->data_seek(0); - //log_error("set dataseek to 0"); - // increase a counter for the saved queries. - if (isset($_SESSION['savedQuerys'])) { - $_SESSION['savedQuerys']++; - } - } else { - $readSqlCached[$crc] = "false"; - } - - // - // if ($readSqlCached[$crc] == "false") { - // add this in case the cache fail - // ->lenghts seems to be always NULL.. fix: $readSqlCached[$crc]->data_seek(0); above - //if("SELECT * FROM configurations WHERE id = 1 LIMIT 1"==$preparedStatement){ - // var_dump($readSqlCached[$crc]); - //} - if ($readSqlCached[$crc] != "false") { - if (is_null($readSqlCached[$crc]->lengths) && !$refreshCache && $readSqlCached[$crc]->num_rows == 0 && $readSqlCached[$crc]->field_count == 0) { - log_error("[sqlDAL::readSql] (mysqlnd) Something was going wrong, re-get the query. {$preparedStatement} {$readSqlCached[$crc]->num_rows}"); - return self::readSql($preparedStatement, $formats, $values, true); - } - } else { - $readSqlCached[$crc] = false; - } - // } - } else { - - // Mysqlnd-fallback - - if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { - log_error("[sqlDAL::readSql] (no mysqlnd) Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement})"); - return false; - } - - if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { - log_error("[sqlDAL::readSql] (no mysqlnd) eval_mysql_bind failed: values and params in stmt don't match {$preparedStatement} with formats {$formats}"); - return false; - } - - $stmt->execute(); - $result = self::iimysqli_stmt_get_result($stmt); - if ($stmt->errno != 0) { - log_error('Error in readSql (no mysqlnd): (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); - $stmt->close(); - $readSqlCached[$crc] = false; - } else { - $readSqlCached[$crc] = $result; - } - } - return $readSqlCached[$crc]; - } - - /* - * This closes the readSql - * @param Object $result A object from sqlDAL::readSql - */ - - static function close($result) { - global $disableMysqlNdMethods, $global; - if ((!function_exists('mysqli_fetch_all')) || ($disableMysqlNdMethods != false)) { - if(!empty($result->stmt)){ - $result->stmt->close(); - } - } - } - - /* - * Get the nr of rows - * @param Object $result A object from sqlDAL::readSql - * @return int The nr of rows - */ - - static function num_rows($res) { - global $global, $disableMysqlNdMethods, $crc, $num_row_cache; - if (!isset($num_row_cache)) { - $num_row_cache = array(); - } - // cache is working - but disable for proper test-results - if (!isset($num_row_cache[$crc])) { - if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { - // Mysqlnd - $num_row_cache[$crc] = 0; - if (!empty($res->num_rows)) { - $num_row_cache[$crc] = $res->num_rows; - } - return $num_row_cache[$crc]; - } else { - // Mysqlnd-fallback - use fetchAllAssoc because this can be cached. - $num_row_cache[$crc] = sizeof(self::fetchAllAssoc($res)); - } - } - return $num_row_cache[$crc]; - } - - // unused - static function cached_num_rows($data) { - return sizeof($data); - } - - /* - * Make a fetch assoc on every row avaible - * @param Object $result A object from sqlDAL::readSql - * @return array A array filled with all rows as a assoc array - */ - - static function fetchAllAssoc($result) { - global $crc, $fetchAllAssoc_cache; - if (!isset($fetchAllAssoc_cache)) { - $fetchAllAssoc_cache = array(); - } - if (!isset($fetchAllAssoc_cache[$crc])) { - $ret = array(); - while ($row = self::fetchAssoc($result)) { - $ret[] = $row; - } - $fetchAllAssoc_cache[$crc] = $ret; - } - return $fetchAllAssoc_cache[$crc]; - } - - /* - * Make a single assoc fetch - * @param Object $result A object from sqlDAL::readSql - * @return int A single row in a assoc array - */ - - static function fetchAssoc($result) { - global $global, $disableMysqlNdMethods; - ini_set('memory_limit', '-1'); - // here, a cache is more/too difficult, because fetch gives always a next. with this kind of cache, we would give always the same. - if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { - if ($result != false) { - return $result->fetch_assoc(); - } - } else { - return self::iimysqli_result_fetch_assoc($result); - } - return false; - } - - /* - * Make a fetchArray on every row avaible - * @param Object $result A object from sqlDAL::readSql - * @return array A array filled with all rows - */ - - static function fetchAllArray($result) { - global $crc, $fetchAllArray_cache; - if (!isset($fetchAllArray_cache)) { - $fetchAllArray_cache = array(); - } - // cache is working - but disable for proper test-results - if (!isset($fetchAllArray_cache[$crc])) { - $ret = array(); - while ($row = self::fetchArray($result)) { - $ret[] = $row; - } - $fetchAllArray_cache[$crc] = $ret; - } else { - log_error("array-cache"); - } - return $fetchAllArray_cache[$crc]; - } - - /* - * Make a single fetch - * @param Object $result A object from sqlDAL::readSql - * @return int A single row in a array - */ - - static function fetchArray($result) { - global $global, $disableMysqlNdMethods; - if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { - return $result->fetch_array(); - } else { - return self::iimysqli_result_fetch_array($result); - } - return false; - } - - private static function eval_mysql_bind($stmt, $formats, $values) { - if (($stmt->param_count != sizeof($values)) || ($stmt->param_count != strlen($formats))) { - return false; - } - if ((!empty($formats)) && (!empty($values))) { - $code = "return \$stmt->bind_param(\"" . $formats . "\""; - $i = 0; - foreach ($values as $val) { - $code .= ", \$values[" . $i . "]"; - $i++; - }; - $code .= ");"; - // echo $code. " : ".$preparedStatement; - eval($code); - } - return true; - } - - private static function iimysqli_stmt_get_result($stmt) { - global $global; - $metadata = mysqli_stmt_result_metadata($stmt); - $ret = new iimysqli_result; - $field_array = array(); - if (!$metadata) { - die("Execute query error, because: {$stmt->error}"); - } - $tmpFields = $metadata->fetch_fields(); - $i = 0; - foreach ($tmpFields as $f) { - $field_array[$i] = $f->name; - $i++; - } - $ret->fields = $field_array; - if (!$ret) - return NULL; - - $ret->nCols = mysqli_num_fields($metadata); - - $ret->stmt = $stmt; - - mysqli_free_result($metadata); - return $ret; - } - - private static function iimysqli_result_fetch_assoc(&$result) { - global $global; - $ret = array(); - $code = "return mysqli_stmt_bind_result(\$result->stmt "; - for ($i = 0; $i < $result->nCols; $i++) { - $ret[$result->fields[$i]] = NULL; - $code .= ", \$ret['" . $result->fields[$i] . "']"; - }; - - $code .= ");"; - if (!eval($code)) { - return false; - }; - if (!mysqli_stmt_fetch($result->stmt)) { - return false; - }; - return $ret; - } - - private static function iimysqli_result_fetch_array(&$result) { - $ret = array(); - $code = "return mysqli_stmt_bind_result(\$result->stmt "; - - for ($i = 0; $i < $result->nCols; $i++) { - $ret[$i] = NULL; - $code .= ", \$ret['" . $i . "']"; - }; - $code .= ");"; - if (!eval($code)) { - return false; - }; - if (!mysqli_stmt_fetch($result->stmt)) { - return false; - }; - return $ret; - } - -} - -function log_error($err) { - if (!empty($global['debug'])) { - echo $err; - } - _error_log("MySQL ERROR: ".json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)), AVideoLog::$ERROR); - _error_log($err, AVideoLog::$ERROR); -} - -?> +"; + } + + OR + + while($row = sqlDAL::fetchAssoc($result)){ + echo $row['user']."
"; + } + */ + +/* + * Internal used class + */ + +class iimysqli_result +{ + public $stmt; + public $nCols; + public $fields; +} + +global $disableMysqlNdMethods; +// this is only to test both methods more easy. +$disableMysqlNdMethods = false; + +/* + * This class exists for making servers avaible, which have no mysqlnd, withouth cause a performance-issue for those who have the driver. + * It wouldn't be possible without Daan on https://stackoverflow.com/questions/31562359/workaround-for-mysqlnd-missing-driver + */ + +class sqlDAL +{ + public static function executeFile($filename) + { + global $global; + $templine = ''; + // Read in entire file + $lines = file($filename); + // Loop through each line + 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 + if (!$global['mysqli']->query($templine)) { + _error_log('sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

', AVideoLog::$ERROR); + } + // Reset temp variable to empty + $templine = ''; + } + } + } + + /* + * For Sql like INSERT and UPDATE. The special point about this method: You do not need to close it (more direct). + * @param string $preparedStatement The Sql-command + * @param string $formats i=int,d=doube,s=string,b=blob (http://www.php.net/manual/en/mysqli-stmt.bind-param.php) + * @param array $values A array, containing the values for the prepared statement. + * @return boolean true on success, false on fail + */ + + public static function writeSql($preparedStatement, $formats = "", $values = []) + { + global $global, $disableMysqlNdMethods; + if (empty($preparedStatement)) { + return false; + } + // make sure it does not store autid transactions + $debug = debug_backtrace(); + if (empty($debug[2]['class']) || $debug[2]['class'] !== "AuditTable") { + $audit = AVideoPlugin::loadPluginIfEnabled('Audit'); + if (!empty($audit)) { + try { + $audit->exec(@$debug[1]['function'], @$debug[1]['class'], $preparedStatement, $formats, json_encode($values), User::getId()); + } catch (Exception $exc) { + echo log_error($exc->getTraceAsString()); + } + } + } + + if (!is_object($global['mysqli'])) { + _mysql_connect(); + } + + if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { + log_error("[sqlDAL::writeSql] Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement})"); + return false; + } + if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { + log_error("[sqlDAL::writeSql] eval_mysql_bind failed: values and params in stmt don't match ({$preparedStatement}) with formats ({$formats})"); + return false; + } + $stmt->execute(); + if ($stmt->errno != 0) { + log_error('Error in writeSql : (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); + $stmt->close(); + return false; + } + $iid = @$global['mysqli']->insert_id; + //$global['mysqli']->affected_rows = $stmt->affected_rows; + //$stmt->commit(); + $stmt->close(); + if (!empty($iid)) { + return $iid; + } else { + return true; + } + } + + /* + * For Sql like SELECT. This method needs to be closed anyway. If you start another readSql, while the old is open, it will fail. + * @param string $preparedStatement The Sql-command + * @param string $formats i=int,d=doube,s=string,b=blob (http://www.php.net/manual/en/mysqli-stmt.bind-param.php) + * @param array $values A array, containing the values for the prepared statement. + * @return Object Depend if mysqlnd is active or not, a object, but always false on fail + */ + + public static function readSql($preparedStatement, $formats = "", $values = [], $refreshCache = false) + { + // $refreshCache = true; + global $global, $disableMysqlNdMethods, $readSqlCached, $crc; + // need to add dechex because some times it return an negative value and make it fails on javascript playlists + $crc = (md5($preparedStatement . implode($values))); + + if (!isset($readSqlCached)) { + $readSqlCached = []; + } + if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { + + // Mysqlnd enabled + + if ((!isset($readSqlCached[$crc])) || ($refreshCache)) { + + // When not cached + + $readSqlCached[$crc] = "false"; + _mysql_connect(); + + if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { + log_error("[sqlDAL::readSql] (mysqlnd) Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement}) - format=({$formats}) values=" . json_encode($values)); + //log_error("[sqlDAL::readSql] trying close and reconnect"); + _mysql_close(); + _mysql_connect(); + if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { + log_error("[sqlDAL::readSql] (mysqlnd) Prepare failed again return false"); + return false; + } else { + log_error("[sqlDAL::readSql] SUCCESS close and reconnect works!"); + } + } + if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { + log_error("[sqlDAL::readSql] (mysqlnd) eval_mysql_bind failed: values and params in stmt don't match {$preparedStatement} with formats {$formats}"); + return false; + } + $TimeLog = "[$preparedStatement], $formats, " . json_encode($values) . ", $refreshCache"; + TimeLogStart($TimeLog); + $stmt->execute(); + $readSqlCached[$crc] = $stmt->get_result(); + if ($stmt->errno != 0) { + log_error('Error in readSql (mysqlnd): (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); + $stmt->close(); + $disableMysqlNdMethods = true; + // try again with noMysqlND + $read = self::readSql($preparedStatement, $formats, $values, $refreshCache); + TimeLogEnd($TimeLog, "mysql_dal", 0.5); + return $read; + } + TimeLogEnd($TimeLog, "mysql_dal", 0.5); + $stmt->close(); + } elseif (is_object($readSqlCached[$crc])) { + + // When cached + // reset the stmt for fetch. this solves objects/video.php line 550 + $readSqlCached[$crc]->data_seek(0); + //log_error("set dataseek to 0"); + // increase a counter for the saved queries. + if (isset($_SESSION['savedQuerys'])) { + $_SESSION['savedQuerys']++; + } + } else { + $readSqlCached[$crc] = "false"; + } + + // + // if ($readSqlCached[$crc] == "false") { + // add this in case the cache fail + // ->lenghts seems to be always NULL.. fix: $readSqlCached[$crc]->data_seek(0); above + //if("SELECT * FROM configurations WHERE id = 1 LIMIT 1"==$preparedStatement){ + // var_dump($readSqlCached[$crc]); + //} + if ($readSqlCached[$crc] != "false") { + if (is_null($readSqlCached[$crc]->lengths) && !$refreshCache && $readSqlCached[$crc]->num_rows == 0 && $readSqlCached[$crc]->field_count == 0) { + log_error("[sqlDAL::readSql] (mysqlnd) Something was going wrong, re-get the query. {$preparedStatement} {$readSqlCached[$crc]->num_rows}"); + return self::readSql($preparedStatement, $formats, $values, true); + } + } else { + $readSqlCached[$crc] = false; + } + // } + } else { + + // Mysqlnd-fallback + + if (!($stmt = $global['mysqli']->prepare($preparedStatement))) { + log_error("[sqlDAL::readSql] (no mysqlnd) Prepare failed: (" . $global['mysqli']->errno . ") " . $global['mysqli']->error . " ({$preparedStatement})"); + return false; + } + + if (!sqlDAL::eval_mysql_bind($stmt, $formats, $values)) { + log_error("[sqlDAL::readSql] (no mysqlnd) eval_mysql_bind failed: values and params in stmt don't match {$preparedStatement} with formats {$formats}"); + return false; + } + + $stmt->execute(); + $result = self::iimysqli_stmt_get_result($stmt); + if ($stmt->errno != 0) { + log_error('Error in readSql (no mysqlnd): (' . $stmt->errno . ') ' . $stmt->error . ", SQL-CMD:" . $preparedStatement); + $stmt->close(); + $readSqlCached[$crc] = false; + } else { + $readSqlCached[$crc] = $result; + } + } + return $readSqlCached[$crc]; + } + + /* + * This closes the readSql + * @param Object $result A object from sqlDAL::readSql + */ + + public static function close($result) + { + global $disableMysqlNdMethods, $global; + if ((!function_exists('mysqli_fetch_all')) || ($disableMysqlNdMethods != false)) { + if (!empty($result->stmt)) { + $result->stmt->close(); + } + } + } + + /* + * Get the nr of rows + * @param Object $result A object from sqlDAL::readSql + * @return int The nr of rows + */ + + public static function num_rows($res) + { + global $global, $disableMysqlNdMethods, $crc, $num_row_cache; + if (!isset($num_row_cache)) { + $num_row_cache = []; + } + // cache is working - but disable for proper test-results + if (!isset($num_row_cache[$crc])) { + if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { + // Mysqlnd + $num_row_cache[$crc] = 0; + if (!empty($res->num_rows)) { + $num_row_cache[$crc] = $res->num_rows; + } + return $num_row_cache[$crc]; + } else { + // Mysqlnd-fallback - use fetchAllAssoc because this can be cached. + $num_row_cache[$crc] = sizeof(self::fetchAllAssoc($res)); + } + } + return $num_row_cache[$crc]; + } + + // unused + public static function cached_num_rows($data) + { + return sizeof($data); + } + + /* + * Make a fetch assoc on every row avaible + * @param Object $result A object from sqlDAL::readSql + * @return array A array filled with all rows as a assoc array + */ + + public static function fetchAllAssoc($result) + { + global $crc, $fetchAllAssoc_cache; + if (!isset($fetchAllAssoc_cache)) { + $fetchAllAssoc_cache = []; + } + if (!isset($fetchAllAssoc_cache[$crc])) { + $ret = []; + while ($row = self::fetchAssoc($result)) { + $ret[] = $row; + } + $fetchAllAssoc_cache[$crc] = $ret; + } + return $fetchAllAssoc_cache[$crc]; + } + + /* + * Make a single assoc fetch + * @param Object $result A object from sqlDAL::readSql + * @return int A single row in a assoc array + */ + + public static function fetchAssoc($result) + { + global $global, $disableMysqlNdMethods; + ini_set('memory_limit', '-1'); + // here, a cache is more/too difficult, because fetch gives always a next. with this kind of cache, we would give always the same. + if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { + if ($result != false) { + return $result->fetch_assoc(); + } + } else { + return self::iimysqli_result_fetch_assoc($result); + } + return false; + } + + /* + * Make a fetchArray on every row avaible + * @param Object $result A object from sqlDAL::readSql + * @return array A array filled with all rows + */ + + public static function fetchAllArray($result) + { + global $crc, $fetchAllArray_cache; + if (!isset($fetchAllArray_cache)) { + $fetchAllArray_cache = []; + } + // cache is working - but disable for proper test-results + if (!isset($fetchAllArray_cache[$crc])) { + $ret = []; + while ($row = self::fetchArray($result)) { + $ret[] = $row; + } + $fetchAllArray_cache[$crc] = $ret; + } else { + log_error("array-cache"); + } + return $fetchAllArray_cache[$crc]; + } + + /* + * Make a single fetch + * @param Object $result A object from sqlDAL::readSql + * @return int A single row in a array + */ + + public static function fetchArray($result) + { + global $global, $disableMysqlNdMethods; + if ((function_exists('mysqli_fetch_all')) && ($disableMysqlNdMethods == false)) { + return $result->fetch_array(); + } else { + return self::iimysqli_result_fetch_array($result); + } + return false; + } + + private static function eval_mysql_bind($stmt, $formats, $values) + { + if (($stmt->param_count != sizeof($values)) || ($stmt->param_count != strlen($formats))) { + return false; + } + if ((!empty($formats)) && (!empty($values))) { + $code = "return \$stmt->bind_param(\"" . $formats . "\""; + $i = 0; + foreach ($values as $val) { + $code .= ", \$values[" . $i . "]"; + $i++; + }; + $code .= ");"; + // echo $code. " : ".$preparedStatement; + eval($code); + } + return true; + } + + private static function iimysqli_stmt_get_result($stmt) + { + global $global; + $metadata = mysqli_stmt_result_metadata($stmt); + $ret = new iimysqli_result(); + $field_array = []; + if (!$metadata) { + die("Execute query error, because: {$stmt->error}"); + } + $tmpFields = $metadata->fetch_fields(); + $i = 0; + foreach ($tmpFields as $f) { + $field_array[$i] = $f->name; + $i++; + } + $ret->fields = $field_array; + if (!$ret) { + return null; + } + + $ret->nCols = mysqli_num_fields($metadata); + + $ret->stmt = $stmt; + + mysqli_free_result($metadata); + return $ret; + } + + private static function iimysqli_result_fetch_assoc(&$result) + { + global $global; + $ret = []; + $code = "return mysqli_stmt_bind_result(\$result->stmt "; + for ($i = 0; $i < $result->nCols; $i++) { + $ret[$result->fields[$i]] = null; + $code .= ", \$ret['" . $result->fields[$i] . "']"; + }; + + $code .= ");"; + if (!eval($code)) { + return false; + }; + if (!mysqli_stmt_fetch($result->stmt)) { + return false; + }; + return $ret; + } + + private static function iimysqli_result_fetch_array(&$result) + { + $ret = []; + $code = "return mysqli_stmt_bind_result(\$result->stmt "; + + for ($i = 0; $i < $result->nCols; $i++) { + $ret[$i] = null; + $code .= ", \$ret['" . $i . "']"; + }; + $code .= ");"; + if (!eval($code)) { + return false; + }; + if (!mysqli_stmt_fetch($result->stmt)) { + return false; + }; + return $ret; + } +} + +function log_error($err) +{ + if (!empty($global['debug'])) { + echo $err; + } + _error_log("MySQL ERROR: ".json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)), AVideoLog::$ERROR); + _error_log($err, AVideoLog::$ERROR); +} diff --git a/objects/notifications.json.php b/objects/notifications.json.php index 24b9acd5e7..ed6829c942 100644 --- a/objects/notifications.json.php +++ b/objects/notifications.json.php @@ -1,32 +1,32 @@ - $value) { - $_POST[$key]=$value; - } -} -if (!empty($_POST['user']) && !empty($_POST['pass'])) { - $user = new User(0, $_POST['user'], $_POST['pass']); - $user->login(false, true); -} - -$obj = new stdClass(); -if (AVideoPlugin::loadPluginIfEnabled("Live")) { - //$liveStats = url_get_contents("{$global['webSiteRootURL']}plugin/Live/stats.json.php"); - $obj->live = getStatsNotifications(); -} - -echo json_encode($obj); + $value) { + $_POST[$key]=$value; + } +} +if (!empty($_POST['user']) && !empty($_POST['pass'])) { + $user = new User(0, $_POST['user'], $_POST['pass']); + $user->login(false, true); +} + +$obj = new stdClass(); +if (AVideoPlugin::loadPluginIfEnabled("Live")) { + //$liveStats = url_get_contents("{$global['webSiteRootURL']}plugin/Live/stats.json.php"); + $obj->live = getStatsNotifications(); +} + +echo json_encode($obj); diff --git a/objects/notifySubscribers.json.php b/objects/notifySubscribers.json.php index 0fe7f17286..c1d23c8b32 100644 --- a/objects/notifySubscribers.json.php +++ b/objects/notifySubscribers.json.php @@ -1,47 +1,47 @@ -setFrom($config->getContactEmail()); -//Set who the message is to be sent to -//$mail->addAddress($config->getContactEmail()); -foreach ($Subscribes as $value) { - $mail->addBCC($value["email"]); -} -$obj->total = count($Subscribes); -//Set the subject line -$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle(); -$mail->msgHTML($_POST['message']); - -//send the message, check for errors -if (!$mail->send()) { - $obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo; -} else { - $obj->success = __("Message sent"); -} - -echo json_encode($obj); +setFrom($config->getContactEmail()); +//Set who the message is to be sent to +//$mail->addAddress($config->getContactEmail()); +foreach ($Subscribes as $value) { + $mail->addBCC($value["email"]); +} +$obj->total = count($Subscribes); +//Set the subject line +$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle(); +$mail->msgHTML($_POST['message']); + +//send the message, check for errors +if (!$mail->send()) { + $obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo; +} else { + $obj->success = __("Message sent"); +} + +echo json_encode($obj); diff --git a/objects/playListAddVideo.json.php b/objects/playListAddVideo.json.php index 05464dde02..ed45f03bf3 100644 --- a/objects/playListAddVideo.json.php +++ b/objects/playListAddVideo.json.php @@ -1,40 +1,40 @@ -error = true; -$obj->status = 0; - -if (!User::isLogged()) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -$plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists"); -if (empty($plugin)) { - $obj->msg = "Plugin not enabled"; - die(json_encode($obj)); -} - -if (!PlayLists::canAddVideoOnPlaylist($_POST['videos_id'])) { - $obj->msg = "You can not add this video on playlist"; - die(json_encode($obj)); -} - -$playList = new PlayList($_POST['playlists_id']); -if (empty($playList || User::getId()!=$playList->getUsers_id()) || empty($_POST['videos_id'])) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -$obj->error = false; -$obj->status = $playList->addVideo($_POST['videos_id'], $_POST['add']); - -//log_error("videos id: ".$_POST['videos_id']." playlist_id: ".$_POST['playlists_id']); -die(json_encode($obj)); +error = true; +$obj->status = 0; + +if (!User::isLogged()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +$plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists"); +if (empty($plugin)) { + $obj->msg = "Plugin not enabled"; + die(json_encode($obj)); +} + +if (!PlayLists::canAddVideoOnPlaylist($_POST['videos_id'])) { + $obj->msg = "You can not add this video on playlist"; + die(json_encode($obj)); +} + +$playList = new PlayList($_POST['playlists_id']); +if (empty($playList || User::getId()!=$playList->getUsers_id()) || empty($_POST['videos_id'])) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +$obj->error = false; +$obj->status = $playList->addVideo($_POST['videos_id'], $_POST['add']); + +//log_error("videos id: ".$_POST['videos_id']." playlist_id: ".$_POST['playlists_id']); +die(json_encode($obj)); diff --git a/objects/playlist.php b/objects/playlist.php index 651c05a464..b38385f4ab 100644 --- a/objects/playlist.php +++ b/objects/playlist.php @@ -1,795 +1,836 @@ -setName($name); - $row = self::getFromDbFromName($this->getName()); - if (empty($row)) { - return false; - } - foreach ($row as $key => $value) { - $this->$key = $value; - } - return true; - } - - public static function getAllFromPlaylistsID($playlists_id) { - if (empty($playlists_id)) { - return false; - } - $videosArrayId = PlayList::getVideosIdFromPlaylist($playlists_id); - $videosP = Video::getAllVideos("viewable", false, true, $videosArrayId, false, true); - $videosP = PlayList::sortVideos($videosP, $videosArrayId); - foreach ($videosP as $key => $value2) { - if (!empty($value2['serie_playlists_id'])) { - $videosP[$key]['icon'] = ''; - } else { - $videosP[$key]['icon'] = ''; - } - } - - return $videosP; - } - - /** - * - * @global type $global - * @param type $publicOnly - * @param type $userId if not present check session - * @param type $isVideoIdPresent pass the ID of the video checking - * @return boolean - */ - public static function getAllFromUser($userId, $publicOnly = true, $status = false, $playlists_id = 0, $try = 0) { - global $global, $config, $refreshCacheFromPlaylist; - $playlists_id = intval($playlists_id); - $formats = ""; - $values = array(); - $sql = "SELECT u.*, pl.* FROM " . static::getTableName() . " pl " - . " LEFT JOIN users u ON u.id = users_id WHERE 1=1 "; - if (!empty($playlists_id)) { - $sql .= " AND pl.id = '{$playlists_id}' "; - } - if (!empty($status)) { - $status = str_replace("'", "", $status); - $sql .= " AND pl.status = '{$status}' "; - } elseif ($publicOnly) { - $sql .= " AND pl.status = 'public' "; - } - if (!empty($userId)) { - $sql .= " AND users_id = ? "; - $formats .= "i"; - $values[] = $userId; - } - $sql .= self::getSqlFromPost("pl."); - //echo $sql, $userId;exit; - $res = sqlDAL::readSql($sql, $formats, $values, $refreshCacheFromPlaylist); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - $favorite = array(); - $watch_later = array(); - $favoriteCount = 0; - $watch_laterCount = 0; - if ($res != false) { - foreach ($fullData as $row) { - $row = cleanUpRowFromDatabase($row); - $row['name_translated'] = __($row['name']); - $row['videos'] = static::getVideosFromPlaylist($row['id']); - $row['isFavorite'] = false; - $row['isWatchLater'] = false; - if ($row['status'] === "favorite") { - $row['isFavorite'] = true; - $favoriteCount++; - $favorite = $row; - } elseif ($row['status'] === "watch_later") { - $watch_laterCount++; - $row['isWatchLater'] = true; - $watch_later = $row; - } else { - $rows[] = $row; - } - } - if (!empty($userId)) { - if ($try == 0 && ($favoriteCount > 1 || $watch_laterCount > 1)) { - self::fixDuplicatePlayList($userId); - $refreshCacheFromPlaylist = true; - return self::getAllFromUser($userId, $publicOnly, $status, $playlists_id, $try + 1); - } - if (empty($_POST['current']) && empty($status) && $config->currentVersionGreaterThen("6.4")) { - if (empty($favorite)) { - $pl = new PlayList(0); - $pl->setName("Favorite"); - $pl->setStatus("favorite"); - $pl->setUsers_id($userId); - $id = $pl->save(); - $refreshCacheFromPlaylist = true; - $row['id'] = $id; - $row['name'] = $pl->getName(); - $row['status'] = $pl->getStatus(); - $row['users_id'] = $pl->getUsers_id(); - $favorite = $row; - } - if (empty($watch_later)) { - $pl = new PlayList(0); - $pl->setName("Watch Later"); - $pl->setStatus("watch_later"); - $pl->setUsers_id($userId); - $id = $pl->save(); - $refreshCacheFromPlaylist = true; - $row['id'] = $id; - $row['name'] = $pl->getName(); - $row['status'] = $pl->getStatus(); - $row['users_id'] = $pl->getUsers_id(); - $watch_later = $row; - } - } - } - if (!empty($favorite)) { - array_unshift($rows, $favorite); - } - if (!empty($watch_later)) { - array_unshift($rows, $watch_later); - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $rows; - } - - /** - * - * @global type $global - * @param type $publicOnly - * @param type $userId if not present check session - * @param type $isVideoIdPresent pass the ID of the video checking - * @return boolean - */ - public static function getAllFromUserLight($userId, $publicOnly = true, $status = false, $playlists_id = 0, $onlyWithVideos = false) { - global $global, $config, $refreshCacheFromPlaylist; - $playlists_id = intval($playlists_id); - $formats = ""; - $values = array(); - $sql = "SELECT u.*, pl.* FROM " . static::getTableName() . " pl " - . " LEFT JOIN users u ON u.id = users_id WHERE 1=1 "; - if (!empty($playlists_id)) { - $sql .= " AND pl.id = '{$playlists_id}' "; - } - if (!empty($status)) { - $status = str_replace("'", "", $status); - $sql .= " AND pl.status = '{$status}' "; - } elseif ($publicOnly) { - if (User::getId() != $userId) { - $sql .= " AND pl.status = 'public' "; - } - } - if (!empty($userId)) { - $sql .= " AND users_id = ? "; - $formats .= "i"; - $values[] = $userId; - } - $sql .= self::getSqlFromPost("pl."); - //echo $sql, $userId;exit; - $res = sqlDAL::readSql($sql, $formats, $values, $refreshCacheFromPlaylist); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $row = cleanUpRowFromDatabase($row); - if ($onlyWithVideos) { - $videos = self::getVideosIDFromPlaylistLight($row['id']); - if (empty($videos)) { - continue; - } - } - $rows[] = $row; - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $rows; - } - - public static function fixDuplicatePlayList($user_id) { - if (empty($user_id)) { - return false; - } - _error_log("PlayList::fixDuplicatePlayList Process user_id = {$user_id} favorite"); - $sql = "SELECT * FROM playlists WHERE users_id = ? AND status = 'favorite' ORDER BY created "; - $res = sqlDAL::readSql($sql, "i", array($user_id), true); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $key => $row) { - if ($key === 0) { - continue; - } - - if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { - _error_log("PlayList::fixDuplicatePlayList favorite PlayList NOT empty {$row['id']}"); - continue; - } - - $sql = "DELETE FROM playlists "; - $sql .= " WHERE id = ?"; - - _error_log("PlayList::fixDuplicatePlayList favorite {$row['id']}"); - sqlDAL::writeSql($sql, "i", array($row['id'])); - } - } - - _error_log("PlayList::fixDuplicatePlayList Process user_id = {$user_id} watch_later"); - $sql = "SELECT * FROM playlists WHERE users_id = ? AND status = 'watch_later' ORDER BY created "; - $res = sqlDAL::readSql($sql, "i", array($user_id), true); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $key => $row) { - if ($key === 0) { - continue; - } - if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { - _error_log("PlayList::fixDuplicatePlayList watch_later PlayList NOT empty {$row['id']}"); - continue; - } - $sql = "DELETE FROM playlists "; - $sql .= " WHERE id = ?"; - _error_log("PlayList::fixDuplicatePlayList watch_later {$row['id']}"); - ob_flush(); - sqlDAL::writeSql($sql, "i", array($row['id'])); - } - } - } - - public static function getAllFromUserVideo($userId, $videos_id, $publicOnly = true, $status = false) { - if (empty($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)])) { - $rows = self::getAllFromUser($userId, $publicOnly, $status); - foreach ($rows as $key => $value) { - $rows[$key]['name_translated'] = __($rows[$key]['name']); - $videos = self::getVideosIdFromPlaylist($value['id']); - $rows[$key]['isOnPlaylist'] = in_array($videos_id, $videos); - } - _session_start(); - $_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)] = $rows; - } else { - $rows = $_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)]; - } - - return $rows; - } - - private static function removeCache($videos_id) { - $close = false; - _session_start(); - unset($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id]); - } - - public static function getVideosIDFromPlaylistLight($playlists_id) { - global $global, $getVideosIDFromPlaylistLight; - - if (!isset($getVideosIDFromPlaylistLight)) { - $getVideosIDFromPlaylistLight = array(); - } - - if (isset($getVideosIDFromPlaylistLight[$playlists_id])) { - return $getVideosIDFromPlaylistLight[$playlists_id]; - } - - $sql = "SELECT * FROM playlists_has_videos p WHERE playlists_id = ? ORDER BY `order` "; - /* - cleanSearchVar(); - $sort = @$_POST['sort']; - $_POST['sort'] = array(); - $sql .= self::getSqlFromPost(); - $_POST['sort'] = $sort; - reloadSearchVar(); - * - */ - $res = sqlDAL::readSql($sql, "i", array($playlists_id)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $rows[] = $row; - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - $getVideosIDFromPlaylistLight[$playlists_id] = $rows; - return $rows; - } - - public static function getVideosFromPlaylist($playlists_id) { - $sql = "SELECT *,v.created as cre, p.`order` as video_order, v.externalOptions as externalOptions " - //. ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes " - . " FROM playlists_has_videos p " - . " LEFT JOIN videos as v ON videos_id = v.id " - . " LEFT JOIN users u ON u.id = v.users_id " - . " WHERE playlists_id = ? AND v.status != 'i' "; - cleanSearchVar(); - $sort = @$_POST['sort']; - $_POST['sort'] = array(); - $_POST['sort']['p.`order`'] = 'ASC'; - $sql .= self::getSqlFromPost(); - reloadSearchVar(); - $_POST['sort'] = $sort; - $cacheName = "getVideosFromPlaylist{$playlists_id}" . DIRECTORY_SEPARATOR . md5($sql); - $rows = self::getCache($cacheName, 0, true); - if (empty($rows)) { - global $global; - - $res = sqlDAL::readSql($sql, "i", array($playlists_id)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - $SubtitleSwitcher = AVideoPlugin::loadPluginIfEnabled("SubtitleSwitcher"); - if ($res != false) { - foreach ($fullData as $row) { - $row = cleanUpRowFromDatabase($row); - if (!empty($_GET['isChannel'])) { - $row['tags'] = Video::getTags($row['id']); - $row['pluginBtns'] = AVideoPlugin::getPlayListButtons($playlists_id); - $row['humancreate'] = humanTiming(strtotime($row['cre'])); - } - $images = Video::getImageFromFilename($row['filename'], $row['type']); - if (!file_exists($images->posterLandscapePath) && !empty($row['serie_playlists_id'])) { - $images = self::getRandomImageFromPlayList($row['serie_playlists_id']); - } - $row['images'] = $images; - $row['videos'] = Video::getVideosPaths($row['filename'], true); - $row['progress'] = Video::getVideoPogressPercent($row['videos_id']); - $row['title'] = UTF8encode($row['title']); - $row['description'] = UTF8encode($row['description']); - $row['tags'] = Video::getTags($row['videos_id']); - if (AVideoPlugin::isEnabledByName("VideoTags")) { - $row['videoTags'] = Tags::getAllFromVideosId($row['videos_id']); - $row['videoTagsObject'] = Tags::getObjectFromVideosId($row['videos_id']); - } - if ($SubtitleSwitcher) { - $row['subtitles'] = getVTTTracks($row['filename'], true); - foreach ($row['subtitles'] as $value) { - $row['subtitlesSRT'][] = convertSRTTrack($value); - } - } - if(empty($row['externalOptions'])){ - $row['externalOptions'] = json_encode(array('videoStartSeconds'=>'00:00:00')); - } - $rows[] = $row; - } - - $cache = self::setCache($cacheName, $rows); - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - } else { - $rows = object_to_array($rows); - } - return $rows; - } - - public static function getRandomImageFromPlayList($playlists_id) { - global $global; - $sql = "SELECT v.* " - . " FROM playlists_has_videos p " - . " LEFT JOIN videos as v ON videos_id = v.id " - . " WHERE playlists_id = ? AND v.status != 'i' ORDER BY RAND() - LIMIT 1"; - $res = sqlDAL::readSql($sql, "i", array($playlists_id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - $row = $data; - $images = Video::getImageFromFilename($row['filename'], $row['type']); - - if (!file_exists($images->posterLandscapePath) && !empty($row['serie_playlists_id'])) { - return self::getRandomImageFromPlayList($row['serie_playlists_id']); - } - return $images; - } - return false; - } - - public static function isAGroupOfPlayLists($playlists_id) { - - $rows = self::getAllSubPlayLists($playlists_id); - - return count($rows); - } - - public static function getAllSubPlayLists($playlists_id, $NOTSubPlaylists = 0) { - global $getAllSubPlayLists; - if (empty($playlists_id)) { - return false; - } - if (!isset($getAllSubPlayLists)) { - $getAllSubPlayLists = array(); - } - if (!isset($getAllSubPlayLists[$playlists_id])) { - $getAllSubPlayLists[$playlists_id] = array(); - } - if (isset($getAllSubPlayLists[$playlists_id][$NOTSubPlaylists])) { - return $getAllSubPlayLists[$playlists_id][$NOTSubPlaylists]; - } - $sql = "SELECT v.* " - . " FROM playlists_has_videos p " - . " LEFT JOIN videos as v ON videos_id = v.id " - . " WHERE playlists_id = ? AND v.status != 'i' "; - - if ($NOTSubPlaylists) { - $sql .= ' AND serie_playlists_id IS NULL '; - } else { - $sql .= ' AND serie_playlists_id IS NOT NULL '; - } - - $res = sqlDAL::readSql($sql, "i", array($playlists_id)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $rows[] = $row; - } - } - $getAllSubPlayLists[$playlists_id][$NOTSubPlaylists] = $rows; - return $rows; - } - - public static function getAllNOTSubPlayLists($playlists_id) { - return self::getAllSubPlayLists($playlists_id, 1); - } - - public static function isVideoOnFavorite($videos_id, $users_id) { - return self::isVideoOn($videos_id, $users_id, 'favorite'); - } - - public static function isVideoOnWatchLater($videos_id, $users_id) { - return self::isVideoOn($videos_id, $users_id, 'watch_later'); - } - - private static function isVideoOn($videos_id, $users_id, $status) { - global $global; - $status = str_replace("'", "", $status); - - $sql = "SELECT pl.id FROM " . static::getTableName() . " pl " - . " LEFT JOIN users u ON u.id = users_id " - . " LEFT JOIN playlists_has_videos p ON pl.id = playlists_id" - . " LEFT JOIN videos as v ON videos_id = v.id " - . " WHERE videos_id = ? AND pl.users_id = ? AND pl.status = '{$status}' LIMIT 1 "; - //echo $videos_id," - " ,$users_id, $sql; - $res = sqlDAL::readSql($sql, "ii", array($videos_id, $users_id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res) { - $row = $data; - $row = cleanUpRowFromDatabase($row); - } else { - $row = false; - } - return $row; - } - - public static function getFavoriteIdFromUser($users_id) { - global $refreshCacheFromPlaylist; - $favorite = self::getIdFromUser($users_id, "favorite"); - if (empty($favorite)) { - $pl = new PlayList(0); - $pl->setName("Favorite"); - $pl->setUsers_id($users_id); - $pl->setStatus("favorite"); - $pl->save(); - $refreshCacheFromPlaylist = true; - $favorite = self::getIdFromUser($users_id, "favorite"); - } - return $favorite; - } - - public static function getWatchLaterIdFromUser($users_id) { - global $refreshCacheFromPlaylist; - $watch_later = self::getIdFromUser($users_id, "watch_later"); - - if (empty($watch_later)) { - $pl = new PlayList(0); - $pl->setName("Watch Later"); - $pl->setUsers_id($users_id); - $pl->setStatus("watch_later"); - $pl->save(); - $refreshCacheFromPlaylist = true; - $watch_later = self::getIdFromUser($users_id, "watch_later"); - } - return $watch_later; - } - - private static function getIdFromUser($users_id, $status) { - global $global; - - $status = str_replace("'", "", $status); - $sql = "SELECT * FROM " . static::getTableName() . " pl WHERE" - . " users_id = ? AND pl.status = '{$status}' LIMIT 1 "; - $res = sqlDAL::readSql($sql, "i", array($users_id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res && !empty($data)) { - $row = $data['id']; - } else { - $row = false; - } - return $row; - } - - public static function getVideosIdFromPlaylist($playlists_id) { - global $getVideosIdFromPlaylist; - if (empty($getVideosIdFromPlaylist)) { - $getVideosIdFromPlaylist = array(); - } - if (isset($getVideosIdFromPlaylist[$playlists_id])) { - return $getVideosIdFromPlaylist[$playlists_id]; - } - $videosId = array(); - $rows = static::getVideosIDFromPlaylistLight($playlists_id); - foreach ($rows as $value) { - $videosId[] = $value['videos_id']; - } - - $getVideosIdFromPlaylist[$playlists_id] = $videosId; - return $videosId; - } - - public static function sortVideos($videosList, $listIdOrder) { - $list = array(); - foreach ($listIdOrder as $value) { - $found = false; - foreach ($videosList as $key => $value2) { - if ($value2['id'] == $value) { - $list[] = $value2; - unset($videosList[$key]); - $found = true; - } - } - if (!$found) { - $v = new Video("", "", $value); - if (empty($v->getFilename())) { - continue; - } - $list[] = array('id' => $value); - } - } - return $list; - } - - public function save() { - if (!User::isLogged()) { - return false; - } - $this->clearEmptyLists(); - $users_id = User::getId(); - $this->setUsers_id($users_id); - $this->showOnTV = intval($this->showOnTV); - $playlists_id = parent::save(); - if (!empty($playlists_id)) { - self::deleteCacheDir($playlists_id); - } - return $playlists_id; - } - - /** - * This is just to fix errors from the update 6.4 to 6.5, where empty playlists were created before the update - * @return type - */ - private function clearEmptyLists() { - $sql = "DELETE FROM " . static::getTableName() . " WHERE status = ''"; - - return sqlDAL::writeSql($sql); - } - - public function addVideo($videos_id, $add, $order = 0) { - global $global; - $formats = ""; - $values = array(); - if (empty($add) || $add === "false") { - $sql = "DELETE FROM playlists_has_videos WHERE playlists_id = ? AND videos_id = ? "; - $formats = "ii"; - $values[] = $this->id; - $values[] = $videos_id; - } else { - $this->addVideo($videos_id, false); - $sql = "INSERT INTO playlists_has_videos ( playlists_id, videos_id , `order`) VALUES (?, ?, ?) "; - $formats = "iii"; - $values[] = $this->id; - $values[] = $videos_id; - $values[] = $order; - } - $result = sqlDAL::writeSql($sql, $formats, $values); - self::deleteCacheDir($this->id); - self::removeCache($videos_id); - return $result; - } - - private static function deleteCacheDir($playlists_id){ - $tmpDir = ObjectYPT::getCacheDir(); - $name = "getvideosfromplaylist{$playlists_id}"; - $cacheDir = $tmpDir . $name . DIRECTORY_SEPARATOR; - rrmdir($cacheDir); - if(class_exists('CachesInDB')){ - CachesInDB::_deleteCacheStartingWith($name); - } - } - - public function delete() { - if (empty($this->id)) { - return false; - } - global $global; - $sql = "DELETE FROM playlists WHERE id = ? "; - //echo $sql; - $result = sqlDAL::writeSql($sql, "i", array($this->id)); - - self::deleteCacheDir($this->id); - return $result; - } - - public function getId() { - return $this->id; - } - - public function getName() { - return $this->name; - } - - public function getModified() { - return $this->modified; - } - - public function getUsers_id() { - return $this->users_id; - } - - public function getStatus() { - return $this->status; - } - - public function setId($id) { - $this->id = $id; - } - - public function setName($name) { - if (strlen($name) > 45) { - $name = substr($name, 0, 42) . '...'; - } - $this->name = xss_esc($name); - //var_dump($name,$this->name);exit; - } - - public function setUsers_id($users_id) { - $this->users_id = $users_id; - } - - public function setStatus($status) { - if (!in_array($status, self::$validStatus)) { - $status = 'public'; - } - $this->status = $status; - } - - public static function canSee($playlist_id, $users_id) { - $obj = new PlayList($playlist_id); - $status = $obj->getStatus(); - if ($status !== 'public' && $status !== 'unlisted' && $users_id != $obj->getUsers_id()) { - return false; - } - return true; - } - - public static function getEPG() { - global $config, $global; - $encoder = $config->_getEncoderURL(); - $url = "{$encoder}view/videosListEPG.php?date_default_timezone=" . urlencode(date_default_timezone_get()); - - $content = url_get_contents($url); - return _json_decode($content); - } - - public function getShowOnTV() { - return intval($this->showOnTV); - } - - public function setShowOnTV($showOnTV) { - if (strtolower($showOnTV) === "false") { - $showOnTV = 0; - } elseif (strtolower($showOnTV) === "true") { - $showOnTV = 1; - } - $this->showOnTV = intval($showOnTV); - } - - public static function getAllToShowOnTV() { - global $global; - if (!static::isTableInstalled()) { - return false; - } - $sql = "SELECT u.*, pl.* FROM playlists pl " - . " LEFT JOIN users u ON users_id = u.id " - . " WHERE showOnTV=1 "; - - $sql .= self::getSqlFromPost(); - //echo $sql;exit; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $row = cleanUpRowFromDatabase($row); - $rows[] = $row; - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $rows; - } - - public static function showPlayListSelector($playListArray) { - $collections = array(); - $videos = array(); - foreach ($playListArray as $value) { - if ($value['type'] === 'serie' && !empty($value['serie_playlists_id'])) { - $collections[] = $value; - } else { - $videos[] = $value; - } - } - $countCollections = count($collections); - $countVideos = count($videos); - if (!empty($countCollections)) { - if ($countCollections === 1 && empty($countVideos)) { - return false; - } - return $collections; - } - return false; - } - -} +setName($name); + $row = self::getFromDbFromName($this->getName()); + if (empty($row)) { + return false; + } + foreach ($row as $key => $value) { + $this->$key = $value; + } + return true; + } + + public static function getAllFromPlaylistsID($playlists_id) + { + if (empty($playlists_id)) { + return false; + } + $videosArrayId = PlayList::getVideosIdFromPlaylist($playlists_id); + $videosP = Video::getAllVideos("viewable", false, true, $videosArrayId, false, true); + $videosP = PlayList::sortVideos($videosP, $videosArrayId); + foreach ($videosP as $key => $value2) { + if (!empty($value2['serie_playlists_id'])) { + $videosP[$key]['icon'] = ''; + } else { + $videosP[$key]['icon'] = ''; + } + } + + return $videosP; + } + + /** + * + * @global type $global + * @param type $publicOnly + * @param type $userId if not present check session + * @param type $isVideoIdPresent pass the ID of the video checking + * @return boolean + */ + public static function getAllFromUser($userId, $publicOnly = true, $status = false, $playlists_id = 0, $try = 0) + { + global $global, $config, $refreshCacheFromPlaylist; + $playlists_id = intval($playlists_id); + $formats = ''; + $values = []; + $sql = "SELECT u.*, pl.* FROM " . static::getTableName() . " pl " + . " LEFT JOIN users u ON u.id = users_id WHERE 1=1 "; + if (!empty($playlists_id)) { + $sql .= " AND pl.id = '{$playlists_id}' "; + } + if (!empty($status)) { + $status = str_replace("'", "", $status); + $sql .= " AND pl.status = '{$status}' "; + } elseif ($publicOnly) { + $sql .= " AND pl.status = 'public' "; + } + if (!empty($userId)) { + $sql .= " AND users_id = ? "; + $formats .= "i"; + $values[] = $userId; + } + $sql .= self::getSqlFromPost("pl."); + //echo $sql, $userId;exit; + $res = sqlDAL::readSql($sql, $formats, $values, $refreshCacheFromPlaylist); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + $favorite = []; + $watch_later = []; + $favoriteCount = 0; + $watch_laterCount = 0; + if ($res != false) { + foreach ($fullData as $row) { + $row = cleanUpRowFromDatabase($row); + $row['name_translated'] = __($row['name']); + $row['videos'] = static::getVideosFromPlaylist($row['id']); + $row['isFavorite'] = false; + $row['isWatchLater'] = false; + if ($row['status'] === "favorite") { + $row['isFavorite'] = true; + $favoriteCount++; + $favorite = $row; + } elseif ($row['status'] === "watch_later") { + $watch_laterCount++; + $row['isWatchLater'] = true; + $watch_later = $row; + } else { + $rows[] = $row; + } + } + if (!empty($userId)) { + if ($try == 0 && ($favoriteCount > 1 || $watch_laterCount > 1)) { + self::fixDuplicatePlayList($userId); + $refreshCacheFromPlaylist = true; + return self::getAllFromUser($userId, $publicOnly, $status, $playlists_id, $try + 1); + } + if (empty($_POST['current']) && empty($status) && $config->currentVersionGreaterThen("6.4")) { + if (empty($favorite)) { + $pl = new PlayList(0); + $pl->setName("Favorite"); + $pl->setStatus("favorite"); + $pl->setUsers_id($userId); + $id = $pl->save(); + $refreshCacheFromPlaylist = true; + $row['id'] = $id; + $row['name'] = $pl->getName(); + $row['status'] = $pl->getStatus(); + $row['users_id'] = $pl->getUsers_id(); + $favorite = $row; + } + if (empty($watch_later)) { + $pl = new PlayList(0); + $pl->setName("Watch Later"); + $pl->setStatus("watch_later"); + $pl->setUsers_id($userId); + $id = $pl->save(); + $refreshCacheFromPlaylist = true; + $row['id'] = $id; + $row['name'] = $pl->getName(); + $row['status'] = $pl->getStatus(); + $row['users_id'] = $pl->getUsers_id(); + $watch_later = $row; + } + } + } + if (!empty($favorite)) { + array_unshift($rows, $favorite); + } + if (!empty($watch_later)) { + array_unshift($rows, $watch_later); + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + /** + * + * @global type $global + * @param type $publicOnly + * @param type $userId if not present check session + * @param type $isVideoIdPresent pass the ID of the video checking + * @return boolean + */ + public static function getAllFromUserLight($userId, $publicOnly = true, $status = false, $playlists_id = 0, $onlyWithVideos = false) + { + global $global, $config, $refreshCacheFromPlaylist; + $playlists_id = intval($playlists_id); + $formats = ''; + $values = []; + $sql = "SELECT u.*, pl.* FROM " . static::getTableName() . " pl " + . " LEFT JOIN users u ON u.id = users_id WHERE 1=1 "; + if (!empty($playlists_id)) { + $sql .= " AND pl.id = '{$playlists_id}' "; + } + if (!empty($status)) { + $status = str_replace("'", "", $status); + $sql .= " AND pl.status = '{$status}' "; + } elseif ($publicOnly) { + if (User::getId() != $userId) { + $sql .= " AND pl.status = 'public' "; + } + } + if (!empty($userId)) { + $sql .= " AND users_id = ? "; + $formats .= "i"; + $values[] = $userId; + } + $sql .= self::getSqlFromPost("pl."); + //echo $sql, $userId;exit; + $res = sqlDAL::readSql($sql, $formats, $values, $refreshCacheFromPlaylist); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $row = cleanUpRowFromDatabase($row); + if ($onlyWithVideos) { + $videos = self::getVideosIDFromPlaylistLight($row['id']); + if (empty($videos)) { + continue; + } + } + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + public static function fixDuplicatePlayList($user_id) + { + if (empty($user_id)) { + return false; + } + _error_log("PlayList::fixDuplicatePlayList Process user_id = {$user_id} favorite"); + $sql = "SELECT * FROM playlists WHERE users_id = ? AND status = 'favorite' ORDER BY created "; + $res = sqlDAL::readSql($sql, "i", [$user_id], true); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $key => $row) { + if ($key === 0) { + continue; + } + + if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { + _error_log("PlayList::fixDuplicatePlayList favorite PlayList NOT empty {$row['id']}"); + continue; + } + + $sql = "DELETE FROM playlists "; + $sql .= " WHERE id = ?"; + + _error_log("PlayList::fixDuplicatePlayList favorite {$row['id']}"); + sqlDAL::writeSql($sql, "i", [$row['id']]); + } + } + + _error_log("PlayList::fixDuplicatePlayList Process user_id = {$user_id} watch_later"); + $sql = "SELECT * FROM playlists WHERE users_id = ? AND status = 'watch_later' ORDER BY created "; + $res = sqlDAL::readSql($sql, "i", [$user_id], true); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $key => $row) { + if ($key === 0) { + continue; + } + if (!empty(PlayList::getVideosIDFromPlaylistLight($row['id']))) { + _error_log("PlayList::fixDuplicatePlayList watch_later PlayList NOT empty {$row['id']}"); + continue; + } + $sql = "DELETE FROM playlists "; + $sql .= " WHERE id = ?"; + _error_log("PlayList::fixDuplicatePlayList watch_later {$row['id']}"); + ob_flush(); + sqlDAL::writeSql($sql, "i", [$row['id']]); + } + } + } + + public static function getAllFromUserVideo($userId, $videos_id, $publicOnly = true, $status = false) + { + if (empty($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)])) { + $rows = self::getAllFromUser($userId, $publicOnly, $status); + foreach ($rows as $key => $value) { + $rows[$key]['name_translated'] = __($rows[$key]['name']); + $videos = self::getVideosIdFromPlaylist($value['id']); + $rows[$key]['isOnPlaylist'] = in_array($videos_id, $videos); + } + _session_start(); + $_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)] = $rows; + } else { + $rows = $_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id][$userId][intval($publicOnly)][intval($status)]; + } + + return $rows; + } + + private static function removeCache($videos_id) + { + $close = false; + _session_start(); + unset($_SESSION['user']['sessionCache']['getAllFromUserVideo'][$videos_id]); + } + + public static function getVideosIDFromPlaylistLight($playlists_id) + { + global $global, $getVideosIDFromPlaylistLight; + + if (!isset($getVideosIDFromPlaylistLight)) { + $getVideosIDFromPlaylistLight = []; + } + + if (isset($getVideosIDFromPlaylistLight[$playlists_id])) { + return $getVideosIDFromPlaylistLight[$playlists_id]; + } + + $sql = "SELECT * FROM playlists_has_videos p WHERE playlists_id = ? ORDER BY `order` "; + /* + cleanSearchVar(); + $sort = @$_POST['sort']; + $_POST['sort'] = array(); + $sql .= self::getSqlFromPost(); + $_POST['sort'] = $sort; + reloadSearchVar(); + * + */ + $res = sqlDAL::readSql($sql, "i", [$playlists_id]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + $getVideosIDFromPlaylistLight[$playlists_id] = $rows; + return $rows; + } + + public static function getVideosFromPlaylist($playlists_id) + { + $sql = "SELECT *,v.created as cre, p.`order` as video_order, v.externalOptions as externalOptions " + //. ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes " + . " FROM playlists_has_videos p " + . " LEFT JOIN videos as v ON videos_id = v.id " + . " LEFT JOIN users u ON u.id = v.users_id " + . " WHERE playlists_id = ? AND v.status != 'i' "; + cleanSearchVar(); + $sort = @$_POST['sort']; + $_POST['sort'] = []; + $_POST['sort']['p.`order`'] = 'ASC'; + $sql .= self::getSqlFromPost(); + reloadSearchVar(); + $_POST['sort'] = $sort; + $cacheName = "getVideosFromPlaylist{$playlists_id}" . DIRECTORY_SEPARATOR . md5($sql); + $rows = self::getCache($cacheName, 0, true); + if (empty($rows)) { + global $global; + + $res = sqlDAL::readSql($sql, "i", [$playlists_id]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + $SubtitleSwitcher = AVideoPlugin::loadPluginIfEnabled("SubtitleSwitcher"); + if ($res != false) { + foreach ($fullData as $row) { + $row = cleanUpRowFromDatabase($row); + if (!empty($_GET['isChannel'])) { + $row['tags'] = Video::getTags($row['id']); + $row['pluginBtns'] = AVideoPlugin::getPlayListButtons($playlists_id); + $row['humancreate'] = humanTiming(strtotime($row['cre'])); + } + $images = Video::getImageFromFilename($row['filename'], $row['type']); + if (!file_exists($images->posterLandscapePath) && !empty($row['serie_playlists_id'])) { + $images = self::getRandomImageFromPlayList($row['serie_playlists_id']); + } + $row['images'] = $images; + $row['videos'] = Video::getVideosPaths($row['filename'], true); + $row['progress'] = Video::getVideoPogressPercent($row['videos_id']); + $row['title'] = UTF8encode($row['title']); + $row['description'] = UTF8encode($row['description']); + $row['tags'] = Video::getTags($row['videos_id']); + if (AVideoPlugin::isEnabledByName("VideoTags")) { + $row['videoTags'] = Tags::getAllFromVideosId($row['videos_id']); + $row['videoTagsObject'] = Tags::getObjectFromVideosId($row['videos_id']); + } + if ($SubtitleSwitcher) { + $row['subtitles'] = getVTTTracks($row['filename'], true); + foreach ($row['subtitles'] as $value) { + $row['subtitlesSRT'][] = convertSRTTrack($value); + } + } + if (empty($row['externalOptions'])) { + $row['externalOptions'] = json_encode(['videoStartSeconds' => '00:00:00']); + } + $rows[] = $row; + } + + $cache = self::setCache($cacheName, $rows); + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + } else { + $rows = object_to_array($rows); + } + return $rows; + } + + public static function getRandomImageFromPlayList($playlists_id) + { + global $global; + $sql = "SELECT v.* " + . " FROM playlists_has_videos p " + . " LEFT JOIN videos as v ON videos_id = v.id " + . " WHERE playlists_id = ? AND v.status != 'i' ORDER BY RAND() + LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$playlists_id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + $row = $data; + $images = Video::getImageFromFilename($row['filename'], $row['type']); + + if (!file_exists($images->posterLandscapePath) && !empty($row['serie_playlists_id'])) { + return self::getRandomImageFromPlayList($row['serie_playlists_id']); + } + return $images; + } + return false; + } + + public static function isAGroupOfPlayLists($playlists_id) + { + $rows = self::getAllSubPlayLists($playlists_id); + + return count($rows); + } + + public static function getAllSubPlayLists($playlists_id, $NOTSubPlaylists = 0) + { + global $getAllSubPlayLists; + if (empty($playlists_id)) { + return false; + } + if (!isset($getAllSubPlayLists)) { + $getAllSubPlayLists = []; + } + if (!isset($getAllSubPlayLists[$playlists_id])) { + $getAllSubPlayLists[$playlists_id] = []; + } + if (isset($getAllSubPlayLists[$playlists_id][$NOTSubPlaylists])) { + return $getAllSubPlayLists[$playlists_id][$NOTSubPlaylists]; + } + $sql = "SELECT v.* " + . " FROM playlists_has_videos p " + . " LEFT JOIN videos as v ON videos_id = v.id " + . " WHERE playlists_id = ? AND v.status != 'i' "; + + if ($NOTSubPlaylists) { + $sql .= ' AND serie_playlists_id IS NULL '; + } else { + $sql .= ' AND serie_playlists_id IS NOT NULL '; + } + + $res = sqlDAL::readSql($sql, "i", [$playlists_id]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row; + } + } + $getAllSubPlayLists[$playlists_id][$NOTSubPlaylists] = $rows; + return $rows; + } + + public static function getAllNOTSubPlayLists($playlists_id) + { + return self::getAllSubPlayLists($playlists_id, 1); + } + + public static function isVideoOnFavorite($videos_id, $users_id) + { + return self::isVideoOn($videos_id, $users_id, 'favorite'); + } + + public static function isVideoOnWatchLater($videos_id, $users_id) + { + return self::isVideoOn($videos_id, $users_id, 'watch_later'); + } + + private static function isVideoOn($videos_id, $users_id, $status) + { + global $global; + $status = str_replace("'", "", $status); + + $sql = "SELECT pl.id FROM " . static::getTableName() . " pl " + . " LEFT JOIN users u ON u.id = users_id " + . " LEFT JOIN playlists_has_videos p ON pl.id = playlists_id" + . " LEFT JOIN videos as v ON videos_id = v.id " + . " WHERE videos_id = ? AND pl.users_id = ? AND pl.status = '{$status}' LIMIT 1 "; + //echo $videos_id," - " ,$users_id, $sql; + $res = sqlDAL::readSql($sql, "ii", [$videos_id, $users_id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res) { + $row = $data; + $row = cleanUpRowFromDatabase($row); + } else { + $row = false; + } + return $row; + } + + public static function getFavoriteIdFromUser($users_id) + { + global $refreshCacheFromPlaylist; + $favorite = self::getIdFromUser($users_id, "favorite"); + if (empty($favorite)) { + $pl = new PlayList(0); + $pl->setName("Favorite"); + $pl->setUsers_id($users_id); + $pl->setStatus("favorite"); + $pl->save(); + $refreshCacheFromPlaylist = true; + $favorite = self::getIdFromUser($users_id, "favorite"); + } + return $favorite; + } + + public static function getWatchLaterIdFromUser($users_id) + { + global $refreshCacheFromPlaylist; + $watch_later = self::getIdFromUser($users_id, "watch_later"); + + if (empty($watch_later)) { + $pl = new PlayList(0); + $pl->setName("Watch Later"); + $pl->setUsers_id($users_id); + $pl->setStatus("watch_later"); + $pl->save(); + $refreshCacheFromPlaylist = true; + $watch_later = self::getIdFromUser($users_id, "watch_later"); + } + return $watch_later; + } + + private static function getIdFromUser($users_id, $status) + { + global $global; + + $status = str_replace("'", "", $status); + $sql = "SELECT * FROM " . static::getTableName() . " pl WHERE" + . " users_id = ? AND pl.status = '{$status}' LIMIT 1 "; + $res = sqlDAL::readSql($sql, "i", [$users_id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res && !empty($data)) { + $row = $data['id']; + } else { + $row = false; + } + return $row; + } + + public static function getVideosIdFromPlaylist($playlists_id) + { + global $getVideosIdFromPlaylist; + if (empty($getVideosIdFromPlaylist)) { + $getVideosIdFromPlaylist = []; + } + if (isset($getVideosIdFromPlaylist[$playlists_id])) { + return $getVideosIdFromPlaylist[$playlists_id]; + } + $videosId = []; + $rows = static::getVideosIDFromPlaylistLight($playlists_id); + foreach ($rows as $value) { + $videosId[] = $value['videos_id']; + } + + $getVideosIdFromPlaylist[$playlists_id] = $videosId; + return $videosId; + } + + public static function sortVideos($videosList, $listIdOrder) + { + $list = []; + foreach ($listIdOrder as $value) { + $found = false; + foreach ($videosList as $key => $value2) { + if ($value2['id'] == $value) { + $list[] = $value2; + unset($videosList[$key]); + $found = true; + } + } + if (!$found) { + $v = new Video("", "", $value); + if (empty($v->getFilename())) { + continue; + } + $list[] = ['id' => $value]; + } + } + return $list; + } + + public function save() + { + if (!User::isLogged()) { + return false; + } + $this->clearEmptyLists(); + $users_id = User::getId(); + $this->setUsers_id($users_id); + $this->showOnTV = intval($this->showOnTV); + $playlists_id = parent::save(); + if (!empty($playlists_id)) { + self::deleteCacheDir($playlists_id); + } + return $playlists_id; + } + + /** + * This is just to fix errors from the update 6.4 to 6.5, where empty playlists were created before the update + * @return type + */ + private function clearEmptyLists() + { + $sql = "DELETE FROM " . static::getTableName() . " WHERE status = ''"; + + return sqlDAL::writeSql($sql); + } + + public function addVideo($videos_id, $add, $order = 0) + { + global $global; + $formats = ''; + $values = []; + if (empty($add) || $add === "false") { + $sql = "DELETE FROM playlists_has_videos WHERE playlists_id = ? AND videos_id = ? "; + $formats = "ii"; + $values[] = $this->id; + $values[] = $videos_id; + } else { + $this->addVideo($videos_id, false); + $sql = "INSERT INTO playlists_has_videos ( playlists_id, videos_id , `order`) VALUES (?, ?, ?) "; + $formats = "iii"; + $values[] = $this->id; + $values[] = $videos_id; + $values[] = $order; + } + $result = sqlDAL::writeSql($sql, $formats, $values); + self::deleteCacheDir($this->id); + self::removeCache($videos_id); + return $result; + } + + private static function deleteCacheDir($playlists_id) + { + $tmpDir = ObjectYPT::getCacheDir(); + $name = "getvideosfromplaylist{$playlists_id}"; + $cacheDir = $tmpDir . $name . DIRECTORY_SEPARATOR; + rrmdir($cacheDir); + if (class_exists('CachesInDB')) { + CachesInDB::_deleteCacheStartingWith($name); + } + } + + public function delete() + { + if (empty($this->id)) { + return false; + } + global $global; + $sql = "DELETE FROM playlists WHERE id = ? "; + //echo $sql; + $result = sqlDAL::writeSql($sql, "i", [$this->id]); + + self::deleteCacheDir($this->id); + return $result; + } + + public function getId() + { + return $this->id; + } + + public function getName() + { + return $this->name; + } + + public function getModified() + { + return $this->modified; + } + + public function getUsers_id() + { + return $this->users_id; + } + + public function getStatus() + { + return $this->status; + } + + public function setId($id) + { + $this->id = $id; + } + + public function setName($name) + { + if (strlen($name) > 45) { + $name = substr($name, 0, 42) . '...'; + } + $this->name = xss_esc($name); + //var_dump($name,$this->name);exit; + } + + public function setUsers_id($users_id) + { + $this->users_id = $users_id; + } + + public function setStatus($status) + { + if (!in_array($status, self::$validStatus)) { + $status = 'public'; + } + $this->status = $status; + } + + public static function canSee($playlist_id, $users_id) + { + $obj = new PlayList($playlist_id); + $status = $obj->getStatus(); + if ($status !== 'public' && $status !== 'unlisted' && $users_id != $obj->getUsers_id()) { + return false; + } + return true; + } + + public static function getEPG() + { + global $config, $global; + $encoder = $config->_getEncoderURL(); + $url = "{$encoder}view/videosListEPG.php?date_default_timezone=" . urlencode(date_default_timezone_get()); + + $content = url_get_contents($url); + return _json_decode($content); + } + + public function getShowOnTV() + { + return intval($this->showOnTV); + } + + public function setShowOnTV($showOnTV) + { + if (strtolower($showOnTV) === "false") { + $showOnTV = 0; + } elseif (strtolower($showOnTV) === "true") { + $showOnTV = 1; + } + $this->showOnTV = intval($showOnTV); + } + + public static function getAllToShowOnTV() + { + global $global; + if (!static::isTableInstalled()) { + return false; + } + $sql = "SELECT u.*, pl.* FROM playlists pl " + . " LEFT JOIN users u ON users_id = u.id " + . " WHERE showOnTV=1 "; + + $sql .= self::getSqlFromPost(); + //echo $sql;exit; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $row = cleanUpRowFromDatabase($row); + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + public static function showPlayListSelector($playListArray) + { + $collections = []; + $videos = []; + foreach ($playListArray as $value) { + if ($value['type'] === 'serie' && !empty($value['serie_playlists_id'])) { + $collections[] = $value; + } else { + $videos[] = $value; + } + } + $countCollections = count($collections); + $countVideos = count($videos); + if (!empty($countCollections)) { + if ($countCollections === 1 && empty($countVideos)) { + return false; + } + return $collections; + } + return false; + } +} diff --git a/objects/playlistAddNew.json.php b/objects/playlistAddNew.json.php index c51f8a5017..ee21a45fea 100644 --- a/objects/playlistAddNew.json.php +++ b/objects/playlistAddNew.json.php @@ -1,8 +1,7 @@ getUsers_id()){ - die('{"error":"'.__("Permission denied").'"}'); -} - -echo '{"status":"'.$obj->delete().'"}'; +getUsers_id()) { + die('{"error":"'.__("Permission denied").'"}'); +} + +echo '{"status":"'.$obj->delete().'"}'; diff --git a/objects/playlistRemoveVideo.php b/objects/playlistRemoveVideo.php index 12559bf1dc..9c111711bc 100644 --- a/objects/playlistRemoveVideo.php +++ b/objects/playlistRemoveVideo.php @@ -1,18 +1,18 @@ -getUsers_id()){ - die('{"error":"'.__("Permission denied").'"}'); -} -$result = $obj->addVideo($_POST['video_id'], false); - -echo '{"status":"'.$result.'"}'; +getUsers_id()) { + die('{"error":"'.__("Permission denied").'"}'); +} +$result = $obj->addVideo($_POST['video_id'], false); + +echo '{"status":"'.$result.'"}'; diff --git a/objects/playlistRename.php b/objects/playlistRename.php index 1981a1d2c1..e9dc30fbb6 100644 --- a/objects/playlistRename.php +++ b/objects/playlistRename.php @@ -1,39 +1,39 @@ -error = true; -$obj->msg = ''; -$obj->name = ''; - -if (empty($_REQUEST['playlist_id'])) { - $obj->msg = "playlist_id cannot be empty"; - die(json_encode($obj)); -} -if (empty($_REQUEST['name'])) { - $obj->msg = "name cannot be empty"; - die(json_encode($obj)); -} - -$obj->name = $_REQUEST['name']; - -require_once $global['systemRootPath'] . 'objects/user.php'; -require_once $global['systemRootPath'] . 'objects/playlist.php'; -if (!User::isLogged()) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} -$playList = new PlayList($_REQUEST['playlist_id']); -if(!User::isAdmin() && User::getId() != $playList->getUsers_id()){ - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -$playList->setName($obj->name); -$obj->error = empty($playList->save()); - -die(json_encode($obj)); +error = true; +$obj->msg = ''; +$obj->name = ''; + +if (empty($_REQUEST['playlist_id'])) { + $obj->msg = "playlist_id cannot be empty"; + die(json_encode($obj)); +} +if (empty($_REQUEST['name'])) { + $obj->msg = "name cannot be empty"; + die(json_encode($obj)); +} + +$obj->name = $_REQUEST['name']; + +require_once $global['systemRootPath'] . 'objects/user.php'; +require_once $global['systemRootPath'] . 'objects/playlist.php'; +if (!User::isLogged()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} +$playList = new PlayList($_REQUEST['playlist_id']); +if (!User::isAdmin() && User::getId() != $playList->getUsers_id()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +$playList->setName($obj->name); +$obj->error = empty($playList->save()); + +die(json_encode($obj)); diff --git a/objects/playlistSort.php b/objects/playlistSort.php index 1eb950a7af..d73e935971 100644 --- a/objects/playlistSort.php +++ b/objects/playlistSort.php @@ -1,96 +1,96 @@ -getUsers_id()) { - die('{"error":"'.__("Permission denied").'"}'); -} - -$count = 1; - -if (empty($_POST['list'])) { - // get all videos from playlist - $videosArrayId = PlayList::getVideosIdFromPlaylist($_POST['playlist_id']); - $videos = array(); - foreach ($videosArrayId as $value) { - $videos[] = Video::getVideoLight($value); - } - $sortFunc = "titleASC"; - switch ($_GET['sort']) { - case 1: - $sortFunc = "titleASC"; - break; - case 2: - $sortFunc = "titleDESC"; - break; - case 3: - $sortFunc = "dateCmp"; - break; - case 4: - $sortFunc = "dateCmpDesc"; - break; - } - //var_dump($sortFunc);exit; - // sort video - uasort($videos, $sortFunc); - - // transfer the id to the list - foreach ($videos as $key => $value) { - $_POST['list'][] = $value['id']; - } -} - -foreach ($_POST['list'] as $key => $value) { - $result = $obj->addVideo($value, true, $count++); -} - -if (!empty($_GET['sort'])) { - header("Location: ". $_SERVER['HTTP_REFERER']); - //header("Location: ". User::getChannelLink($obj->getUsers_id())); - exit; -} -$o = new stdClass(); -$o->status = $result; -//$o->channelName = $obj->get; -echo json_encode($o);exit; - -// Comparison function -function dateCmp($videoA, $videoB) -{ - $a = strtotime($videoA['created']); - $b = strtotime($videoB['created']); - if ($a == $b) { - return 0; - } - return ($a > $b) ? -1 : 1; -} -function dateCmpDesc($videoA, $videoB) -{ - $a = strtotime($videoA['created']); - $b = strtotime($videoB['created']); - if ($a == $b) { - return 0; - } - return ($a < $b) ? -1 : 1; -} -function titleASC($videoA, $videoB) -{ - return strcasecmp($videoA['title'], $videoB['title']); -} -function titleDESC($videoA, $videoB) -{ - return strcasecmp($videoB['title'], $videoA['title']); -} +getUsers_id()) { + die('{"error":"'.__("Permission denied").'"}'); +} + +$count = 1; + +if (empty($_POST['list'])) { + // get all videos from playlist + $videosArrayId = PlayList::getVideosIdFromPlaylist($_POST['playlist_id']); + $videos = []; + foreach ($videosArrayId as $value) { + $videos[] = Video::getVideoLight($value); + } + $sortFunc = "titleASC"; + switch ($_GET['sort']) { + case 1: + $sortFunc = "titleASC"; + break; + case 2: + $sortFunc = "titleDESC"; + break; + case 3: + $sortFunc = "dateCmp"; + break; + case 4: + $sortFunc = "dateCmpDesc"; + break; + } + //var_dump($sortFunc);exit; + // sort video + uasort($videos, $sortFunc); + + // transfer the id to the list + foreach ($videos as $key => $value) { + $_POST['list'][] = $value['id']; + } +} + +foreach ($_POST['list'] as $key => $value) { + $result = $obj->addVideo($value, true, $count++); +} + +if (!empty($_GET['sort'])) { + header("Location: ". $_SERVER['HTTP_REFERER']); + //header("Location: ". User::getChannelLink($obj->getUsers_id())); + exit; +} +$o = new stdClass(); +$o->status = $result; +//$o->channelName = $obj->get; +echo json_encode($o);exit; + +// Comparison function +function dateCmp($videoA, $videoB) +{ + $a = strtotime($videoA['created']); + $b = strtotime($videoB['created']); + if ($a == $b) { + return 0; + } + return ($a > $b) ? -1 : 1; +} +function dateCmpDesc($videoA, $videoB) +{ + $a = strtotime($videoA['created']); + $b = strtotime($videoB['created']); + if ($a == $b) { + return 0; + } + return ($a < $b) ? -1 : 1; +} +function titleASC($videoA, $videoB) +{ + return strcasecmp($videoA['title'], $videoB['title']); +} +function titleDESC($videoA, $videoB) +{ + return strcasecmp($videoB['title'], $videoA['title']); +} diff --git a/objects/playlistStatus.php b/objects/playlistStatus.php index d5c0091eaa..44df82380d 100644 --- a/objects/playlistStatus.php +++ b/objects/playlistStatus.php @@ -1,17 +1,17 @@ -getUsers_id()){ - die('{"error":"'.__("Permission denied").'"}'); -} -$obj->setStatus($_POST['status']); -echo '{"status":"'.$obj->save().'"}'; +getUsers_id()) { + die('{"error":"'.__("Permission denied").'"}'); +} +$obj->setStatus($_POST['status']); +echo '{"status":"'.$obj->save().'"}'; diff --git a/objects/playlists.json.php b/objects/playlists.json.php index 69d05a1977..4bfca32df1 100644 --- a/objects/playlists.json.php +++ b/objects/playlists.json.php @@ -1,18 +1,18 @@ - $value) { - foreach ($row[$key]['videos'] as $key2 => $value2) { - unset($row[$key]['videos'][$key2]['description']); - } -} -echo json_encode($row); + $value) { + foreach ($row[$key]['videos'] as $key2 => $value2) { + unset($row[$key]['videos'][$key2]['description']); + } +} +echo json_encode($row); diff --git a/objects/playlistsFromUser.json.php b/objects/playlistsFromUser.json.php index cbb0c683a6..c22f04a808 100644 --- a/objects/playlistsFromUser.json.php +++ b/objects/playlistsFromUser.json.php @@ -1,18 +1,18 @@ - $value) { - $_POST[$key]=$value; - } -} -if(!empty($_POST['user']) && !empty($_POST['pass'])){ - $user = new User(0, $_POST['user'], $_POST['pass']); - $user->login(false, true); -} -if(empty($_POST['playlists_id'])){ - die('Play List can not be empty'); -} - -require_once './playlist.php'; -$videos = PlayList::getVideosFromPlaylist($_POST['playlists_id']); -$objMob = AVideoPlugin::getObjectData("MobileManager"); -$index = 0; -foreach ($videos as $key => $value) { - $videos[$key] = cleanUpRowFromDatabase($videos[$key]); - $images = Video::getImageFromFilename($videos[$key]['filename'], $videos[$key]['type']); - $videos[$key]['images'] = $images; - $videos[$key]['Poster'] = !empty($objMob->portraitImage)?$images->posterPortrait:$images->poster; - $videos[$key]['Thumbnail'] = !empty($objMob->portraitImage)?$images->posterPortraitThumbs:$images->thumbsJpg; - $videos[$key]['imageClass'] = !empty($objMob->portraitImage)?"portrait":"landscape"; - $videos[$key]['VideoUrl'] = getVideosURL($videos[$key]['filename']); - $videos[$key]['createdHumanTiming'] = humanTiming(strtotime($videos[$key]['created'])); - $videos[$key]['pageUrl'] = PlayLists::getLink($_POST['playlists_id'], false, $index); - $videos[$key]['embedUrl'] = PlayLists::getLink($_POST['playlists_id'], true, $index); - unset($_POST['sort'], $_POST['current'], $_POST['searchPhrase']); - $_REQUEST['rowCount'] = 10; - $_POST['sort']['created'] = "desc"; - $videos[$key]['comments'] = Comment::getAllComments($videos[$key]['id']); - $videos[$key]['commentsTotal'] = Comment::getTotalComments($videos[$key]['id']); - foreach ($videos[$key]['comments'] as $key2 => $value2) { - $user = new User($value2['users_id']); - $videos[$key]['comments'][$key2]['userPhotoURL'] = User::getPhoto($videos[$key]['comments'][$key2]['users_id']); - $videos[$key]['comments'][$key2]['userName'] = $user->getNameIdentificationBd(); - } - $videos[$key]['subscribers'] = Subscribe::getTotalSubscribes($videos[$key]['users_id']); - - $videos[$key]['firstVideo'] = ""; - foreach ($videos[$key]['VideoUrl'] as $value2) { - if($value2["type"] === 'video'){ - $videos[$key]['firstVideo'] = $value2["url"]; - break; - } - } - if(preg_match("/^videos/", $videos[$key]['photoURL'])){ - $videos[$key]['UserPhoto'] = "{$global['webSiteRootURL']}".$videos[$key]['photoURL']; - }else{ - $videos[$key]['UserPhoto'] = $videos[$key]['photoURL']; - } - $index++; -} - -echo json_encode($videos); + $value) { + $_POST[$key]=$value; + } +} +if (!empty($_POST['user']) && !empty($_POST['pass'])) { + $user = new User(0, $_POST['user'], $_POST['pass']); + $user->login(false, true); +} +if (empty($_POST['playlists_id'])) { + die('Play List can not be empty'); +} + +require_once './playlist.php'; +$videos = PlayList::getVideosFromPlaylist($_POST['playlists_id']); +$objMob = AVideoPlugin::getObjectData("MobileManager"); +$index = 0; +foreach ($videos as $key => $value) { + $videos[$key] = cleanUpRowFromDatabase($videos[$key]); + $images = Video::getImageFromFilename($videos[$key]['filename'], $videos[$key]['type']); + $videos[$key]['images'] = $images; + $videos[$key]['Poster'] = !empty($objMob->portraitImage) ? $images->posterPortrait : $images->poster; + $videos[$key]['Thumbnail'] = !empty($objMob->portraitImage) ? $images->posterPortraitThumbs : $images->thumbsJpg; + $videos[$key]['imageClass'] = !empty($objMob->portraitImage) ? "portrait" : "landscape"; + $videos[$key]['VideoUrl'] = getVideosURL($videos[$key]['filename']); + $videos[$key]['createdHumanTiming'] = humanTiming(strtotime($videos[$key]['created'])); + $videos[$key]['pageUrl'] = PlayLists::getLink($_POST['playlists_id'], false, $index); + $videos[$key]['embedUrl'] = PlayLists::getLink($_POST['playlists_id'], true, $index); + unset($_POST['sort'], $_POST['current'], $_POST['searchPhrase']); + $_REQUEST['rowCount'] = 10; + $_POST['sort']['created'] = "desc"; + $videos[$key]['comments'] = Comment::getAllComments($videos[$key]['id']); + $videos[$key]['commentsTotal'] = Comment::getTotalComments($videos[$key]['id']); + foreach ($videos[$key]['comments'] as $key2 => $value2) { + $user = new User($value2['users_id']); + $videos[$key]['comments'][$key2]['userPhotoURL'] = User::getPhoto($videos[$key]['comments'][$key2]['users_id']); + $videos[$key]['comments'][$key2]['userName'] = $user->getNameIdentificationBd(); + } + $videos[$key]['subscribers'] = Subscribe::getTotalSubscribes($videos[$key]['users_id']); + + $videos[$key]['firstVideo'] = ''; + foreach ($videos[$key]['VideoUrl'] as $value2) { + if ($value2["type"] === 'video') { + $videos[$key]['firstVideo'] = $value2["url"]; + break; + } + } + if (preg_match("/^videos/", $videos[$key]['photoURL'])) { + $videos[$key]['UserPhoto'] = "{$global['webSiteRootURL']}".$videos[$key]['photoURL']; + } else { + $videos[$key]['UserPhoto'] = $videos[$key]['photoURL']; + } + $index++; +} + +echo json_encode($videos); diff --git a/objects/plugin.php b/objects/plugin.php index 7452b88cbf..7c154c3d6d 100644 --- a/objects/plugin.php +++ b/objects/plugin.php @@ -1,541 +1,583 @@ -id; - } - - function getStatus() { - return $this->status; - } - - function getObject_data() { - return $this->object_data; - } - - function getPluginVersion() { - return $this->pluginVersion; - } - - function getName() { - return $this->name; - } - - function setId($id) { - $this->id = $id; - } - - function setStatus($status) { - $this->status = $status; - } - - function setObject_data($object_data) { - $this->object_data = $object_data; - } - - function setName($name) { - $name = preg_replace("/[^A-Za-z0-9 _-]/", '', $name); - $this->name = $name; - } - - function getUuid() { - return $this->uuid; - } - - function getDirName() { - return $this->dirName; - } - - function setUuid($uuid) { - $this->uuid = $uuid; - $this->loadFromUUID($uuid); - } - - function setDirName($dirName) { - $dirName = preg_replace("/[^A-Za-z0-9 _-]/", '', $dirName); - $this->dirName = $dirName; - } - - function setPluginversion($pluginversion) { - $this->pluginversion = $pluginversion; - } - - static function setCurrentVersionByUuid($uuid, $currentVersion) { - _error_log("plugin::setCurrentVersionByUuid $uuid, $currentVersion"); - $p = static::getPluginByUUID($uuid); - if (!$p) { - _error_log("plugin::setCurrentVersionByUuid error on get plugin"); - return false; - } - //pluginversion isn't an object property so we must explicity update it using this function - $sql = "update " . static::getTableName() . " set pluginversion='$currentVersion' where uuid='$uuid'"; - - $name = "plugin$uuid"; - ObjectYPT::deleteCache($name); - $res = sqlDal::writeSql($sql); - } - - static function getCurrentVersionByUuid($uuid) { - $p = static::getPluginByUUID($uuid); - if (!$p) - return false; - //pluginversion isn't an object property so we must explicity update it using this function - $sql = "SELECT pluginversion FROM " . static::getTableName() . " WHERE uuid=? LIMIT 1 "; - $res = sqlDAL::readSql($sql, "s", array($uuid)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - return $data['pluginversion']; - } - return false; - } - - static function getPluginByName($name) { - global $global, $getPluginByName; - if (empty($getPluginByName)) { - $getPluginByName = array(); - } - if (empty($getPluginByName[$name])) { - $sql = "SELECT * FROM " . static::getTableName() . " WHERE name = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "s", array($name), true); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - $getPluginByName[$name] = $data; - } else { - $getPluginByName[$name] = false; - } - } - return $getPluginByName[$name]; - } - - static function getPluginByUUID($uuid) { - global $global, $getPluginByUUID, $pluginJustInstalled; - $name = "plugin$uuid"; - if (!isset($getPluginByUUID)) { - $getPluginByUUID = array(); - } - if (!isset($pluginJustInstalled)) { - $pluginJustInstalled = array(); - } - if (empty($getPluginByUUID[$uuid])) { - $sql = "SELECT * FROM " . static::getTableName() . " WHERE uuid = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "s", array($uuid)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - if (empty($data['pluginversion'])) { - $data['pluginversion'] = "1.0"; - } - if (AVideoPlugin::isPluginOnByDefault($uuid)) { - $data['status'] = 'active'; - } - $getPluginByUUID[$uuid] = $data; - } else { - $name = AVideoPlugin::getPluginsNameOnByDefaultFromUUID($uuid); - if ($name !== false && empty($pluginJustInstalled[$uuid])) { - $pluginJustInstalled[$uuid] = 1; - _error_log("plugin::getPluginByUUID {$name} {$uuid} this plugin is On By Default we will install it ($sql)"); - self::deleteByUUID($uuid); - self::deleteByName($name); - unset($getPluginByUUID[$uuid]); - $getPluginByUUID[$uuid] = self::getOrCreatePluginByName($name, 'active'); - } else { - $getPluginByUUID[$uuid] = false; - } - } - } - return $getPluginByUUID[$uuid]; - } - - function loadFromUUID($uuid) { - $uuid = preg_replace("/[^A-Za-z0-9 _-]/", '', $uuid); - $this->uuid = $uuid; - $row = static::getPluginByUUID($uuid); - if (!empty($row)) { - $this->load($row['id']); - } - } - - static function isEnabledByName($name) { - $row = static::getPluginByName($name); - if ($row) { - return $row['status'] == 'active' && AVideoPlugin::isPluginTablesInstalled($name, true); - } - return false; - } - - static function isEnabledByUUID($uuid) { - $row = static::getPluginByUUID($uuid); - if ($row) { - return $row['status'] == 'active' && AVideoPlugin::isPluginTablesInstalled($row['name'], true); - } - return false; - } - - static function getAvailablePlugins($comparePluginVersion = false) { - global $global, $getAvailablePlugins; - $pluginsMarketplace = array(); - if ($comparePluginVersion) { - $pluginsMarketplace = ObjectYPT::getSessionCache('getAvailablePlugins', 600); // 10 min cache - if (empty($pluginsMarketplace)) { - $pluginsMarketplace = _json_decode(url_get_contents("https://tutorials.avideo.com/info?version=1", "", 2)); - if (!empty($pluginsMarketplace)) { - ObjectYPT::setSessionCache('getAvailablePlugins', $pluginsMarketplace); - } - } - } - if (empty($getAvailablePlugins)) { - $dir = $global['systemRootPath'] . "plugin"; - $getAvailablePlugins = array(); - $cdir = scandir($dir); - foreach ($cdir as $key => $value) { - if (!in_array($value, array(".", ".."))) { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { - $p = AVideoPlugin::loadPlugin($value); - if (!is_object($p) || $p->hidePlugin()) { - if ($value !== "Statistics") { // avoid error while this plugin is not ready - _error_log("Plugin Not Found: {$value}"); - } - continue; - } - $obj = new stdClass(); - $obj->name = $p->getName(); - $obj->dir = $value; - $obj->uuid = $p->getUUID(); - $obj->description = $p->getDescription(); - $obj->installedPlugin = static::getPluginByUUID($obj->uuid); - $obj->enabled = (!empty($obj->installedPlugin['status']) && $obj->installedPlugin['status'] === "active") ? true : false; - $obj->id = (!empty($obj->installedPlugin['id'])) ? $obj->installedPlugin['id'] : 0; - $obj->data_object = $p->getDataObject(); - $obj->data_object_helper = $p->getDataObjectHelper(); - $obj->databaseScript = !empty(static::getDatabaseFile($value)); - $obj->pluginMenu = $p->getPluginMenu(); - $obj->tags = $p->getTags(); - $obj->pluginversion = $p->getPluginVersion(); - $obj->pluginversionMarketPlace = (!empty($pluginsMarketplace->plugins->{$obj->uuid}) ? $pluginsMarketplace->plugins->{$obj->uuid}->pluginversion : 0); - $obj->pluginversionCompare = (!empty($obj->pluginversionMarketPlace) ? version_compare($obj->pluginversion, $obj->pluginversionMarketPlace) : 0); - $obj->permissions = $obj->enabled ? Permissions::getPluginPermissions($obj->id) : array(); - if (User::isAdmin()) { - $obj->isPluginTablesInstalled = AVideoPlugin::isPluginTablesInstalled($obj->name, false); - } - if ($obj->pluginversionCompare < 0) { - $obj->tags[] = "update"; - } - $getAvailablePlugins[] = $obj; - } - } - } - } - return $getAvailablePlugins; - } - - static function getAvailablePluginsBasic() { - global $global, $getAvailablePlugins; - if (empty($getAvailablePlugins)) { - $dir = $global['systemRootPath'] . "plugin"; - $getAvailablePlugins = array(); - $cdir = scandir($dir); - foreach ($cdir as $key => $value) { - if (!in_array($value, array(".", ".."))) { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { - $p = AVideoPlugin::loadPlugin($value); - if (!is_object($p) || $p->hidePlugin()) { - if ($value !== "Statistics") { // avoid error while this plugin is not ready - _error_log("Plugin Not Found: {$value}"); - } - continue; - } - $row = self::getPluginByUUID($p->getUUID()); - $obj = new stdClass(); - $obj->name = $p->getName(); - $obj->pluginversion = $p->getPluginVersion(); - $obj->status = $row['status']; - - $pinfoFile = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR . 'pinfo.json'; - if (file_exists($pinfoFile)) { - $obj->pinfo = json_decode(file_get_contents($pinfoFile)); - } else { - $obj->pinfo = false; - } - $getAvailablePlugins[$p->getUUID()] = $obj; - } - } - } - } - return $getAvailablePlugins; - } - - static function getDatabaseFile($pluginName) { - $filename = static::getDatabaseFileName($pluginName); - if (!$filename) { - return false; - } - return url_get_contents($filename); - } - - static function getDatabaseFileName($pluginName) { - global $global; - - $pluginName = AVideoPlugin::fixName($pluginName); - $dir = $global['systemRootPath'] . "plugin"; - $filename = $dir . DIRECTORY_SEPARATOR . $pluginName . DIRECTORY_SEPARATOR . "install" . DIRECTORY_SEPARATOR . "install.sql"; - if (!file_exists($filename)) { - return false; - } - return $filename; - } - - static function getAllEnabled($try = 0) { - global $global, $getAllEnabledRows; - if (empty($getAllEnabledRows)) { - $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='active' "; - - $defaultEnabledUUIDs = AVideoPlugin::getPluginsOnByDefault(true); - $defaultEnabledNames = AVideoPlugin::getPluginsOnByDefault(false); - $sql .= " OR uuid IN ('" . implode("','", $defaultEnabledUUIDs) . "')"; - - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $getAllEnabledRows = array(); - foreach ($fullData as $row) { - $getAllEnabledRows[] = $row; - if (($key = array_search($row['uuid'], $defaultEnabledUUIDs)) !== false) { - unset($defaultEnabledUUIDs[$key], $defaultEnabledNames[$key]); - } - } - - $addedNewPlugin = false; - foreach ($defaultEnabledUUIDs as $key => $value) { - $obj = new Plugin(0); - $obj->loadFromUUID($defaultEnabledUUIDs[$key]); - $obj->setName($defaultEnabledNames[$key]); - $obj->setDirName($defaultEnabledNames[$key]); - $obj->setStatus("active"); - if ($obj->save()) { - $addedNewPlugin = true; - } - } - - if ($addedNewPlugin && empty($try)) { - //ObjectYPT::deleteALLCache(); - return self::getAllEnabled(1); - } - - uasort($getAllEnabledRows, 'cmpPlugin'); - } - return $getAllEnabledRows; - } - - static function getAllDisabled() { - global $global, $getAllDisabledRows; - if (empty($getAllDisabledRows)) { - $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='inactive' "; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $getAllDisabledRows = array(); - foreach ($fullData as $row) { - $getAllDisabledRows[] = $row; - } - uasort($getAllDisabledRows, 'cmpPlugin'); - } - return $getAllDisabledRows; - } - - static function getEnabled($uuid) { - global $global, $getEnabled; - if (empty($getEnabled)) { - $getEnabled = array(); - } - - if (in_array($uuid, AVideoPlugin::getPluginsOnByDefault())) { - // make sure the OnByDefault plugins are enabled - return self::getOrCreatePluginByName(AVideoPlugin::getPluginsNameOnByDefaultFromUUID($uuid)); - } - - if (empty($getEnabled[$uuid])) { - $getEnabled[$uuid] = array(); - $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='active' AND uuid = '" . $uuid . "' ;"; - $res = sqlDAL::readSql($sql); - $pluginRows = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($pluginRows != false) { - foreach ($pluginRows as $row) { - $getEnabled[$uuid][] = $row; - } - } - } - - return $getEnabled[$uuid]; - } - - static function deleteByUUID($uuid) { - global $global; - $uuid = $global['mysqli']->real_escape_string($uuid); - if (!empty($uuid)) { - _error_log("Plugin:deleteByUUID {$uuid}"); - $sql = "DELETE FROM " . static::getTableName() . " "; - $sql .= " WHERE uuid = ?"; - $global['lastQuery'] = $sql; - //_error_log("Delete Query: ".$sql); - return sqlDAL::writeSql($sql, "s", array($uuid)); - } - return false; - } - - static function deleteByName($name) { - global $global; - $name = $global['mysqli']->real_escape_string($name); - if (!empty($name)) { - _error_log("Plugin:deleteByName {$name}"); - $sql = "DELETE FROM " . static::getTableName() . " "; - $sql .= " WHERE name = ?"; - $global['lastQuery'] = $sql; - //_error_log("Delete Query: ".$sql); - return sqlDAL::writeSql($sql, "s", array($name)); - } - return false; - } - - static function getOrCreatePluginByName($name, $statusIfCreate = 'inactive') { - global $global; - if (self::getPluginByName($name) === false) { - $pluginFile = $global['systemRootPath'] . "plugin/{$name}/{$name}.php"; - if (file_exists($pluginFile)) { - require_once $pluginFile; - $code = "\$p = new {$name}();"; - eval($code); - $plugin = new Plugin(0); - $plugin->setUuid($p->getUUID()); - $plugin->setDirName($name); - $plugin->setName($name); - $plugin->setObject_data(json_encode($p->getDataObject())); - $plugin->setStatus($statusIfCreate); - $plugin->setPluginversion($p->getPluginVersion()); - $plugin->save(); - } - } - return self::getPluginByName($name); - } - - function save() { - if (empty($this->uuid)) { - return false; - } - global $global; - $this->object_data = $global['mysqli']->real_escape_string($this->object_data); - if (empty($this->object_data)) { - $this->object_data = 'null'; - } - self::deletePluginCache($this->uuid); - //ObjectYPT::deleteALLCache(); - return parent::save(); - } - - static function deletePluginCache($uuid) { - $name = "plugin{$uuid}"; - ObjectYPT::deleteCache($name); - ObjectYPT::deleteCache("plugin::getAllEnabled"); - } - - static function encryptIfNeed($object_data) { - $isString = false; - if (!is_object($object_data)) { - $object_data = _json_decode($object_data); - $isString = true; - } - if (!empty($object_data)) { - foreach ($object_data as $key => $value) { - if (!empty($value->type) && !empty($value->value) && is_string($value->type) && strtolower($value->type) === "encrypted") { - if (!self::isEncrypted($value->value)) { - $obj2 = new stdClass(); - $obj2->dateEncrypted = time(); - $obj2->value = $value->value; - $object_data->$key->value = encryptString($obj2); - } - } - } - if ($isString) { - $object_data = json_encode($object_data); - } - return $object_data; - } else { - return ''; - } - } - - static function decryptIfNeed($object_data) { - $isString = false; - if (!is_object($object_data)) { - $object_data = _json_decode($object_data); - $isString = true; - } - if (!empty($object_data)) { - foreach ($object_data as $key => $value) { - if (!empty($value->type) && !empty($value->value) && strtolower($value->type) === "encrypted") { - $isEncrypted = self::isEncrypted($value->value); - if ($isEncrypted) { - $object_data->$key->value = $isEncrypted; - } - } - } - if ($isString) { - $object_data = json_encode($object_data); - } - return $object_data; - } else { - return ''; - } - } - - static function isEncrypted($object_data_element_value) { - if (!empty($object_data_element_value)) { - $object_data_element_value_json = decryptString($object_data_element_value); - $object_data_element_value_json = _json_decode($object_data_element_value_json); - if (!empty($object_data_element_value_json) && !empty($object_data_element_value_json->dateEncrypted)) { - return $object_data_element_value_json->value; - } - } - return false; - } - -} - -class PluginTags { - - static $RECOMMENDED = array('success', 'Recommended', '', 'RECOMMENDED'); - static $SECURITY = array('warning', 'Security', '', 'SECURITY'); - static $LIVE = array('primary', 'Live', '', 'LIVE'); - static $MONETIZATION = array('primary', 'Monetization', '', 'MONETIZATION'); - static $ADS = array('primary', 'ADS', '', 'ADS'); - static $STORAGE = array('primary', 'Storage', '', 'STORAGE'); - static $GALLERY = array('primary', 'Gallery', '', 'GALLERY'); - static $NETFLIX = array('primary', 'Netflix', '', 'NETFLIX'); - static $LAYOUT = array('primary', 'Layout', '', 'LAYOUT'); - static $LOGIN = array('primary', 'Login', '', 'LOGIN'); - static $MOBILE = array('primary', 'Mobile', '', 'MOBILE'); - static $PLAYER = array('primary', 'Player', '', 'PLAYER'); - static $FREE = array('info', 'Free', '', 'FREE'); - static $PREMIUM = array('info', 'Premium', '', 'PREMIUM'); - static $DEPRECATED = array('danger', 'Deprecated', '', 'DEPRECATED'); - -} +id; + } + + public function getStatus() + { + return $this->status; + } + + public function getObject_data() + { + return $this->object_data; + } + + public function getPluginVersion() + { + return $this->pluginVersion; + } + + public function getName() + { + return $this->name; + } + + public function setId($id) + { + $this->id = $id; + } + + public function setStatus($status) + { + $this->status = $status; + } + + public function setObject_data($object_data) + { + $this->object_data = $object_data; + } + + public function setName($name) + { + $name = preg_replace("/[^A-Za-z0-9 _-]/", '', $name); + $this->name = $name; + } + + public function getUuid() + { + return $this->uuid; + } + + public function getDirName() + { + return $this->dirName; + } + + public function setUuid($uuid) + { + $this->uuid = $uuid; + $this->loadFromUUID($uuid); + } + + public function setDirName($dirName) + { + $dirName = preg_replace("/[^A-Za-z0-9 _-]/", '', $dirName); + $this->dirName = $dirName; + } + + public function setPluginversion($pluginversion) + { + $this->pluginversion = $pluginversion; + } + + public static function setCurrentVersionByUuid($uuid, $currentVersion) + { + _error_log("plugin::setCurrentVersionByUuid $uuid, $currentVersion"); + $p = static::getPluginByUUID($uuid); + if (!$p) { + _error_log("plugin::setCurrentVersionByUuid error on get plugin"); + return false; + } + //pluginversion isn't an object property so we must explicity update it using this function + $sql = "update " . static::getTableName() . " set pluginversion='$currentVersion' where uuid='$uuid'"; + + $name = "plugin$uuid"; + ObjectYPT::deleteCache($name); + $res = sqlDal::writeSql($sql); + } + + public static function getCurrentVersionByUuid($uuid) + { + $p = static::getPluginByUUID($uuid); + if (!$p) { + return false; + } + //pluginversion isn't an object property so we must explicity update it using this function + $sql = "SELECT pluginversion FROM " . static::getTableName() . " WHERE uuid=? LIMIT 1 "; + $res = sqlDAL::readSql($sql, "s", [$uuid]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + return $data['pluginversion']; + } + return false; + } + + public static function getPluginByName($name) + { + global $global, $getPluginByName; + if (empty($getPluginByName)) { + $getPluginByName = []; + } + if (empty($getPluginByName[$name])) { + $sql = "SELECT * FROM " . static::getTableName() . " WHERE name = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "s", [$name], true); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + $getPluginByName[$name] = $data; + } else { + $getPluginByName[$name] = false; + } + } + return $getPluginByName[$name]; + } + + public static function getPluginByUUID($uuid) + { + global $global, $getPluginByUUID, $pluginJustInstalled; + $name = "plugin$uuid"; + if (!isset($getPluginByUUID)) { + $getPluginByUUID = []; + } + if (!isset($pluginJustInstalled)) { + $pluginJustInstalled = []; + } + if (empty($getPluginByUUID[$uuid])) { + $sql = "SELECT * FROM " . static::getTableName() . " WHERE uuid = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "s", [$uuid]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + if (empty($data['pluginversion'])) { + $data['pluginversion'] = "1.0"; + } + if (AVideoPlugin::isPluginOnByDefault($uuid)) { + $data['status'] = 'active'; + } + $getPluginByUUID[$uuid] = $data; + } else { + $name = AVideoPlugin::getPluginsNameOnByDefaultFromUUID($uuid); + if ($name !== false && empty($pluginJustInstalled[$uuid])) { + $pluginJustInstalled[$uuid] = 1; + _error_log("plugin::getPluginByUUID {$name} {$uuid} this plugin is On By Default we will install it ($sql)"); + self::deleteByUUID($uuid); + self::deleteByName($name); + unset($getPluginByUUID[$uuid]); + $getPluginByUUID[$uuid] = self::getOrCreatePluginByName($name, 'active'); + } else { + $getPluginByUUID[$uuid] = false; + } + } + } + return $getPluginByUUID[$uuid]; + } + + public function loadFromUUID($uuid) + { + $uuid = preg_replace("/[^A-Za-z0-9 _-]/", '', $uuid); + $this->uuid = $uuid; + $row = static::getPluginByUUID($uuid); + if (!empty($row)) { + $this->load($row['id']); + } + } + + public static function isEnabledByName($name) + { + $row = static::getPluginByName($name); + if ($row) { + return $row['status'] == 'active' && AVideoPlugin::isPluginTablesInstalled($name, true); + } + return false; + } + + public static function isEnabledByUUID($uuid) + { + $row = static::getPluginByUUID($uuid); + if ($row) { + return $row['status'] == 'active' && AVideoPlugin::isPluginTablesInstalled($row['name'], true); + } + return false; + } + + public static function getAvailablePlugins($comparePluginVersion = false) + { + global $global, $getAvailablePlugins; + $pluginsMarketplace = []; + if ($comparePluginVersion) { + $pluginsMarketplace = ObjectYPT::getSessionCache('getAvailablePlugins', 600); // 10 min cache + if (empty($pluginsMarketplace)) { + $pluginsMarketplace = _json_decode(url_get_contents("https://tutorials.avideo.com/info?version=1", "", 2)); + if (!empty($pluginsMarketplace)) { + ObjectYPT::setSessionCache('getAvailablePlugins', $pluginsMarketplace); + } + } + } + if (empty($getAvailablePlugins)) { + $dir = $global['systemRootPath'] . "plugin"; + $getAvailablePlugins = []; + $cdir = scandir($dir); + foreach ($cdir as $key => $value) { + if (!in_array($value, [".", ".."])) { + if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { + $p = AVideoPlugin::loadPlugin($value); + if (!is_object($p) || $p->hidePlugin()) { + if ($value !== "Statistics") { // avoid error while this plugin is not ready + _error_log("Plugin Not Found: {$value}"); + } + continue; + } + $obj = new stdClass(); + $obj->name = $p->getName(); + $obj->dir = $value; + $obj->uuid = $p->getUUID(); + $obj->description = $p->getDescription(); + $obj->installedPlugin = static::getPluginByUUID($obj->uuid); + $obj->enabled = (!empty($obj->installedPlugin['status']) && $obj->installedPlugin['status'] === "active") ? true : false; + $obj->id = (!empty($obj->installedPlugin['id'])) ? $obj->installedPlugin['id'] : 0; + $obj->data_object = $p->getDataObject(); + $obj->data_object_helper = $p->getDataObjectHelper(); + $obj->databaseScript = !empty(static::getDatabaseFile($value)); + $obj->pluginMenu = $p->getPluginMenu(); + $obj->tags = $p->getTags(); + $obj->pluginversion = $p->getPluginVersion(); + $obj->pluginversionMarketPlace = (!empty($pluginsMarketplace->plugins->{$obj->uuid}) ? $pluginsMarketplace->plugins->{$obj->uuid}->pluginversion : 0); + $obj->pluginversionCompare = (!empty($obj->pluginversionMarketPlace) ? version_compare($obj->pluginversion, $obj->pluginversionMarketPlace) : 0); + $obj->permissions = $obj->enabled ? Permissions::getPluginPermissions($obj->id) : []; + if (User::isAdmin()) { + $obj->isPluginTablesInstalled = AVideoPlugin::isPluginTablesInstalled($obj->name, false); + } + if ($obj->pluginversionCompare < 0) { + $obj->tags[] = "update"; + } + $getAvailablePlugins[] = $obj; + } + } + } + } + return $getAvailablePlugins; + } + + public static function getAvailablePluginsBasic() + { + global $global, $getAvailablePlugins; + if (empty($getAvailablePlugins)) { + $dir = $global['systemRootPath'] . "plugin"; + $getAvailablePlugins = []; + $cdir = scandir($dir); + foreach ($cdir as $key => $value) { + if (!in_array($value, [".", ".."])) { + if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { + $p = AVideoPlugin::loadPlugin($value); + if (!is_object($p) || $p->hidePlugin()) { + if ($value !== "Statistics") { // avoid error while this plugin is not ready + _error_log("Plugin Not Found: {$value}"); + } + continue; + } + $row = self::getPluginByUUID($p->getUUID()); + $obj = new stdClass(); + $obj->name = $p->getName(); + $obj->pluginversion = $p->getPluginVersion(); + $obj->status = $row['status']; + + $pinfoFile = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR . 'pinfo.json'; + if (file_exists($pinfoFile)) { + $obj->pinfo = json_decode(file_get_contents($pinfoFile)); + } else { + $obj->pinfo = false; + } + $getAvailablePlugins[$p->getUUID()] = $obj; + } + } + } + } + return $getAvailablePlugins; + } + + public static function getDatabaseFile($pluginName) + { + $filename = static::getDatabaseFileName($pluginName); + if (!$filename) { + return false; + } + return url_get_contents($filename); + } + + public static function getDatabaseFileName($pluginName) + { + global $global; + + $pluginName = AVideoPlugin::fixName($pluginName); + $dir = $global['systemRootPath'] . "plugin"; + $filename = $dir . DIRECTORY_SEPARATOR . $pluginName . DIRECTORY_SEPARATOR . "install" . DIRECTORY_SEPARATOR . "install.sql"; + if (!file_exists($filename)) { + return false; + } + return $filename; + } + + public static function getAllEnabled($try = 0) + { + global $global, $getAllEnabledRows; + if (empty($getAllEnabledRows)) { + $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='active' "; + + $defaultEnabledUUIDs = AVideoPlugin::getPluginsOnByDefault(true); + $defaultEnabledNames = AVideoPlugin::getPluginsOnByDefault(false); + $sql .= " OR uuid IN ('" . implode("','", $defaultEnabledUUIDs) . "')"; + + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $getAllEnabledRows = []; + foreach ($fullData as $row) { + $getAllEnabledRows[] = $row; + if (($key = array_search($row['uuid'], $defaultEnabledUUIDs)) !== false) { + unset($defaultEnabledUUIDs[$key], $defaultEnabledNames[$key]); + } + } + + $addedNewPlugin = false; + foreach ($defaultEnabledUUIDs as $key => $value) { + $obj = new Plugin(0); + $obj->loadFromUUID($defaultEnabledUUIDs[$key]); + $obj->setName($defaultEnabledNames[$key]); + $obj->setDirName($defaultEnabledNames[$key]); + $obj->setStatus("active"); + if ($obj->save()) { + $addedNewPlugin = true; + } + } + + if ($addedNewPlugin && empty($try)) { + //ObjectYPT::deleteALLCache(); + return self::getAllEnabled(1); + } + + uasort($getAllEnabledRows, 'cmpPlugin'); + } + return $getAllEnabledRows; + } + + public static function getAllDisabled() + { + global $global, $getAllDisabledRows; + if (empty($getAllDisabledRows)) { + $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='inactive' "; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $getAllDisabledRows = []; + foreach ($fullData as $row) { + $getAllDisabledRows[] = $row; + } + uasort($getAllDisabledRows, 'cmpPlugin'); + } + return $getAllDisabledRows; + } + + public static function getEnabled($uuid) + { + global $global, $getEnabled; + if (empty($getEnabled)) { + $getEnabled = []; + } + + if (in_array($uuid, AVideoPlugin::getPluginsOnByDefault())) { + // make sure the OnByDefault plugins are enabled + return self::getOrCreatePluginByName(AVideoPlugin::getPluginsNameOnByDefaultFromUUID($uuid)); + } + + if (empty($getEnabled[$uuid])) { + $getEnabled[$uuid] = []; + $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='active' AND uuid = '" . $uuid . "' ;"; + $res = sqlDAL::readSql($sql); + $pluginRows = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + if ($pluginRows != false) { + foreach ($pluginRows as $row) { + $getEnabled[$uuid][] = $row; + } + } + } + + return $getEnabled[$uuid]; + } + + public static function deleteByUUID($uuid) + { + global $global; + $uuid = $global['mysqli']->real_escape_string($uuid); + if (!empty($uuid)) { + _error_log("Plugin:deleteByUUID {$uuid}"); + $sql = "DELETE FROM " . static::getTableName() . " "; + $sql .= " WHERE uuid = ?"; + $global['lastQuery'] = $sql; + //_error_log("Delete Query: ".$sql); + return sqlDAL::writeSql($sql, "s", [$uuid]); + } + return false; + } + + public static function deleteByName($name) + { + global $global; + $name = $global['mysqli']->real_escape_string($name); + if (!empty($name)) { + _error_log("Plugin:deleteByName {$name}"); + $sql = "DELETE FROM " . static::getTableName() . " "; + $sql .= " WHERE name = ?"; + $global['lastQuery'] = $sql; + //_error_log("Delete Query: ".$sql); + return sqlDAL::writeSql($sql, "s", [$name]); + } + return false; + } + + public static function getOrCreatePluginByName($name, $statusIfCreate = 'inactive') + { + global $global; + if (self::getPluginByName($name) === false) { + $pluginFile = $global['systemRootPath'] . "plugin/{$name}/{$name}.php"; + if (file_exists($pluginFile)) { + require_once $pluginFile; + $code = "\$p = new {$name}();"; + eval($code); + $plugin = new Plugin(0); + $plugin->setUuid($p->getUUID()); + $plugin->setDirName($name); + $plugin->setName($name); + $plugin->setObject_data(json_encode($p->getDataObject())); + $plugin->setStatus($statusIfCreate); + $plugin->setPluginversion($p->getPluginVersion()); + $plugin->save(); + } + } + return self::getPluginByName($name); + } + + public function save() + { + if (empty($this->uuid)) { + return false; + } + global $global; + $this->object_data = $global['mysqli']->real_escape_string($this->object_data); + if (empty($this->object_data)) { + $this->object_data = 'null'; + } + self::deletePluginCache($this->uuid); + //ObjectYPT::deleteALLCache(); + return parent::save(); + } + + public static function deletePluginCache($uuid) + { + $name = "plugin{$uuid}"; + ObjectYPT::deleteCache($name); + ObjectYPT::deleteCache("plugin::getAllEnabled"); + } + + public static function encryptIfNeed($object_data) + { + $isString = false; + if (!is_object($object_data)) { + $object_data = _json_decode($object_data); + $isString = true; + } + if (!empty($object_data)) { + foreach ($object_data as $key => $value) { + if (!empty($value->type) && !empty($value->value) && is_string($value->type) && strtolower($value->type) === "encrypted") { + if (!self::isEncrypted($value->value)) { + $obj2 = new stdClass(); + $obj2->dateEncrypted = time(); + $obj2->value = $value->value; + $object_data->$key->value = encryptString($obj2); + } + } + } + if ($isString) { + $object_data = json_encode($object_data); + } + return $object_data; + } else { + return ''; + } + } + + public static function decryptIfNeed($object_data) + { + $isString = false; + if (!is_object($object_data)) { + $object_data = _json_decode($object_data); + $isString = true; + } + if (!empty($object_data)) { + foreach ($object_data as $key => $value) { + if (!empty($value->type) && !empty($value->value) && strtolower($value->type) === "encrypted") { + $isEncrypted = self::isEncrypted($value->value); + if ($isEncrypted) { + $object_data->$key->value = $isEncrypted; + } + } + } + if ($isString) { + $object_data = json_encode($object_data); + } + return $object_data; + } else { + return ''; + } + } + + public static function isEncrypted($object_data_element_value) + { + if (!empty($object_data_element_value)) { + $object_data_element_value_json = decryptString($object_data_element_value); + $object_data_element_value_json = _json_decode($object_data_element_value_json); + if (!empty($object_data_element_value_json) && !empty($object_data_element_value_json->dateEncrypted)) { + return $object_data_element_value_json->value; + } + } + return false; + } +} + +class PluginTags +{ + public static $RECOMMENDED = ['success', 'Recommended', '', 'RECOMMENDED']; + public static $SECURITY = ['warning', 'Security', '', 'SECURITY']; + public static $LIVE = ['primary', 'Live', '', 'LIVE']; + public static $MONETIZATION = ['primary', 'Monetization', '', 'MONETIZATION']; + public static $ADS = ['primary', 'ADS', '', 'ADS']; + public static $STORAGE = ['primary', 'Storage', '', 'STORAGE']; + public static $GALLERY = ['primary', 'Gallery', '', 'GALLERY']; + public static $NETFLIX = ['primary', 'Netflix', '', 'NETFLIX']; + public static $LAYOUT = ['primary', 'Layout', '', 'LAYOUT']; + public static $LOGIN = ['primary', 'Login', '', 'LOGIN']; + public static $MOBILE = ['primary', 'Mobile', '', 'MOBILE']; + public static $PLAYER = ['primary', 'Player', '', 'PLAYER']; + public static $FREE = ['info', 'Free', '', 'FREE']; + public static $PREMIUM = ['info', 'Premium', '', 'PREMIUM']; + public static $DEPRECATED = ['danger', 'Deprecated', '', 'DEPRECATED']; +} diff --git a/objects/pluginAddDataObject.json.php b/objects/pluginAddDataObject.json.php index cd643c07ea..d6342b6813 100644 --- a/objects/pluginAddDataObject.json.php +++ b/objects/pluginAddDataObject.json.php @@ -1,23 +1,22 @@ -setObject_data(addcslashes($_POST['object_data'],'\\')); - -echo '{"status":"'.$obj->save().'"}'; +setObject_data(addcslashes($_POST['object_data'], '\\')); + +echo '{"status":"'.$obj->save().'"}'; diff --git a/objects/pluginImport.json.php b/objects/pluginImport.json.php index 6206ab947f..d15edd4a39 100644 --- a/objects/pluginImport.json.php +++ b/objects/pluginImport.json.php @@ -1,44 +1,44 @@ -uploaded = false; -$obj->filename = $_FILES['input-b1']['name']; - -if (!empty($global['disableAdvancedConfigurations'])) { - die(json_encode($obj)); -} - -if (!User::isAdmin()) { - $obj->msg = "You are not admin"; - die(json_encode($obj)); -} - -$allowed = array('zip'); -$path_parts = pathinfo($_FILES['input-b1']['name']); -$extension = $path_parts['extension']; - -if (!in_array(strtolower($extension), $allowed)) { - $obj->msg = "File extension error (" . $_FILES['input-b1']['name'] . "), we allow only (" . implode(",", $global['allowed']) . ")"; - die(json_encode($obj)); -} - - -if (strcasecmp($extension, 'zip') == 0) { - //$id = File::encodeAndsaveZipFile($_FILES['input-b1']['tmp_name'], $_FILES['input-b1']['name'], $key); - $destination = "{$global['systemRootPath']}plugin/"; - $obj->destination = $destination; - $path = $_FILES['input-b1']['tmp_name']; - $dir = "{$destination}/{$path_parts['filename']}"; - if(is_dir($dir)){ - rrmdir($dir); - } - exec("unzip {$path} -d {$destination}"); -} -die(json_encode($obj)); +uploaded = false; +$obj->filename = $_FILES['input-b1']['name']; + +if (!empty($global['disableAdvancedConfigurations'])) { + die(json_encode($obj)); +} + +if (!User::isAdmin()) { + $obj->msg = "You are not admin"; + die(json_encode($obj)); +} + +$allowed = ['zip']; +$path_parts = pathinfo($_FILES['input-b1']['name']); +$extension = $path_parts['extension']; + +if (!in_array(strtolower($extension), $allowed)) { + $obj->msg = "File extension error (" . $_FILES['input-b1']['name'] . "), we allow only (" . implode(",", $global['allowed']) . ")"; + die(json_encode($obj)); +} + + +if (strcasecmp($extension, 'zip') == 0) { + //$id = File::encodeAndsaveZipFile($_FILES['input-b1']['tmp_name'], $_FILES['input-b1']['name'], $key); + $destination = "{$global['systemRootPath']}plugin/"; + $obj->destination = $destination; + $path = $_FILES['input-b1']['tmp_name']; + $dir = "{$destination}/{$path_parts['filename']}"; + if (is_dir($dir)) { + rrmdir($dir); + } + exec("unzip {$path} -d {$destination}"); +} +die(json_encode($obj)); diff --git a/objects/pluginRunDatabaseScript.json.php b/objects/pluginRunDatabaseScript.json.php index 1c344fa82d..5b14480c5a 100644 --- a/objects/pluginRunDatabaseScript.json.php +++ b/objects/pluginRunDatabaseScript.json.php @@ -1,44 +1,44 @@ -error = true; -$obj->msg = ""; -$obj->name = $_POST['name']; -$templine = ''; -$fileName = Plugin::getDatabaseFileName($_POST['name']); -$obj->fileName = $fileName; -if ($fileName) { - $lines = file($fileName); - foreach ($lines as $line) { - if (substr($line, 0, 2) == '--' || $line == '') - continue; - $templine .= $line; - if (substr(trim($line), -1, 1) == ';') { - if (!$global['mysqli']->query($templine)) { - $obj->msg = ('Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

'); - die(json_encode($obj)); - } - $templine = ''; - } - } - $obj->error = false; - $obj->msg = "All queries executed"; -} else { - $obj->msg = "File not found"; -} - -die(json_encode($obj)); +error = true; +$obj->msg = ''; +$obj->name = $_POST['name']; +$templine = ''; +$fileName = Plugin::getDatabaseFileName($_POST['name']); +$obj->fileName = $fileName; +if ($fileName) { + $lines = file($fileName); + foreach ($lines as $line) { + if (substr($line, 0, 2) == '--' || $line == '') { + continue; + } + $templine .= $line; + if (substr(trim($line), -1, 1) == ';') { + if (!$global['mysqli']->query($templine)) { + $obj->msg = ('Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

'); + die(json_encode($obj)); + } + $templine = ''; + } + } + $obj->error = false; + $obj->msg = "All queries executed"; +} else { + $obj->msg = "File not found"; +} + +die(json_encode($obj)); diff --git a/objects/pluginRunUpdateScript.json.php b/objects/pluginRunUpdateScript.json.php index cb32dc47d9..5f61320abe 100644 --- a/objects/pluginRunUpdateScript.json.php +++ b/objects/pluginRunUpdateScript.json.php @@ -1,20 +1,20 @@ -loadFromUUID($_POST['uuid']); -$obj->setName($_POST['name']); -$obj->setDirName($_POST['dir']); - -$_POST['status'] = (empty($_POST['enable']) || $_POST['enable'] === 'false') ? 'inactive' : 'active'; - -$obj->setStatus($_POST['status']); - -if(empty($obj->pluginversion)||is_null($obj->pluginversion)){ - require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; - $p=AVideoPlugin::loadPlugin($_POST['dir']); - if(is_object($p)){ - $currentVersion=$p->getPluginVersion(); - $obj->setPluginversion($currentVersion); - Plugin::setCurrentVersionByUuid($_POST['uuid'], $currentVersion); - } - -} - -echo '{"status":"'.$obj->save().'"}'; +loadFromUUID($_POST['uuid']); +$obj->setName($_POST['name']); +$obj->setDirName($_POST['dir']); + +$_POST['status'] = (empty($_POST['enable']) || $_POST['enable'] === 'false') ? 'inactive' : 'active'; + +$obj->setStatus($_POST['status']); + +if (empty($obj->pluginversion)||is_null($obj->pluginversion)) { + require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; + $p=AVideoPlugin::loadPlugin($_POST['dir']); + if (is_object($p)) { + $currentVersion=$p->getPluginVersion(); + $obj->setPluginversion($currentVersion); + Plugin::setCurrentVersionByUuid($_POST['uuid'], $currentVersion); + } +} + +echo '{"status":"'.$obj->save().'"}'; diff --git a/objects/plugins.json.php b/objects/plugins.json.php index 4c510d5d80..782881da5c 100644 --- a/objects/plugins.json.php +++ b/objects/plugins.json.php @@ -1,18 +1,18 @@ - $value) { - if(!empty($row[$key]->installedPlugin['object_data'])){ - $row[$key]->installedPlugin['object_data'] = ""; - } - } -} -$total = Plugin::getTotal(); -echo '{ "current": '.$_POST['current'].',"rowCount": '.$_POST['rowCount'].', "total": '.$total.', "rows":'. json_encode($row).'}'; + $value) { + if (!empty($row[$key]->installedPlugin['object_data'])) { + $row[$key]->installedPlugin['object_data'] = ''; + } + } +} +$total = Plugin::getTotal(); +echo '{ "current": '.$_POST['current'].',"rowCount": '.$_POST['rowCount'].', "total": '.$total.', "rows":'. json_encode($row).'}'; diff --git a/objects/pluginsAvailable.json.php b/objects/pluginsAvailable.json.php index 7861ff53d5..032d9b2e57 100644 --- a/objects/pluginsAvailable.json.php +++ b/objects/pluginsAvailable.json.php @@ -1,34 +1,34 @@ - $value) { - if(!empty($row[$key]->installedPlugin['object_data'])){ - $row[$key]->installedPlugin['object_data'] = ""; - } - } -} -$json = _json_encode($row); - -if(empty($json)){ - _error_log(print_r($row, true)); - // remove object data - foreach ($row as $key => $value) { - $row[$key]->installedPlugin['object_data'] = ""; - } - $json = _json_encode($row); -} - -echo '{ "current": 1,"rowCount": '.$total.', "total": '.$total.', "rows":'. $json.'}'; + $value) { + if (!empty($row[$key]->installedPlugin['object_data'])) { + $row[$key]->installedPlugin['object_data'] = ''; + } + } +} +$json = _json_encode($row); + +if (empty($json)) { + _error_log(print_r($row, true)); + // remove object data + foreach ($row as $key => $value) { + $row[$key]->installedPlugin['object_data'] = ''; + } + $json = _json_encode($row); +} + +echo '{ "current": 1,"rowCount": '.$total.', "total": '.$total.', "rows":'. $json.'}'; diff --git a/objects/security.php b/objects/security.php index 8fb6aa89ee..d5d134363f 100644 --- a/objects/security.php +++ b/objects/security.php @@ -2,11 +2,11 @@ require_once $global['systemRootPath'] . 'objects/functions.php'; // filter some security here -$securityFilter = array('error', 'catName', 'type', 'channelName', 'captcha', 'showOnly', 'key', 'link', 'email', 'country', 'region', 'videoName'); -$securityFilterInt = array('isAdmin', 'priority', 'totalClips', 'rowCount'); -$securityRemoveSingleQuotes = array('search', 'searchPhrase', 'videoName', 'databaseName', 'sort', 'user', 'pass', 'encodedPass', 'isAdmin', 'videoLink', 'video_password'); -$securityRemoveNonChars = array('resolution', 'format', 'videoDirectory'); -$filterURL = array('videoURL', 'siteURL', 'redirectUri', 'encoderURL'); +$securityFilter = ['error', 'catName', 'type', 'channelName', 'captcha', 'showOnly', 'key', 'link', 'email', 'country', 'region', 'videoName']; +$securityFilterInt = ['isAdmin', 'priority', 'totalClips', 'rowCount']; +$securityRemoveSingleQuotes = ['search', 'searchPhrase', 'videoName', 'databaseName', 'sort', 'user', 'pass', 'encodedPass', 'isAdmin', 'videoLink', 'video_password']; +$securityRemoveNonChars = ['resolution', 'format', 'videoDirectory']; +$filterURL = ['videoURL', 'siteURL', 'redirectUri', 'encoderURL']; if (!empty($_FILES)) { foreach ($_FILES as $key => $value) { @@ -14,7 +14,7 @@ if (!empty($_FILES)) { } } -$scanVars = array('_GET', '_POST', '_REQUEST'); +$scanVars = ['_GET', '_POST', '_REQUEST']; foreach ($scanVars as $value) { $scanThis = &$$value; @@ -30,11 +30,11 @@ foreach ($scanVars as $value) { if (!empty($scanThis['v'])) { $originalValue = $scanThis['v']; $scanThis['v'] = videosHashToID($scanThis['v']); - if(!empty($global['makeVideosIDHarderToGuessNotDecrypted']) && $originalValue != $scanThis['v']){ - // if you set $global['makeVideosIDHarderToGuessNotDecrypted'] and originalValue = scanThis['v'] it meand it was not decrypted, and it is a direct video ID, + if (!empty($global['makeVideosIDHarderToGuessNotDecrypted']) && $originalValue != $scanThis['v']) { + // if you set $global['makeVideosIDHarderToGuessNotDecrypted'] and originalValue = scanThis['v'] it meand it was not decrypted, and it is a direct video ID, // otherwiseit was a hash that we decrypt into an ID $global['makeVideosIDHarderToGuessNotDecrypted'] = 0; - } + } } foreach ($filterURL as $key => $value) { @@ -43,7 +43,7 @@ foreach ($scanVars as $value) { //_error_log($value.' attack ' . json_encode($_SERVER), AVideoLog::$SECURITY); unset($scanThis[$value]); } else { - $scanThis[$value] = str_replace(array("'", '"', "<", ">"), array("", "", "", ""), $scanThis[$value]); + $scanThis[$value] = str_replace(["'", '"', "<", ">"], ["", "", "", ""], $scanThis[$value]); } } } @@ -79,18 +79,17 @@ foreach ($scanVars as $value) { // all variables with _id at the end will be forced to be interger foreach ($scanThis as $key => $value) { if (preg_match('/_id$/i', $key)) { - if(empty($value)){ + if (empty($value)) { $scanThis[$key] = 0; - }else - if (is_numeric($value)) { + } elseif (is_numeric($value)) { $scanThis[$key] = intval($value); } else { - if(is_string($value)){ + if (is_string($value)) { $json = json_decode($value); - if(empty($json)){ + if (empty($json)) { $json = json_decode("[$value]"); } - }else{ + } else { $json = $value; } if (is_array($json)) { @@ -117,7 +116,7 @@ foreach ($scanVars as $value) { foreach ($securityFilter as $value) { if (!empty($scanThis[$value])) { - $scanThis[$value] = str_replace(array('\\', "--", "'", '"', """, "'", "%23", "%5c", "#"), array('', '', '', '', '', '', '', '', ''), xss_esc($scanThis[$value])); + $scanThis[$value] = str_replace(['\\', "--", "'", '"', """, "'", "%23", "%5c", "#"], ['', '', '', '', '', '', '', '', ''], xss_esc($scanThis[$value])); } } diff --git a/objects/sendEmail.json.php b/objects/sendEmail.json.php index 1c61b51440..01aa41b09a 100644 --- a/objects/sendEmail.json.php +++ b/objects/sendEmail.json.php @@ -1,58 +1,58 @@ -error = ""; -if ($valid) { - $msg = "Email: {$_POST['email']}

{$_POST['comment']}"; - //Create a new PHPMailer instance - $mail = new \PHPMailer\PHPMailer\PHPMailer; - setSiteSendMessage($mail); - //$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only - //var_dump($mail->SMTPAuth, $mail); - //Set who the message is to be sent from - - $replyTo = User::getEmail_(); - if (empty($replyTo)) { - $replyTo = $config->getContactEmail(); - } - - $sendTo = $_POST['email']; - - // if it is from contact form send the message to the siteowner and the sender is the email on the form field - if (!empty($_POST['contactForm'])) { - $replyTo = $_POST['email']; - $sendTo = $config->getContactEmail(); - } - - if (filter_var($sendTo, FILTER_VALIDATE_EMAIL)) { - $mail->AddReplyTo($replyTo); - $mail->setFrom($replyTo); - //Set who the message is to be sent to - $mail->addAddress($sendTo); - //Set the subject line - $mail->Subject = 'Message From Site ' . $config->getWebSiteTitle() . " ({$_POST['first_name']})"; - $mail->msgHTML($msg); - - //send the message, check for errors - if (!$mail->send()) { - $obj->error = __("Message could not be sent") . " (" . $mail->ErrorInfo.")"; - } else { - $obj->success = __("Message sent"); - } - } else { - $obj->error = __("The email is invalid"); - } -} else { - $obj->error = __("Your code is not valid"); -} -_error_log("sendEmail: ".$obj->error); -header('Content-Type: application/json'); -echo json_encode($obj); +error = ''; +if ($valid) { + $msg = "Email: {$_POST['email']}

{$_POST['comment']}"; + //Create a new PHPMailer instance + $mail = new \PHPMailer\PHPMailer\PHPMailer(); + setSiteSendMessage($mail); + //$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only + //var_dump($mail->SMTPAuth, $mail); + //Set who the message is to be sent from + + $replyTo = User::getEmail_(); + if (empty($replyTo)) { + $replyTo = $config->getContactEmail(); + } + + $sendTo = $_POST['email']; + + // if it is from contact form send the message to the siteowner and the sender is the email on the form field + if (!empty($_POST['contactForm'])) { + $replyTo = $_POST['email']; + $sendTo = $config->getContactEmail(); + } + + if (filter_var($sendTo, FILTER_VALIDATE_EMAIL)) { + $mail->AddReplyTo($replyTo); + $mail->setFrom($replyTo); + //Set who the message is to be sent to + $mail->addAddress($sendTo); + //Set the subject line + $mail->Subject = 'Message From Site ' . $config->getWebSiteTitle() . " ({$_POST['first_name']})"; + $mail->msgHTML($msg); + + //send the message, check for errors + if (!$mail->send()) { + $obj->error = __("Message could not be sent") . " (" . $mail->ErrorInfo.")"; + } else { + $obj->success = __("Message sent"); + } + } else { + $obj->error = __("The email is invalid"); + } +} else { + $obj->error = __("Your code is not valid"); +} +_error_log("sendEmail: ".$obj->error); +header('Content-Type: application/json'); +echo json_encode($obj); diff --git a/objects/sendSiteEmailAsync.php b/objects/sendSiteEmailAsync.php index ad8cd7b740..ac996e72a5 100644 --- a/objects/sendSiteEmailAsync.php +++ b/objects/sendSiteEmailAsync.php @@ -1,32 +1,31 @@ -to); -$subject = ($json->subject); -$message = ($json->message); - -sendSiteEmail($to, $subject, $message); -_error_log('sendSiteEmailAsync: Complete'); +to); +$subject = ($json->subject); +$message = ($json->message); + +sendSiteEmail($to, $subject, $message); +_error_log('sendSiteEmailAsync: Complete'); diff --git a/objects/sites.php b/objects/sites.php index 49ef0309ca..b470e571bb 100644 --- a/objects/sites.php +++ b/objects/sites.php @@ -1,97 +1,113 @@ -name; - } - - function getUrl() { - return $this->url; - } - - function getStatus() { - return $this->status; - } - - function setName($name) { - $this->name = $name; - } - - function setUrl($url) { - $this->url = $url; - } - - function setStatus($status) { - $this->status = $status; - } - - function getSecret() { - return $this->secret; - } - - function setSecret($secret) { - $this->secret = $secret; - } - - function save() { - if(empty($this->getSecret())){ - $this->setSecret(md5(uniqid())); - } - - $siteURL = $this->getUrl(); - if (substr($siteURL, -1) !== '/') { - $siteURL .= "/"; - } - $this->setUrl($siteURL); - return parent::save(); - } - - static function getFromFileName($fileName){ - $obj = new stdClass(); - $obj->url = ""; - $obj->secret = ""; - $obj->filename = $fileName; - $video = Video::getVideoFromFileNameLight($fileName); - if(!empty($video['sites_id'])){ - $site = new Sites($video['sites_id']); - $obj->url = $site->getUrl(); - $obj->secret = $site->getSecret(); - } - return $obj; - } - - static function getFromStatus($status) { - global $global; - if (!static::isTableInstalled()) { - return false; - } - $sql = "SELECT * FROM " . static::getTableName() . " WHERE status = ? "; - - $res = sqlDAL::readSql($sql, 's', array($status)); - $fullData = sqlDAL::fetchAllAssoc($res); - 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; - } - -} +name; + } + + public function getUrl() + { + return $this->url; + } + + public function getStatus() + { + return $this->status; + } + + public function setName($name) + { + $this->name = $name; + } + + public function setUrl($url) + { + $this->url = $url; + } + + public function setStatus($status) + { + $this->status = $status; + } + + public function getSecret() + { + return $this->secret; + } + + public function setSecret($secret) + { + $this->secret = $secret; + } + + public function save() + { + if (empty($this->getSecret())) { + $this->setSecret(md5(uniqid())); + } + + $siteURL = $this->getUrl(); + if (substr($siteURL, -1) !== '/') { + $siteURL .= "/"; + } + $this->setUrl($siteURL); + return parent::save(); + } + + public static function getFromFileName($fileName) + { + $obj = new stdClass(); + $obj->url = ''; + $obj->secret = ''; + $obj->filename = $fileName; + $video = Video::getVideoFromFileNameLight($fileName); + if (!empty($video['sites_id'])) { + $site = new Sites($video['sites_id']); + $obj->url = $site->getUrl(); + $obj->secret = $site->getSecret(); + } + return $obj; + } + + public static function getFromStatus($status) + { + global $global; + if (!static::isTableInstalled()) { + return false; + } + $sql = "SELECT * FROM " . static::getTableName() . " WHERE status = ? "; + + $res = sqlDAL::readSql($sql, 's', [$status]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } +} diff --git a/objects/status.json.php b/objects/status.json.php index 7be718826d..a616c37553 100644 --- a/objects/status.json.php +++ b/objects/status.json.php @@ -1,40 +1,40 @@ -max_file_size = get_max_file_size(); -$obj->file_upload_max_size = file_upload_max_size(); -$obj->videoStorageLimitMinutes = $global['videoStorageLimitMinutes']; -$obj->currentStorageUsage = getSecondsTotalVideosLength(); -$obj->webSiteLogo = $config->getLogo(true); -$obj->webSiteTitle = $config->getWebSiteTitle(); -$obj->PHPSESSID = session_id(); -$obj->version = $config->getVersion(); -$obj->mobileSreamerVersion = MobileManager::getVersion(); -$obj->reportVideoPluginEnabled = AVideoPlugin::isEnabledByName("ReportVideo"); -$obj->oauthLogin = array(); -$obj->oauthLogin[] = array('type'=>'Facebook', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginFacebook'))); -$obj->oauthLogin[] = array('type'=>'Google', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginGoogle'))); -$obj->oauthLogin[] = array('type'=>'Twitter', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginTwitter'))); -$obj->oauthLogin[] = array('type'=>'LinkedIn', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginLinkedin'))); -$obj->oauthLogin[] = array('type'=>'Apple', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginApple'))); - -$obj->plugins = array(); -$plugins = Plugin::getAllEnabled(); -foreach ($plugins as $value) { - $p = AVideoPlugin::loadPlugin($value['dirName']); - if (is_object($p)) { - $info = $p->getMobileInfo(); - if(!empty($info)){ - $obj->plugins[$value['dirName']] = $info; - } - } -} - -echo json_encode($obj); +max_file_size = get_max_file_size(); +$obj->file_upload_max_size = file_upload_max_size(); +$obj->videoStorageLimitMinutes = $global['videoStorageLimitMinutes']; +$obj->currentStorageUsage = getSecondsTotalVideosLength(); +$obj->webSiteLogo = $config->getLogo(true); +$obj->webSiteTitle = $config->getWebSiteTitle(); +$obj->PHPSESSID = session_id(); +$obj->version = $config->getVersion(); +$obj->mobileSreamerVersion = MobileManager::getVersion(); +$obj->reportVideoPluginEnabled = AVideoPlugin::isEnabledByName("ReportVideo"); +$obj->oauthLogin = []; +$obj->oauthLogin[] = ['type' => 'Facebook', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginFacebook'))]; +$obj->oauthLogin[] = ['type' => 'Google', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginGoogle'))]; +$obj->oauthLogin[] = ['type' => 'Twitter', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginTwitter'))]; +$obj->oauthLogin[] = ['type' => 'LinkedIn', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginLinkedin'))]; +$obj->oauthLogin[] = ['type' => 'Apple', 'status'=> !empty(AVideoPlugin::loadPluginIfEnabled('LoginApple'))]; + +$obj->plugins = []; +$plugins = Plugin::getAllEnabled(); +foreach ($plugins as $value) { + $p = AVideoPlugin::loadPlugin($value['dirName']); + if (is_object($p)) { + $info = $p->getMobileInfo(); + if (!empty($info)) { + $obj->plugins[$value['dirName']] = $info; + } + } +} + +echo json_encode($obj); diff --git a/objects/subscribe.json.php b/objects/subscribe.json.php index b1bc2a5604..a4e61c6b0e 100644 --- a/objects/subscribe.json.php +++ b/objects/subscribe.json.php @@ -1,44 +1,43 @@ -error = ""; -$obj->subscribe = ""; - -// gettig the mobile submited value -$inputJSON = url_get_contents('php://input'); -$input = _json_decode($inputJSON, TRUE); //convert JSON into array -unset($_POST["redirectUri"]); -if(!empty($input) && empty($_POST)){ - foreach ($input as $key => $value) { - $_POST[$key]=$value; - } -} - -// gettig the mobile submited value -if(empty($_POST) && !empty($_GET)){ - foreach ($_GET as $key => $value) { - $_POST[$key]=$value; - } -} - -if(!empty($_POST['user']) && !empty($_POST['pass'])){ - $user = new User(0, $_POST['user'], $_POST['pass']); - $user->login(false, true); -} - -if (!User::isLogged()) { - $obj->error = "Must be logged"; - die(json_encode($obj)); -} - -$_POST['email'] = User::getEmail_(); -if (empty($_POST['user_id'])) { - $obj->error = __("User can not be blank"); - die(json_encode($obj)); -} -$subscribe = new Subscribe(0, $_POST['email'], $_POST['user_id'], User::getId()); -$subscribe->toggle(); -$obj->subscribe = $subscribe->getStatus(); -die(json_encode($obj)); +error = ''; +$obj->subscribe = ''; + +// gettig the mobile submited value +$inputJSON = url_get_contents('php://input'); +$input = _json_decode($inputJSON, true); //convert JSON into array +unset($_POST["redirectUri"]); +if (!empty($input) && empty($_POST)) { + foreach ($input as $key => $value) { + $_POST[$key]=$value; + } +} + +// gettig the mobile submited value +if (empty($_POST) && !empty($_GET)) { + foreach ($_GET as $key => $value) { + $_POST[$key]=$value; + } +} + +if (!empty($_POST['user']) && !empty($_POST['pass'])) { + $user = new User(0, $_POST['user'], $_POST['pass']); + $user->login(false, true); +} + +if (!User::isLogged()) { + $obj->error = "Must be logged"; + die(json_encode($obj)); +} + +$_POST['email'] = User::getEmail_(); +if (empty($_POST['user_id'])) { + $obj->error = __("User can not be blank"); + die(json_encode($obj)); +} +$subscribe = new Subscribe(0, $_POST['email'], $_POST['user_id'], User::getId()); +$subscribe->toggle(); +$obj->subscribe = $subscribe->getStatus(); +die(json_encode($obj)); diff --git a/objects/subscribe.php b/objects/subscribe.php index c27965f55e..3b422cfdb9 100644 --- a/objects/subscribe.php +++ b/objects/subscribe.php @@ -1,404 +1,428 @@ -load($id); - } - if (!empty($subscriber_users_id)) { - $this->email = $email; - $this->users_id = $user_id; - $this->subscriber_users_id = $subscriber_users_id; - if (empty($this->id)) { - $this->loadFromId($this->subscriber_users_id, $user_id, ""); - } - } - } - - private function load($id) { - $obj = self::getSubscribe($id); - if (empty($obj)) - return false; - foreach ($obj as $key => $value) { - $this->$key = $value; - } - return true; - } - - private function loadFromEmail($email, $user_id, $status = "a") { - $obj = self::getSubscribeFromEmail($email, $user_id, $status); - if (empty($obj)) - return false; - foreach ($obj as $key => $value) { - $this->$key = $value; - } - return true; - } - - private function loadFromId($subscriber_users_id, $user_id, $status = "a") { - $obj = self::getSubscribeFromID($subscriber_users_id, $user_id, $status); - if (empty($obj)) - return false; - foreach ($obj as $key => $value) { - $this->$key = $value; - } - return true; - } - - function save() { - global $global; - if (!empty($this->id)) { - $sql = "UPDATE subscribes SET status = '{$this->status}', notify = '{$this->notify}',ip = '" . getRealIpAddr() . "', modified = now() WHERE id = {$this->id}"; - } else { - $sql = "INSERT INTO subscribes ( users_id, email,status,ip, created, modified, subscriber_users_id) VALUES ('{$this->users_id}','{$this->email}', 'a', '" . getRealIpAddr() . "',now(), now(), '$this->subscriber_users_id')"; - } - return sqlDAL::writeSql($sql); - } - - static function getSubscribe($id) { - global $global; - $id = intval($id); - $sql = "SELECT * FROM subscribes WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "i", array($id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res != false) { - $subscribe = $data; - } else { - $subscribe = false; - } - return $subscribe; - } - - static function getSubscribeFromEmail($email, $user_id, $status = "a") { - global $global; - $status = str_replace("'", "", $status); - $sql = "SELECT * FROM subscribes WHERE email = '$email' AND users_id = {$user_id} "; - if (!empty($status)) { - $sql .= " AND status = '{$status}' "; - } - $sql .= " LIMIT 1"; - $res = sqlDAL::readSql($sql); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res != false) { - $subscribe = $data; - } else { - $subscribe = false; - } - return $subscribe; - } - - static function getSubscribeFromID($subscriber_users_id, $user_id, $status = "a") { - global $global; - $status = str_replace("'", "", $status); - $sql = "SELECT * FROM subscribes WHERE subscriber_users_id = '$subscriber_users_id' AND users_id = {$user_id} "; - if (!empty($status)) { - $sql .= " AND status = '{$status}' "; - } - $sql .= " LIMIT 1"; - $res = sqlDAL::readSql($sql, "", array(), true); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if ($res != false) { - $subscribe = $data; - } else { - $subscribe = false; - } - return $subscribe; - } - - static function isSubscribed($subscribed_to_user_id, $user_id = 0) { - if (empty($user_id)) { - if (User::isLogged()) { - $user_id = User::getId(); - } else { - return false; - } - } - $s = self::getSubscribeFromID($subscribed_to_user_id, $user_id); - return !empty($s['users_id']); - } - - /** - * return all subscribers that has subscribe to an user channel - * @global type $global - * @param type $user_id - * @return boolean - */ - static function getAllSubscribes($user_id = "", $status = "a", $verifiedOnly = false) { - global $global; - $cacheName = "getAllSubscribes_{$user_id}_{$status}_" . getCurrentPage() . "_" . getRowCount(); - $subscribe = ObjectYPT::getCache($cacheName, 300); // 5 minutes - if (empty($subscribe)) { - $status = str_replace("'", "", $status); - $sql = "SELECT subscriber_users_id as subscriber_id, s.id, s.status, s.ip, s.users_id, s.notify, " - . " s.subscriber_users_id , s.created , s.modified, suId.email as email, suId.emailVerified as emailVerified FROM subscribes as s " - //. " LEFT JOIN users as su ON s.email = su.email " - . " LEFT JOIN users as suId ON suId.id = s.subscriber_users_id " - . " LEFT JOIN users as u ON users_id = u.id WHERE 1=1 AND subscriber_users_id > 0 "; - if (!empty($user_id)) { - $sql .= " AND users_id = {$user_id} "; - } - if (!empty($status)) { - $sql .= " AND u.status = '{$status}' "; - $sql .= " AND suId.status = '{$status}' "; - //$sql .= " AND su.status = '{$status}' "; - } - if (!empty($verifiedOnly)) { - $sql .= " AND suId.emailVerified = 1 "; - } - - //$sql .= " GROUP BY subscriber_id "; - - $sql .= BootGrid::getSqlFromPost(array('email')); - - - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $subscribe = array(); - if ($res != false) { - $emails = array(); - foreach ($fullData as $row) { - $row = cleanUpRowFromDatabase($row); - if (in_array($row['email'], $emails)) { - //continue; - } - $emails[] = $row['email']; - $row['identification'] = User::getNameIdentificationById($row['subscriber_id']); - if ($row['identification'] === __("Unknown User")) { - $row['identification'] = $row['email']; - } - $row['backgroundURL'] = User::getBackground($row['subscriber_id']); - $row['photoURL'] = User::getPhoto($row['subscriber_id']); - - $subscribe[] = $row; - } - //$subscribe = $res->fetch_all(MYSQLI_ASSOC); - } else { - $subscribe = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - ObjectYPT::setCache($cacheName, $subscribe); - } else { - $subscribe = object_to_array($subscribe); - } - return $subscribe; - } - - /** - * return all channels that a user has subscribed - * @global type $global - * @param type $user_id - * @return boolean - */ - static function getSubscribedChannels($user_id, $limit = 0, $page = 0) { - global $global; - $limit = intval($limit); - $page = intval($page) - 1; - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - $sql = "SELECT s.*, (SELECT MAX(v.created) FROM videos v WHERE v.users_id = s.users_id) as newestvideo " - . " FROM subscribes as s WHERE status = 'a' AND subscriber_users_id = ? " - . " ORDER BY newestvideo DESC "; - - if (!empty($limit)) { - $sql .= " LIMIT {$offset},{$limit} "; - } - //var_dump($sql, $user_id);exit; - $res = sqlDAL::readSql($sql, "i", array($user_id)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $subscribe = array(); - if ($res != false) { - foreach ($fullData as $row) { - $row['identification'] = User::getNameIdentificationById($row['users_id']); - if ($row['identification'] === __("Unknown User")) { - $row['identification'] = $row['email']; - } - $row['channelName'] = User::_getChannelName($row['users_id']); - $row['backgroundURL'] = User::getBackground($row['users_id']); - $row['photoURL'] = User::getPhoto($row['users_id']); - - $current = getCurrentPage(); - $rowCount = getRowCount(); - $sort = @$_POST['sort']; - - $_POST['current'] = 1; - $_REQUEST['rowCount'] = 6; - $_POST['sort']['created'] = "DESC"; - $row['latestVideos'] = Video::getAllVideos("viewable", $row['users_id']); - foreach ($row['latestVideos'] as $key => $video) { - $images = Video::getImageFromFilename($video['filename'], $video['type']); - $row['latestVideos'][$key]['Thumbnail'] = $images->thumbsJpg; - $row['latestVideos'][$key]['createdHumanTiming'] = humanTiming(strtotime($video['created'])); - $row['latestVideos'][$key]['pageUrl'] = Video::getLink($video['id'], $video['clean_title'], false); - $row['latestVideos'][$key]['embedUrl'] = Video::getLink($video['id'], $video['clean_title'], true); - $row['latestVideos'][$key]['UserPhoto'] = User::getPhoto($video['users_id']); - } - $_POST['current'] = $current; - $_REQUEST['rowCount'] = $rowCount; - $_POST['sort'] = $sort; - - $row['totalViewsIn30Days'] = VideoStatistic::getChannelsTotalViews($row['users_id']); - - $subscribe[] = $row; - } - //$subscribe = $res->fetch_all(MYSQLI_ASSOC); - } else { - $subscribe = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $subscribe; - } - - static function getTotalSubscribes($user_id = 0) { - global $global; - $sql = "SELECT id FROM subscribes WHERE status = 'a' AND subscriber_users_id > 0 "; - if (!empty($user_id)) { - $sql .= " AND users_id = '{$user_id}' "; - } - - $sql .= BootGrid::getSqlSearchFromPost(array('email')); - $res = sqlDAL::readSql($sql); - $numRows = sqlDAL::num_rows($res); - sqlDAL::close($res); - - $extra = User::getExtraSubscribers($user_id); - return $numRows+$extra; - } - - static function getTotalSubscribedChannels($user_id = "") { - global $global; - $sql = "SELECT id FROM subscribes WHERE status = 'a' AND subscriber_users_id = ? "; - - //$sql .= BootGrid::getSqlSearchFromPost(array('email')); - $res = sqlDAL::readSql($sql, "i", array($user_id)); - $numRows = sqlDAL::num_rows($res); - sqlDAL::close($res); - - - return $numRows; - } - - function toggle() { - if (empty($this->status) || $this->status == "i") { - $this->status = 'a'; - } else { - $this->status = 'i'; - } - $this->save(); - } - - function notifyToggle() { - if (empty($this->notify)) { - $this->notify = 1; - } else { - $this->notify = 0; - } - $this->save(); - } - - function getStatus() { - return $this->status; - } - - function getNotify() { - return $this->notify; - } - - function setNotify($notify) { - $this->notify = $notify; - } - - static function getButton($user_id) { - global $global, $advancedCustom; - - if (!empty($advancedCustom->removeSubscribeButton)) { - return ""; - } - - $total = static::getTotalSubscribes($user_id); - $btnFile = $global['systemRootPath'] . 'view/subscribeBtnOffline.html'; - - $notify = ''; - $email = ''; - $subscribed = ''; - $subscribeText = __("Subscribe"); - $subscribedText = __("Subscribed"); - if (User::isLogged()) { - $btnFile = $global['systemRootPath'] . 'view/subscribeBtn.html'; - $email = User::getMail(); - $subs = Subscribe::getSubscribeFromID(User::getId(), $user_id); - if (!empty($subs['notify'])) { - $notify = 'notify'; - } - - if (!empty($subs) && $subs['status'] === 'a') { - $subscribed = 'subscribed'; - } - } - $content = local_get_contents($btnFile); - - $signInBTN = ("".__("Sign in to subscribe to this channel").""); - - $search = array( - '_user_id_', - '{notify}', - '{tooltipStop}', - '{tooltip}', - '{titleOffline}', - '{tooltipOffline}', - '{email}', '{total}', - '{subscribed}', '{subscribeText}', '{subscribedText}'); - - $replace = array( - $user_id, - $notify, - __("Stop getting notified for every new video"), - __("Click to get notified for every new video"), - __("Want to subscribe to this channel?"), - $signInBTN, - $email, $total, - $subscribed, $subscribeText, $subscribedText); - - $btnHTML = str_replace($search, $replace, $content); - return $btnHTML; - } - - function getSubscriber_users_id() { - return $this->subscriber_users_id; - } - - function setSubscriber_users_id($subscriber_users_id) { - $this->subscriber_users_id = $subscriber_users_id; - } - - function getUsers_id() { - return $this->users_id; - } - - function setUsers_id($users_id) { - $this->users_id = $users_id; - } - -} +load($id); + } + if (!empty($subscriber_users_id)) { + $this->email = $email; + $this->users_id = $user_id; + $this->subscriber_users_id = $subscriber_users_id; + if (empty($this->id)) { + $this->loadFromId($this->subscriber_users_id, $user_id, ""); + } + } + } + + private function load($id) + { + $obj = self::getSubscribe($id); + if (empty($obj)) { + return false; + } + foreach ($obj as $key => $value) { + $this->$key = $value; + } + return true; + } + + private function loadFromEmail($email, $user_id, $status = "a") + { + $obj = self::getSubscribeFromEmail($email, $user_id, $status); + if (empty($obj)) { + return false; + } + foreach ($obj as $key => $value) { + $this->$key = $value; + } + return true; + } + + private function loadFromId($subscriber_users_id, $user_id, $status = "a") + { + $obj = self::getSubscribeFromID($subscriber_users_id, $user_id, $status); + if (empty($obj)) { + return false; + } + foreach ($obj as $key => $value) { + $this->$key = $value; + } + return true; + } + + public function save() + { + global $global; + if (!empty($this->id)) { + $sql = "UPDATE subscribes SET status = '{$this->status}', notify = '{$this->notify}',ip = '" . getRealIpAddr() . "', modified = now() WHERE id = {$this->id}"; + } else { + $sql = "INSERT INTO subscribes ( users_id, email,status,ip, created, modified, subscriber_users_id) VALUES ('{$this->users_id}','{$this->email}', 'a', '" . getRealIpAddr() . "',now(), now(), '$this->subscriber_users_id')"; + } + return sqlDAL::writeSql($sql); + } + + public static function getSubscribe($id) + { + global $global; + $id = intval($id); + $sql = "SELECT * FROM subscribes WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res != false) { + $subscribe = $data; + } else { + $subscribe = false; + } + return $subscribe; + } + + public static function getSubscribeFromEmail($email, $user_id, $status = "a") + { + global $global; + $status = str_replace("'", "", $status); + $sql = "SELECT * FROM subscribes WHERE email = '$email' AND users_id = {$user_id} "; + if (!empty($status)) { + $sql .= " AND status = '{$status}' "; + } + $sql .= " LIMIT 1"; + $res = sqlDAL::readSql($sql); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res != false) { + $subscribe = $data; + } else { + $subscribe = false; + } + return $subscribe; + } + + public static function getSubscribeFromID($subscriber_users_id, $user_id, $status = "a") + { + global $global; + $status = str_replace("'", "", $status); + $sql = "SELECT * FROM subscribes WHERE subscriber_users_id = '$subscriber_users_id' AND users_id = {$user_id} "; + if (!empty($status)) { + $sql .= " AND status = '{$status}' "; + } + $sql .= " LIMIT 1"; + $res = sqlDAL::readSql($sql, "", [], true); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if ($res != false) { + $subscribe = $data; + } else { + $subscribe = false; + } + return $subscribe; + } + + public static function isSubscribed($subscribed_to_user_id, $user_id = 0) + { + if (empty($user_id)) { + if (User::isLogged()) { + $user_id = User::getId(); + } else { + return false; + } + } + $s = self::getSubscribeFromID($subscribed_to_user_id, $user_id); + return !empty($s['users_id']); + } + + /** + * return all subscribers that has subscribe to an user channel + * @global type $global + * @param type $user_id + * @return boolean + */ + public static function getAllSubscribes($user_id = "", $status = "a", $verifiedOnly = false) + { + global $global; + $cacheName = "getAllSubscribes_{$user_id}_{$status}_" . getCurrentPage() . "_" . getRowCount(); + $subscribe = ObjectYPT::getCache($cacheName, 300); // 5 minutes + if (empty($subscribe)) { + $status = str_replace("'", "", $status); + $sql = "SELECT subscriber_users_id as subscriber_id, s.id, s.status, s.ip, s.users_id, s.notify, " + . " s.subscriber_users_id , s.created , s.modified, suId.email as email, suId.emailVerified as emailVerified FROM subscribes as s " + //. " LEFT JOIN users as su ON s.email = su.email " + . " LEFT JOIN users as suId ON suId.id = s.subscriber_users_id " + . " LEFT JOIN users as u ON users_id = u.id WHERE 1=1 AND subscriber_users_id > 0 "; + if (!empty($user_id)) { + $sql .= " AND users_id = {$user_id} "; + } + if (!empty($status)) { + $sql .= " AND u.status = '{$status}' "; + $sql .= " AND suId.status = '{$status}' "; + //$sql .= " AND su.status = '{$status}' "; + } + if (!empty($verifiedOnly)) { + $sql .= " AND suId.emailVerified = 1 "; + } + + //$sql .= " GROUP BY subscriber_id "; + + $sql .= BootGrid::getSqlFromPost(['email']); + + + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $subscribe = []; + if ($res != false) { + $emails = []; + foreach ($fullData as $row) { + $row = cleanUpRowFromDatabase($row); + if (in_array($row['email'], $emails)) { + //continue; + } + $emails[] = $row['email']; + $row['identification'] = User::getNameIdentificationById($row['subscriber_id']); + if ($row['identification'] === __("Unknown User")) { + $row['identification'] = $row['email']; + } + $row['backgroundURL'] = User::getBackground($row['subscriber_id']); + $row['photoURL'] = User::getPhoto($row['subscriber_id']); + + $subscribe[] = $row; + } + //$subscribe = $res->fetch_all(MYSQLI_ASSOC); + } else { + $subscribe = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + ObjectYPT::setCache($cacheName, $subscribe); + } else { + $subscribe = object_to_array($subscribe); + } + return $subscribe; + } + + /** + * return all channels that a user has subscribed + * @global type $global + * @param type $user_id + * @return boolean + */ + public static function getSubscribedChannels($user_id, $limit = 0, $page = 0) + { + global $global; + $limit = intval($limit); + $page = intval($page) - 1; + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + $sql = "SELECT s.*, (SELECT MAX(v.created) FROM videos v WHERE v.users_id = s.users_id) as newestvideo " + . " FROM subscribes as s WHERE status = 'a' AND subscriber_users_id = ? " + . " ORDER BY newestvideo DESC "; + + if (!empty($limit)) { + $sql .= " LIMIT {$offset},{$limit} "; + } + //var_dump($sql, $user_id);exit; + $res = sqlDAL::readSql($sql, "i", [$user_id]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $subscribe = []; + if ($res != false) { + foreach ($fullData as $row) { + $row['identification'] = User::getNameIdentificationById($row['users_id']); + if ($row['identification'] === __("Unknown User")) { + $row['identification'] = $row['email']; + } + $row['channelName'] = User::_getChannelName($row['users_id']); + $row['backgroundURL'] = User::getBackground($row['users_id']); + $row['photoURL'] = User::getPhoto($row['users_id']); + + $current = getCurrentPage(); + $rowCount = getRowCount(); + $sort = @$_POST['sort']; + + $_POST['current'] = 1; + $_REQUEST['rowCount'] = 6; + $_POST['sort']['created'] = "DESC"; + $row['latestVideos'] = Video::getAllVideos("viewable", $row['users_id']); + foreach ($row['latestVideos'] as $key => $video) { + $images = Video::getImageFromFilename($video['filename'], $video['type']); + $row['latestVideos'][$key]['Thumbnail'] = $images->thumbsJpg; + $row['latestVideos'][$key]['createdHumanTiming'] = humanTiming(strtotime($video['created'])); + $row['latestVideos'][$key]['pageUrl'] = Video::getLink($video['id'], $video['clean_title'], false); + $row['latestVideos'][$key]['embedUrl'] = Video::getLink($video['id'], $video['clean_title'], true); + $row['latestVideos'][$key]['UserPhoto'] = User::getPhoto($video['users_id']); + } + $_POST['current'] = $current; + $_REQUEST['rowCount'] = $rowCount; + $_POST['sort'] = $sort; + + $row['totalViewsIn30Days'] = VideoStatistic::getChannelsTotalViews($row['users_id']); + + $subscribe[] = $row; + } + //$subscribe = $res->fetch_all(MYSQLI_ASSOC); + } else { + $subscribe = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $subscribe; + } + + public static function getTotalSubscribes($user_id = 0) + { + global $global; + $sql = "SELECT id FROM subscribes WHERE status = 'a' AND subscriber_users_id > 0 "; + if (!empty($user_id)) { + $sql .= " AND users_id = '{$user_id}' "; + } + + $sql .= BootGrid::getSqlSearchFromPost(['email']); + $res = sqlDAL::readSql($sql); + $numRows = sqlDAL::num_rows($res); + sqlDAL::close($res); + + $extra = User::getExtraSubscribers($user_id); + return $numRows+$extra; + } + + public static function getTotalSubscribedChannels($user_id = "") + { + global $global; + $sql = "SELECT id FROM subscribes WHERE status = 'a' AND subscriber_users_id = ? "; + + //$sql .= BootGrid::getSqlSearchFromPost(array('email')); + $res = sqlDAL::readSql($sql, "i", [$user_id]); + $numRows = sqlDAL::num_rows($res); + sqlDAL::close($res); + + + return $numRows; + } + + public function toggle() + { + if (empty($this->status) || $this->status == "i") { + $this->status = 'a'; + } else { + $this->status = 'i'; + } + $this->save(); + } + + public function notifyToggle() + { + if (empty($this->notify)) { + $this->notify = 1; + } else { + $this->notify = 0; + } + $this->save(); + } + + public function getStatus() + { + return $this->status; + } + + public function getNotify() + { + return $this->notify; + } + + public function setNotify($notify) + { + $this->notify = $notify; + } + + public static function getButton($user_id) + { + global $global, $advancedCustom; + + if (!empty($advancedCustom->removeSubscribeButton)) { + return ""; + } + + $total = static::getTotalSubscribes($user_id); + $btnFile = $global['systemRootPath'] . 'view/subscribeBtnOffline.html'; + + $notify = ''; + $email = ''; + $subscribed = ''; + $subscribeText = __("Subscribe"); + $subscribedText = __("Subscribed"); + if (User::isLogged()) { + $btnFile = $global['systemRootPath'] . 'view/subscribeBtn.html'; + $email = User::getMail(); + $subs = Subscribe::getSubscribeFromID(User::getId(), $user_id); + if (!empty($subs['notify'])) { + $notify = 'notify'; + } + + if (!empty($subs) && $subs['status'] === 'a') { + $subscribed = 'subscribed'; + } + } + $content = local_get_contents($btnFile); + + $signInBTN = ("".__("Sign in to subscribe to this channel").""); + + $search = [ + '_user_id_', + '{notify}', + '{tooltipStop}', + '{tooltip}', + '{titleOffline}', + '{tooltipOffline}', + '{email}', '{total}', + '{subscribed}', '{subscribeText}', '{subscribedText}', ]; + + $replace = [ + $user_id, + $notify, + __("Stop getting notified for every new video"), + __("Click to get notified for every new video"), + __("Want to subscribe to this channel?"), + $signInBTN, + $email, $total, + $subscribed, $subscribeText, $subscribedText, ]; + + $btnHTML = str_replace($search, $replace, $content); + return $btnHTML; + } + + public function getSubscriber_users_id() + { + return $this->subscriber_users_id; + } + + public function setSubscriber_users_id($subscriber_users_id) + { + $this->subscriber_users_id = $subscriber_users_id; + } + + public function getUsers_id() + { + return $this->users_id; + } + + public function setUsers_id($users_id) + { + $this->users_id = $users_id; + } +} diff --git a/objects/subscribeNotify.json.php b/objects/subscribeNotify.json.php index 68263903c8..ea8fa67af9 100644 --- a/objects/subscribeNotify.json.php +++ b/objects/subscribeNotify.json.php @@ -1,26 +1,26 @@ - $value) { - $_POST[$key]=$value; - } -} -require_once 'subscribe.php'; -header('Content-Type: application/json'); -$obj = new stdClass(); -$obj->error = ""; -$obj->subscribe = ""; -if (!User::isLogged()) { - $obj->error = "Must be logged"; - die(json_encode($obj)); -} - -$_POST['email'] = User::getEmail_(); -if (empty($_POST['user_id'])) { - $obj->error = __("User can not be blank"); - die(json_encode($obj)); -} -$subscribe = new Subscribe(0, $_POST['email'], $_POST['user_id'], User::getId()); -$subscribe->notifyToggle(); -$obj->notify = $subscribe->getNotify(); -die(json_encode($obj)); + $value) { + $_POST[$key]=$value; + } +} +require_once 'subscribe.php'; +header('Content-Type: application/json'); +$obj = new stdClass(); +$obj->error = ''; +$obj->subscribe = ''; +if (!User::isLogged()) { + $obj->error = "Must be logged"; + die(json_encode($obj)); +} + +$_POST['email'] = User::getEmail_(); +if (empty($_POST['user_id'])) { + $obj->error = __("User can not be blank"); + die(json_encode($obj)); +} +$subscribe = new Subscribe(0, $_POST['email'], $_POST['user_id'], User::getId()); +$subscribe->notifyToggle(); +$obj->notify = $subscribe->getNotify(); +die(json_encode($obj)); diff --git a/objects/subscribed.json.php b/objects/subscribed.json.php index 8b5adda245..7aec14f670 100644 --- a/objects/subscribed.json.php +++ b/objects/subscribed.json.php @@ -1,20 +1,20 @@ -login(false, true); -} -if (!User::isLogged()) { - return false; -} -header('Content-Type: application/json'); - -$user_id = User::getId(); - -$Subscribes = Subscribe::getSubscribedChannels($user_id); -$total = Subscribe::getTotalSubscribedChannels($user_id); -echo '{ "current": '. getCurrentPage().',"rowCount": '.getRowCount().', "total": '.$total.', "rows":'. json_encode($Subscribes).'}'; +login(false, true); +} +if (!User::isLogged()) { + return false; +} +header('Content-Type: application/json'); + +$user_id = User::getId(); + +$Subscribes = Subscribe::getSubscribedChannels($user_id); +$total = Subscribe::getTotalSubscribedChannels($user_id); +echo '{ "current": '. getCurrentPage().',"rowCount": '.getRowCount().', "total": '.$total.', "rows":'. json_encode($Subscribes).'}'; diff --git a/objects/subscribes.json.php b/objects/subscribes.json.php index 0c658393df..96f2593b26 100644 --- a/objects/subscribes.json.php +++ b/objects/subscribes.json.php @@ -1,23 +1,23 @@ -login(false, true); -} -if (!User::isLogged()) { - return false; -} -header('Content-Type: application/json'); - -$user_id = User::getId(); -// if admin bring all subscribers -if (User::isAdmin()) { - $user_id = ""; -} -$Subscribes = Subscribe::getAllSubscribes($user_id); -$total = Subscribe::getTotalSubscribes($user_id); -echo '{ "current": '. getCurrentPage().',"rowCount": '.getRowCount().', "total": '.$total.', "rows":'. json_encode($Subscribes).'}'; +login(false, true); +} +if (!User::isLogged()) { + return false; +} +header('Content-Type: application/json'); + +$user_id = User::getId(); +// if admin bring all subscribers +if (User::isAdmin()) { + $user_id = ''; +} +$Subscribes = Subscribe::getAllSubscribes($user_id); +$total = Subscribe::getTotalSubscribes($user_id); +echo '{ "current": '. getCurrentPage().',"rowCount": '.getRowCount().', "total": '.$total.', "rows":'. json_encode($Subscribes).'}'; diff --git a/objects/uploadArticleImage.php b/objects/uploadArticleImage.php index 72053486a6..42f1a6bc70 100644 --- a/objects/uploadArticleImage.php +++ b/objects/uploadArticleImage.php @@ -1,51 +1,50 @@ -error = true; -if (!Video::canEdit($_GET['video_id'])) { - $obj->msg = 'You can\'t edit this file'; - die(json_encode($obj)); -} -header('Content-Type: application/json'); -// A list of permitted file extensions -$allowed = array('jpg', 'gif', 'png'); -if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { - $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); - if (!in_array(strtolower($extension), $allowed)) { - $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; - die(json_encode($obj)); - } - //var_dump($extension, $type);exit; - $video = new Video("", "", $_GET['video_id']); - if (!empty($video)) { - $dir = Video::getStoragePath()."articleImages/" . $video->getFilename()."/"; - $name = uniqid(); - if(!is_dir($dir)){ - mkdir($dir, 0777, true); - } - $destination = $dir . $name.".".strtolower($extension); - _error_log("Try to move " . $destination . " \n " . print_r($video, true)); - if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $destination)) { - $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . $destination; - die(json_encode($obj)); - } - $obj->url = "{$global['webSiteRootURL']}videos/articleImages/" . $video->getFilename()."/{$name}.".strtolower($extension); - $obj->error = false; - } else { - $obj->msg = "Video Not found"; - die(json_encode($obj)); - } -} -$obj->msg = "\$_FILES Error"; -$obj->FILES = $_FILES; -die(json_encode($obj)); +error = true; +if (!Video::canEdit($_GET['video_id'])) { + $obj->msg = 'You can\'t edit this file'; + die(json_encode($obj)); +} +header('Content-Type: application/json'); +// A list of permitted file extensions +$allowed = ['jpg', 'gif', 'png']; +if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { + $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); + if (!in_array(strtolower($extension), $allowed)) { + $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; + die(json_encode($obj)); + } + //var_dump($extension, $type);exit; + $video = new Video("", "", $_GET['video_id']); + if (!empty($video)) { + $dir = Video::getStoragePath()."articleImages/" . $video->getFilename()."/"; + $name = uniqid(); + if (!is_dir($dir)) { + mkdir($dir, 0777, true); + } + $destination = $dir . $name.".".strtolower($extension); + _error_log("Try to move " . $destination . " \n " . print_r($video, true)); + if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $destination)) { + $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . $destination; + die(json_encode($obj)); + } + $obj->url = "{$global['webSiteRootURL']}videos/articleImages/" . $video->getFilename()."/{$name}.".strtolower($extension); + $obj->error = false; + } else { + $obj->msg = "Video Not found"; + die(json_encode($obj)); + } +} +$obj->msg = "\$_FILES Error"; +$obj->FILES = $_FILES; +die(json_encode($obj)); diff --git a/objects/uploadChannelArt.php b/objects/uploadChannelArt.php index 7310084afa..f666570c98 100644 --- a/objects/uploadChannelArt.php +++ b/objects/uploadChannelArt.php @@ -1,48 +1,47 @@ -error = true; -if (!User::isLogged()) { - $obj->msg = 'You can\'t edit this file'; - die(json_encode($obj)); -} -header('Content-Type: application/json'); -// A list of permitted file extensions -$allowed = array('jpg', 'jpeg', 'gif', 'png'); -if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { - $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); - if (!in_array(strtolower($extension), $allowed)) { - $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; - die(json_encode($obj)); - } - - $tmpDestination = Video::getStoragePath()."userPhoto/tmp_background".User::getId().".". $extension; - $obj->file = "videos/userPhoto/background".User::getId().".jpg"; - $oldfile = Video::getStoragePath()."userPhoto/background".User::getId().".png"; - - if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $tmpDestination)) { - $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . Video::getStoragePath()."" . $filename . $ext; - die(json_encode($obj)); - } - convertImage($tmpDestination, $global['systemRootPath'].$obj->file, 70); - unlink($tmpDestination); - if(file_exists($oldfile)){ - unlink($oldfile); - } - - echo "{}"; - exit; -} -$obj->msg = "\$_FILES Error"; -$obj->FILES = $_FILES; -die(json_encode($obj)); +error = true; +if (!User::isLogged()) { + $obj->msg = 'You can\'t edit this file'; + die(json_encode($obj)); +} +header('Content-Type: application/json'); +// A list of permitted file extensions +$allowed = ['jpg', 'jpeg', 'gif', 'png']; +if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { + $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); + if (!in_array(strtolower($extension), $allowed)) { + $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; + die(json_encode($obj)); + } + + $tmpDestination = Video::getStoragePath()."userPhoto/tmp_background".User::getId().".". $extension; + $obj->file = "videos/userPhoto/background".User::getId().".jpg"; + $oldfile = Video::getStoragePath()."userPhoto/background".User::getId().".png"; + + if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $tmpDestination)) { + $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . Video::getStoragePath()."" . $filename . $ext; + die(json_encode($obj)); + } + convertImage($tmpDestination, $global['systemRootPath'].$obj->file, 70); + unlink($tmpDestination); + if (file_exists($oldfile)) { + unlink($oldfile); + } + + echo "{}"; + exit; +} +$obj->msg = "\$_FILES Error"; +$obj->FILES = $_FILES; +die(json_encode($obj)); diff --git a/objects/uploadPoster.php b/objects/uploadPoster.php index 7e3e372513..3cb58371bd 100644 --- a/objects/uploadPoster.php +++ b/objects/uploadPoster.php @@ -1,93 +1,92 @@ -error = true; -if (!Video::canEdit($_GET['video_id'])) { - $obj->msg = 'You can\'t edit this file'; - die(json_encode($obj)); -} -$obj->videos_id = intval($_GET['video_id']); - -header('Content-Type: application/json'); -// A list of permitted file extensions -$allowed = array('jpg', 'jpeg', 'gif', 'pjpg', 'pgif', 'webp', 'png', 'bmp'); -if (!in_array(strtolower($_GET['type']), $allowed)) { - $obj->msg = "UploadPoster FIle extension not allowed"; - _error_log($obj->msg ); - die(json_encode($obj)); -} -if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { - $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); - if (!in_array(strtolower($extension), $allowed)) { - $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; - die(json_encode($obj)); - } - //var_dump($extension, $type);exit; - $video = new Video("", "", $_GET['video_id']); - if (!empty($video)) { - $ext = ".jpg"; - switch ($_GET['type']) { - case "jpg": - case "jpeg": - $ext = ".jpg"; - if($extension == 'png' || $extension == 'bmp'){ - $ext = "_convertToJPG.{$extension}"; - } - break; - case "pjpg": - $ext = "_portrait.jpg"; - if($extension == 'png' || $extension == 'bmp'){ - $ext = "_portrait_convertToJPG.{$extension}"; - } - break; - case "gif": - $ext = ".gif"; - break; - case "webp": - $ext = ".webp"; - break; - case "pgif": - $ext = "_portrait.gif"; - break; - } - /** - * This is when is using in a non file_dataoaded movie - */ - $paths = Video::getPaths($video->getFilename()); - $destination = $paths['path'] . $video->getFilename() . $ext; - _error_log("Try to move " . $destination . " \n " . print_r($video, true)); - if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $destination)) { - $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . $destination; - die(json_encode($obj)); - } else { - if(preg_match('/_convertToJPG/', $ext)){ - $new_destination = str_replace('_convertToJPG.'.$extension, '.jpg', $destination); - if(convertImage($destination, $new_destination, 100)){ - unlink($destination); - } - } - // delete thumbs from poster - Video::deleteThumbs($video->getFilename()); - } - $obj->clearFirstPageCache = clearFirstPageCache(); - $obj->error = false; - echo "{}"; - exit; - } else { - $obj->msg = "Video Not found"; - die(json_encode($obj)); - } -} -$obj->msg = "\$_FILES Error"; -$obj->FILES = $_FILES; -die(json_encode($obj)); +error = true; +if (!Video::canEdit($_GET['video_id'])) { + $obj->msg = 'You can\'t edit this file'; + die(json_encode($obj)); +} +$obj->videos_id = intval($_GET['video_id']); + +header('Content-Type: application/json'); +// A list of permitted file extensions +$allowed = ['jpg', 'jpeg', 'gif', 'pjpg', 'pgif', 'webp', 'png', 'bmp']; +if (!in_array(strtolower($_GET['type']), $allowed)) { + $obj->msg = "UploadPoster FIle extension not allowed"; + _error_log($obj->msg); + die(json_encode($obj)); +} +if (isset($_FILES['file_data']) && $_FILES['file_data']['error'] == 0) { + $extension = pathinfo($_FILES['file_data']['name'], PATHINFO_EXTENSION); + if (!in_array(strtolower($extension), $allowed)) { + $obj->msg = "File extension error [{$_FILES['file_data']['name']}], we allow only (" . implode(",", $allowed) . ")"; + die(json_encode($obj)); + } + //var_dump($extension, $type);exit; + $video = new Video("", "", $_GET['video_id']); + if (!empty($video)) { + $ext = ".jpg"; + switch ($_GET['type']) { + case "jpg": + case "jpeg": + $ext = ".jpg"; + if ($extension == 'png' || $extension == 'bmp') { + $ext = "_convertToJPG.{$extension}"; + } + break; + case "pjpg": + $ext = "_portrait.jpg"; + if ($extension == 'png' || $extension == 'bmp') { + $ext = "_portrait_convertToJPG.{$extension}"; + } + break; + case "gif": + $ext = ".gif"; + break; + case "webp": + $ext = ".webp"; + break; + case "pgif": + $ext = "_portrait.gif"; + break; + } + /** + * This is when is using in a non file_dataoaded movie + */ + $paths = Video::getPaths($video->getFilename()); + $destination = $paths['path'] . $video->getFilename() . $ext; + _error_log("Try to move " . $destination . " \n " . print_r($video, true)); + if (!move_uploaded_file($_FILES['file_data']['tmp_name'], $destination)) { + $obj->msg = "Error on move_file_uploaded_file(" . $_FILES['file_data']['tmp_name'] . ", " . $destination; + die(json_encode($obj)); + } else { + if (preg_match('/_convertToJPG/', $ext)) { + $new_destination = str_replace('_convertToJPG.'.$extension, '.jpg', $destination); + if (convertImage($destination, $new_destination, 100)) { + unlink($destination); + } + } + // delete thumbs from poster + Video::deleteThumbs($video->getFilename()); + } + $obj->clearFirstPageCache = clearFirstPageCache(); + $obj->error = false; + echo "{}"; + exit; + } else { + $obj->msg = "Video Not found"; + die(json_encode($obj)); + } +} +$obj->msg = "\$_FILES Error"; +$obj->FILES = $_FILES; +die(json_encode($obj)); diff --git a/objects/user.php b/objects/user.php index 67a94d0173..abb32967d8 100644 --- a/objects/user.php +++ b/objects/user.php @@ -1,2550 +1,2714 @@ -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 = strip_specific_tags(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)); - //var_dump($this->externalOptions, $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(DEBUG_BACKTRACE_IGNORE_ARGS))); - 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 = getURL($photo); - } else { - $photo = ""; - } - } - if (empty($photo)) { - $photo = getURL("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 don't have analytics code - return false; - } - if (empty($this->user) || empty($this->password)) { - //echo "u:" . $this->user . "|p:" . strlen($this->password); - if (empty($this->user)) { - //echo "u:" . $this->user . "|p:" . strlen($this->password); - _error_log('Error : 1 ' . __("You need a user and passsword to register")); - return false; - } - if (empty($this->password)) { - //echo "u:" . $this->user . "|p:" . strlen($this->password); - _error_log('Error : 2 ' . __("You need a user and passsword to register")); - return false; - } - - 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, 60); - } - if (empty($cache)) { - $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 - $pluginCanWatch = AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id); - if (!$pluginCanWatch) { - 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 (empty($advancedCustom)) { - $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); - } - if (empty($advancedCustom)) { - $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); - } - - 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($checkForRequestLogin=false) { - self::recreateLoginFromCookie(); - $isLogged = !empty($_SESSION['user']['id']); - if(empty($isLogged) && $checkForRequestLogin){ - self::loginFromRequest(); - return !empty($_SESSION['user']['id']); - }else{ - return $isLogged; - } - } - - public static function isVerified() { - self::recreateLoginFromCookie(); - return !empty($_SESSION['user']['emailVerified']); - } - - public static function isAdmin($users_id = 0) { - if (!empty($users_id)) { - $user = new User($users_id); - return !empty($user->getIsAdmin()); - } - - 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 function getExternalOptions($id) { - if (empty($this->id)) { - return null; - } - return self::externalOptionsFromUserID($this->id, $id); - } - - public static function externalOptionsFromUserID($users_id, $id) { - $user = self::findById($users_id); - if ($user) { - if (!is_null($user['externalOptions'])) { - $externalOptions = unserialize(base64_decode($user['externalOptions'])); - if (is_array($externalOptions) && sizeof($externalOptions) > 0) { - //var_dump($externalOptions); - 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 (trim($user) !== $user) { - $formats .= "s"; - $values[] = trim($user); - $sql .= " OR 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'], $user['recoverPass']); - if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) { - unset( - $user['first_name'], - $user['last_name'], - $user['address'], - $user['zip_code'], - $user['country'], - $user['region'], - $user['city'] - ); - } - 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), true); - $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 "; - - $queryIds = array(); - if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'permanent') { - $queryIds[] = " id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; - } - if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'dynamic') { - $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); - if (!empty($ids) && is_array($ids)) { - $ids = array_unique($ids); - $queryIds[] = " id IN ('" . implode("','", $ids) . "') "; - } - } - if (!empty($queryIds)) { - $sql .= " AND ( "; - $sql .= implode(' OR ', $queryIds); - $sql .= " ) "; - }else{ - // do not return nothing - $sql .= " AND u.id < 0 "; - } - - 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'; - //echo $sql;exit; - $res = sqlDAL::readSql($sql . ";"); - $downloadedArray = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($downloadedArray as $row) { - $row['creator'] = Video::getCreatorHTML($row['id'], '', true, true); - $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 "; - - $queryIds = array(); - if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'permanent') { - $queryIds[] = " id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; - } - if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'dynamic') { - $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); - if (!empty($ids) && is_array($ids)) { - $ids = array_unique($ids); - $queryIds[] = " id IN ('" . implode("','", $ids) . "') "; - } - } - if (!empty($queryIds)) { - $sql .= " AND ( "; - $sql .= implode(' OR ', $queryIds); - $sql .= " ) "; - }else{ - // do not return nothing - $sql .= " AND u.id < 0 "; - } - - 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 = "", $isAdmin = null) { - 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' "; - } - } - if (isset($isAdmin)) { - if (empty($isAdmin)) { - $sql .= " AND isAdmin = 0 "; - } else { - $sql .= " AND isAdmin = 1 "; - } - } - $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['creator'] = Video::getCreatorHTML($row['id'], '', true, true); - $row = self::getUserInfoFromRow($row); - $row = cleanUpRowFromDatabase($row); - $user[] = $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'], $row['recoverPass']); - if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) { - unset( - $row['first_name'], - $row['last_name'], - $row['address'], - $row['zip_code'], - $row['country'], - $row['region'], - $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 = "", $isAdmin = null) { - 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' "; - } - } - if (isset($isAdmin)) { - if (empty($isAdmin)) { - $sql .= " AND isAdmin = 0 "; - } else { - $sql .= " AND isAdmin = 1 "; - } - } - $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 = (!empty($value['isDynamic']) ? '' : '') . ' ' . $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']; - } - - $response = false; - if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { - $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); - $response = $user->login(false, !empty($_REQUEST['encodedPass'])); - if ($response !== self::USER_LOGGED) { - //_error_log("loginFromRequest trying again"); - $response = $user->login(false, empty($_REQUEST['encodedPass'])); - } - if ($response) { - - switch ($response) { - case self::USER_LOGGED: - _error_log("loginFromRequest SUCCESS {$_REQUEST['user']}"); - break; - case self::USER_NOT_FOUND: - _error_log("loginFromRequest NOT FOUND {$_REQUEST['user']}"); - break; - case self::USER_NOT_VERIFIED: - _error_log("loginFromRequest NOT VERIFIED {$_REQUEST['user']}"); - break; - case self::CAPTCHA_ERROR: - _error_log("loginFromRequest CAPTCHA_ERROR {$_REQUEST['user']}"); - break; - case self::REQUIRE2FA: - _error_log("loginFromRequest REQUIRE2FA {$_REQUEST['user']}"); - break; - default: - _error_log("loginFromRequest UNDEFINED {$_REQUEST['user']}"); - break; - } - } else { - //_error_log("loginFromRequest ERROR {$_REQUEST['user']}"); - } - $_REQUEST['do_not_login'] = 1; - } - return $response; - } - - 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; - } - - static function getExtraSubscribers($users_id) { - global $config; - $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); - if (empty($obj)) { - return 0; - } - $user = new User($users_id); - $value = $user->getExternalOptions('ExtraSubscribers'); - return intval($value); - } - - static function setExtraSubscribers($users_id, $value) { - $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); - if (empty($obj) || !User::isAdmin()) { - return false; - } - $user = new User($users_id); - return $user->addExternalOptions('ExtraSubscribers', intval($value)); - } - - static function getProfilePassword($users_id) { - global $config; - $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); - if (empty($obj)) { - return false; - } - $user = new User($users_id); - $value = $user->getExternalOptions('ProfilePassword'); - return $value; - } - - static function setProfilePassword($users_id, $value) { - $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); - if (empty($obj) || !User::isAdmin()) { - return false; - } - $user = new User($users_id); - return $user->addExternalOptions('ProfilePassword', preg_replace('/[^0-9a-z]/i', '', $value)); - } - -} +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(['\\\\\\\n'], ["\n"], $this->about); + } + + public function setAbout($about) + { + $this->about = strip_specific_tags(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 = []; + } + $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)); + //var_dump($this->externalOptions, $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(DEBUG_BACKTRACE_IGNORE_ARGS))); + 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", [$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 = getURL($photo); + } else { + $photo = ''; + } + } + if (empty($photo)) { + $photo = getURL("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 don't have analytics code + return false; + } + if (empty($this->user) || empty($this->password)) { + //echo "u:" . $this->user . "|p:" . strlen($this->password); + if (empty($this->user)) { + //echo "u:" . $this->user . "|p:" . strlen($this->password); + _error_log('Error : 1 ' . __("You need a user and passsword to register")); + return false; + } + if (empty($this->password)) { + //echo "u:" . $this->user . "|p:" . strlen($this->password); + _error_log('Error : 2 ' . __("You need a user and passsword to register")); + return false; + } + + 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 = [$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 = [$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", [$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", [$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, 60); + } + if (empty($cache)) { + $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 + $pluginCanWatch = AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id); + if (!$pluginCanWatch) { + 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", [$this->id]); + } + + public const USER_LOGGED = 0; + public const USER_NOT_VERIFIED = 1; + public const USER_NOT_FOUND = 2; + public const CAPTCHA_ERROR = 3; + public const REQUIRE2FA = 4; + + public function login($noPass = false, $encodedPass = false, $ignoreEmailVerification = false) + { + if (User::isLogged()) { + return false; + } + global $global, $advancedCustom, $advancedCustomUser, $config; + + if (empty($advancedCustom)) { + $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); + } + if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); + } + + 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", [$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($checkForRequestLogin=false) + { + self::recreateLoginFromCookie(); + $isLogged = !empty($_SESSION['user']['id']); + if (empty($isLogged) && $checkForRequestLogin) { + self::loginFromRequest(); + return !empty($_SESSION['user']['id']); + } else { + return $isLogged; + } + } + + public static function isVerified() + { + self::recreateLoginFromCookie(); + return !empty($_SESSION['user']['emailVerified']); + } + + public static function isAdmin($users_id = 0) + { + if (!empty($users_id)) { + $user = new User($users_id); + return !empty($user->getIsAdmin()); + } + + 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 function getExternalOptions($id) + { + if (empty($this->id)) { + return null; + } + return self::externalOptionsFromUserID($this->id, $id); + } + + public static function externalOptionsFromUserID($users_id, $id) + { + $user = self::findById($users_id); + if ($user) { + if (!is_null($user['externalOptions'])) { + $externalOptions = unserialize(base64_decode($user['externalOptions'])); + if (is_array($externalOptions) && sizeof($externalOptions) > 0) { + //var_dump($externalOptions); + 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 = []; + $sql = "SELECT * FROM users WHERE user = ? "; + + $formats .= "s"; + $values[] = $user; + + if (trim($user) !== $user) { + $formats .= "s"; + $values[] = trim($user); + $sql .= " OR 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 = []; + $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", [$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", [$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", [$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", [$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", [$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'], $user['recoverPass']); + if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) { + unset( + $user['first_name'], + $user['last_name'], + $user['address'], + $user['zip_code'], + $user['country'], + $user['region'], + $user['city'] + ); + } + 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", [$email], true); + $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 = ['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 "; + + $queryIds = []; + if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'permanent') { + $queryIds[] = " id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; + } + if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'dynamic') { + $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); + if (!empty($ids) && is_array($ids)) { + $ids = array_unique($ids); + $queryIds[] = " id IN ('" . implode("','", $ids) . "') "; + } + } + if (!empty($queryIds)) { + $sql .= " AND ( "; + $sql .= implode(' OR ', $queryIds); + $sql .= " ) "; + } else { + // do not return nothing + $sql .= " AND u.id < 0 "; + } + + if (!empty($status)) { + if (strtolower($status) === 'i') { + $sql .= " AND u.status = 'i' "; + } else { + $sql .= " AND u.status = 'a' "; + } + } + + $sql .= BootGrid::getSqlFromPost($searchFields); + + $user = []; + require_once $global['systemRootPath'] . 'objects/userGroups.php'; + //echo $sql;exit; + $res = sqlDAL::readSql($sql . ";"); + $downloadedArray = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + if ($res != false) { + foreach ($downloadedArray as $row) { + $row['creator'] = Video::getCreatorHTML($row['id'], '', true, true); + $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 "; + + $queryIds = []; + if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'permanent') { + $queryIds[] = " id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; + } + if (empty($_REQUEST['userGroupShowOnly']) || $_REQUEST['userGroupShowOnly'] == 'dynamic') { + $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); + if (!empty($ids) && is_array($ids)) { + $ids = array_unique($ids); + $queryIds[] = " id IN ('" . implode("','", $ids) . "') "; + } + } + if (!empty($queryIds)) { + $sql .= " AND ( "; + $sql .= implode(' OR ', $queryIds); + $sql .= " ) "; + } else { + // do not return nothing + $sql .= " AND u.id < 0 "; + } + + if (!empty($status)) { + if (strtolower($status) === 'i') { + $sql .= " AND status = 'i' "; + } else { + $sql .= " AND status = 'a' "; + } + } + $sql .= BootGrid::getSqlSearchFromPost(['name', 'email', 'user']); + + $res = sqlDAL::readSql($sql); + $result = sqlDal::num_rows($res); + sqlDAL::close($res); + + + return $result; + } + + public static function getAllUsers($ignoreAdmin = false, $searchFields = ['name', 'email', 'user', 'channelName', 'about'], $status = "", $isAdmin = null) + { + 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' "; + } + } + if (isset($isAdmin)) { + if (empty($isAdmin)) { + $sql .= " AND isAdmin = 0 "; + } else { + $sql .= " AND isAdmin = 1 "; + } + } + $sql .= BootGrid::getSqlFromPost($searchFields); + + $user = []; + 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['creator'] = Video::getCreatorHTML($row['id'], '', true, true); + $row = self::getUserInfoFromRow($row); + $row = cleanUpRowFromDatabase($row); + $user[] = $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 = []; + $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'], $row['recoverPass']); + if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) { + unset( + $row['first_name'], + $row['last_name'], + $row['address'], + $row['zip_code'], + $row['country'], + $row['region'], + $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 = []; + $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 = "", $isAdmin = null) + { + 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' "; + } + } + if (isset($isAdmin)) { + if (empty($isAdmin)) { + $sql .= " AND isAdmin = 0 "; + } else { + $sql .= " AND isAdmin = 1 "; + } + } + $sql .= BootGrid::getSqlSearchFromPost(['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", [$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", [$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, [$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)); + } + + public function checkRecoverPass($recoverPass) + { + if ($this->recoverPass === $recoverPass) { + if (!$this->isRecoverPassExpired($recoverPass)) { + _error_log('checkRecoverPass success: ' . $this->user . ' ' . getRealIpAddr()); + return true; + } + } + return false; + } + + public 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 = []; + 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 = (!empty($value['isDynamic']) ? '' : '') . ' ' . $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", [$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", [$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']; + } + + $response = false; + if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { + $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); + $response = $user->login(false, !empty($_REQUEST['encodedPass'])); + if ($response !== self::USER_LOGGED) { + //_error_log("loginFromRequest trying again"); + $response = $user->login(false, empty($_REQUEST['encodedPass'])); + } + if ($response) { + switch ($response) { + case self::USER_LOGGED: + _error_log("loginFromRequest SUCCESS {$_REQUEST['user']}"); + break; + case self::USER_NOT_FOUND: + _error_log("loginFromRequest NOT FOUND {$_REQUEST['user']}"); + break; + case self::USER_NOT_VERIFIED: + _error_log("loginFromRequest NOT VERIFIED {$_REQUEST['user']}"); + break; + case self::CAPTCHA_ERROR: + _error_log("loginFromRequest CAPTCHA_ERROR {$_REQUEST['user']}"); + break; + case self::REQUIRE2FA: + _error_log("loginFromRequest REQUIRE2FA {$_REQUEST['user']}"); + break; + default: + _error_log("loginFromRequest UNDEFINED {$_REQUEST['user']}"); + break; + } + } else { + //_error_log("loginFromRequest ERROR {$_REQUEST['user']}"); + } + $_REQUEST['do_not_login'] = 1; + } + return $response; + } + + 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 = []) + { + $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 = ['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; + } + + public function getExtra_info() + { + return $this->extra_info; + } + + public function setExtra_info($extra_info) + { + $this->extra_info = $extra_info; + } + + public static function saveExtraInfo($string, $users_id) + { + $sql = "UPDATE users SET " + . "extra_info = ?, " + . " modified = now() WHERE id = ?"; + + return sqlDAL::writeSql($sql, "si", [$string, $users_id]); + } + + public 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 = [$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; + } + + public static function getExtraSubscribers($users_id) + { + global $config; + $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); + if (empty($obj)) { + return 0; + } + $user = new User($users_id); + $value = $user->getExternalOptions('ExtraSubscribers'); + return intval($value); + } + + public static function setExtraSubscribers($users_id, $value) + { + $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); + if (empty($obj) || !User::isAdmin()) { + return false; + } + $user = new User($users_id); + return $user->addExternalOptions('ExtraSubscribers', intval($value)); + } + + public static function getProfilePassword($users_id) + { + global $config; + $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); + if (empty($obj)) { + return false; + } + $user = new User($users_id); + $value = $user->getExternalOptions('ProfilePassword'); + return $value; + } + + public static function setProfilePassword($users_id, $value) + { + $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); + if (empty($obj) || !User::isAdmin()) { + return false; + } + $user = new User($users_id); + return $user->addExternalOptions('ProfilePassword', preg_replace('/[^0-9a-z]/i', '', $value)); + } +} diff --git a/objects/userAddNew.json.php b/objects/userAddNew.json.php index 9aa1f44668..7f2bb278c2 100644 --- a/objects/userAddNew.json.php +++ b/objects/userAddNew.json.php @@ -1,75 +1,75 @@ -forceLoginToBeTheEmail)) { - $_POST['email'] = $_POST['user']; -} - -if (empty($_POST['id'])) { - _error_log("userAddNew.json.php: Adding a user"); -} else { - _error_log("userAddNew.json.php: Editing a user id = {$_POST['id']}"); -} - -$user = new User(@$_POST['id']); -$user->setUser($_POST['user']); -$user->setPassword($_POST['pass']); -$user->setEmail($_POST['email']); -$user->setName($_POST['name']); -$user->setIsAdmin($_POST['isAdmin']); -$user->setCanStream($_POST['canStream']); -$user->setCanUpload($_POST['canUpload']); -$user->setCanViewChart($_POST['canViewChart']); -$user->setCanCreateMeet($_POST['canCreateMeet']); -$user->setStatus($_POST['status']); -$user->setEmailVerified($_POST['isEmailVerified']); -$user->setAnalyticsCode($_POST['analyticsCode']); - -_error_log("userAddNew.json.php: set channel name = ({$_POST['channelName']})"); - -if(empty($_POST['channelName'])){ - $_POST['channelName'] = $_POST['user']; -} - -$unique = $user->setChannelName($_POST['channelName']); - -//identify what variables come from external plugins -$userOptions=AVideoPlugin::getPluginUserOptions(); -if (is_array($userOptions)) { - $externalOptions=array(); - foreach ($userOptions as $uo => $id) { - if (isset($_POST[$id])) { - $externalOptions[$id]=$_POST[$id]; - } - } - $user->setExternalOptions($externalOptions); -} -//save it - -if (!empty($_POST['channelName']) && !$unique) { - _error_log("userAddNew.json.php: channel name already exits = ({$_POST['channelName']})"); - $user->setChannelName(User::_recommendChannelName($_POST['channelName'])); - _error_log("userAddNew.json.php: new channel name: ".$user->getChannelName()); -} - -if (empty($_POST['userGroups'])) { - if (empty($_POST['id']) && !empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup - $user->setUserGroups(array($advancedCustomUser->userDefaultUserGroup->value)); - } -} else { - $user->setUserGroups($_POST['userGroups']); -} - -_error_log("userAddNew.json.php: saving"); -$users_id = $user->save(true); -echo '{"status":"'.$users_id.'"}'; -_error_log("userAddNew.json.php: saved users_id ($users_id)"); +forceLoginToBeTheEmail)) { + $_POST['email'] = $_POST['user']; +} + +if (empty($_POST['id'])) { + _error_log("userAddNew.json.php: Adding a user"); +} else { + _error_log("userAddNew.json.php: Editing a user id = {$_POST['id']}"); +} + +$user = new User(@$_POST['id']); +$user->setUser($_POST['user']); +$user->setPassword($_POST['pass']); +$user->setEmail($_POST['email']); +$user->setName($_POST['name']); +$user->setIsAdmin($_POST['isAdmin']); +$user->setCanStream($_POST['canStream']); +$user->setCanUpload($_POST['canUpload']); +$user->setCanViewChart($_POST['canViewChart']); +$user->setCanCreateMeet($_POST['canCreateMeet']); +$user->setStatus($_POST['status']); +$user->setEmailVerified($_POST['isEmailVerified']); +$user->setAnalyticsCode($_POST['analyticsCode']); + +_error_log("userAddNew.json.php: set channel name = ({$_POST['channelName']})"); + +if (empty($_POST['channelName'])) { + $_POST['channelName'] = $_POST['user']; +} + +$unique = $user->setChannelName($_POST['channelName']); + +//identify what variables come from external plugins +$userOptions=AVideoPlugin::getPluginUserOptions(); +if (is_array($userOptions)) { + $externalOptions=[]; + foreach ($userOptions as $uo => $id) { + if (isset($_POST[$id])) { + $externalOptions[$id]=$_POST[$id]; + } + } + $user->setExternalOptions($externalOptions); +} +//save it + +if (!empty($_POST['channelName']) && !$unique) { + _error_log("userAddNew.json.php: channel name already exits = ({$_POST['channelName']})"); + $user->setChannelName(User::_recommendChannelName($_POST['channelName'])); + _error_log("userAddNew.json.php: new channel name: ".$user->getChannelName()); +} + +if (empty($_POST['userGroups'])) { + if (empty($_POST['id']) && !empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup + $user->setUserGroups([$advancedCustomUser->userDefaultUserGroup->value]); + } +} else { + $user->setUserGroups($_POST['userGroups']); +} + +_error_log("userAddNew.json.php: saving"); +$users_id = $user->save(true); +echo '{"status":"'.$users_id.'"}'; +_error_log("userAddNew.json.php: saved users_id ($users_id)"); diff --git a/objects/userCreate.json.php b/objects/userCreate.json.php index bf67b02fa7..b875c107af 100644 --- a/objects/userCreate.json.php +++ b/objects/userCreate.json.php @@ -1,91 +1,90 @@ - $value) { - $_POST[$key] = $value; - } -} -$obj = new stdClass(); -if (empty($ignoreCaptcha)) { - if (empty($_POST['captcha'])) { - $obj->error = __("The captcha is empty"); - die(json_encode($obj)); - } - require_once $global['systemRootPath'] . 'objects/captcha.php'; - $valid = Captcha::validation($_POST['captcha']); - if (!$valid) { - $obj->error = __("The captcha is wrong"); - die(json_encode($obj)); - } -} -// check if user already exists -$userCheck = new User(0, $_POST['user'], false); - -if (!empty($userCheck->getBdId())) { - $obj->error = __("User already exists"); - die(json_encode($obj)); -} - -if (!empty($advancedCustomUser->forceLoginToBeTheEmail)) { - $_POST['email'] = $_POST['user']; -} -$_POST['email'] = trim(@$_POST['email']); -if (!empty($advancedCustomUser->emailMustBeUnique)) { - if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { - $obj->error = __("You must specify a valid email")." {$_POST['email']} (create)"; - die(json_encode($obj)); - } - $userFromEmail = User::getUserFromEmail($_POST['email']); - if (!empty($userFromEmail)) { - $obj->error = __("Email already exists"); - die(json_encode($obj)); - } -} - -if (empty($_POST['user']) || empty($_POST['pass']) || empty($_POST['email']) || empty($_POST['name'])) { - $obj->error = __("You must fill all fields"); - die(json_encode($obj)); -} - -if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { - $obj->error = __("Invalid Email"); - die(json_encode($obj)); -} - -$user = new User(0); -$user->setUser($_POST['user']); -$user->setPassword($_POST['pass']); -$user->setEmail($_POST['email']); -$user->setName($_POST['name']); - -$user->setCanUpload($config->getAuthCanUploadVideos()); - -$users_id = $user->save(); - -if (!empty($users_id)) { - $cu = AVideoPlugin::loadPluginIfEnabled('CustomizeUser'); - if (!empty($cu)) { - CustomizeUser::setCanShareVideosFromUser($users_id, true); - } - if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup - UserGroups::updateUserGroups($users_id, array($advancedCustomUser->userDefaultUserGroup->value), true); - } - AVideoPlugin::onUserSignup($users_id); -} - -echo '{"status":"' . $users_id . '"}'; + $value) { + $_POST[$key] = $value; + } +} +$obj = new stdClass(); +if (empty($ignoreCaptcha)) { + if (empty($_POST['captcha'])) { + $obj->error = __("The captcha is empty"); + die(json_encode($obj)); + } + require_once $global['systemRootPath'] . 'objects/captcha.php'; + $valid = Captcha::validation($_POST['captcha']); + if (!$valid) { + $obj->error = __("The captcha is wrong"); + die(json_encode($obj)); + } +} +// check if user already exists +$userCheck = new User(0, $_POST['user'], false); + +if (!empty($userCheck->getBdId())) { + $obj->error = __("User already exists"); + die(json_encode($obj)); +} + +if (!empty($advancedCustomUser->forceLoginToBeTheEmail)) { + $_POST['email'] = $_POST['user']; +} +$_POST['email'] = trim(@$_POST['email']); +if (!empty($advancedCustomUser->emailMustBeUnique)) { + if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { + $obj->error = __("You must specify a valid email")." {$_POST['email']} (create)"; + die(json_encode($obj)); + } + $userFromEmail = User::getUserFromEmail($_POST['email']); + if (!empty($userFromEmail)) { + $obj->error = __("Email already exists"); + die(json_encode($obj)); + } +} + +if (empty($_POST['user']) || empty($_POST['pass']) || empty($_POST['email']) || empty($_POST['name'])) { + $obj->error = __("You must fill all fields"); + die(json_encode($obj)); +} + +if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { + $obj->error = __("Invalid Email"); + die(json_encode($obj)); +} + +$user = new User(0); +$user->setUser($_POST['user']); +$user->setPassword($_POST['pass']); +$user->setEmail($_POST['email']); +$user->setName($_POST['name']); + +$user->setCanUpload($config->getAuthCanUploadVideos()); + +$users_id = $user->save(); + +if (!empty($users_id)) { + $cu = AVideoPlugin::loadPluginIfEnabled('CustomizeUser'); + if (!empty($cu)) { + CustomizeUser::setCanShareVideosFromUser($users_id, true); + } + if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup + UserGroups::updateUserGroups($users_id, [$advancedCustomUser->userDefaultUserGroup->value], true); + } + AVideoPlugin::onUserSignup($users_id); +} + +echo '{"status":"' . $users_id . '"}'; diff --git a/objects/userDelete.json.php b/objects/userDelete.json.php index e7d618e661..2c6fb47ca4 100644 --- a/objects/userDelete.json.php +++ b/objects/userDelete.json.php @@ -1,13 +1,13 @@ -delete().'"}'; +delete().'"}'; diff --git a/objects/userDocument.png.php b/objects/userDocument.png.php index bdddc94271..692d26b574 100644 --- a/objects/userDocument.png.php +++ b/objects/userDocument.png.php @@ -1,20 +1,20 @@ -userCanManageVideo()) { - $obj->msg = __("You can not Manage This Video"); - die(json_encode($obj)); - } - if(!empty($_POST['add'])){ - UserGroups::addVideoGroups($videos_id, $_POST['users_groups_id']); - }else{ - UserGroups::deleteVideoGroups($videos_id, $_POST['users_groups_id']); - } - $resp = true; -} -echo '{"status":"' . !empty($resp) . '"}'; +userCanManageVideo()) { + $obj->msg = __("You can not Manage This Video"); + die(json_encode($obj)); + } + if (!empty($_POST['add'])) { + UserGroups::addVideoGroups($videos_id, $_POST['users_groups_id']); + } else { + UserGroups::deleteVideoGroups($videos_id, $_POST['users_groups_id']); + } + $resp = true; +} +echo '{"status":"' . !empty($resp) . '"}'; diff --git a/objects/userGroups.php b/objects/userGroups.php index 59adcb6e3f..ed8ee50402 100644 --- a/objects/userGroups.php +++ b/objects/userGroups.php @@ -1,441 +1,463 @@ -group_name = $group_name; - } else { - // get data from id - $this->load($id); - } - } - - private function load($id) { - $user = self::getUserGroupsDb($id); - if (empty($user)) - return false; - foreach ($user as $key => $value) { - $this->$key = $value; - } - } - - static private function getUserGroupsDb($id) { - global $global; - $id = intval($id); - $sql = "SELECT * FROM users_groups WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "i", array($id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - $user = $data; - } else { - $user = false; - } - return $user; - } - - function save() { - global $global; - if (empty($this->isAdmin)) { - $this->isAdmin = "false"; - } - $formats = ""; - $values = array(); - $this->group_name = _substr($this->group_name, 0, 255); - if (!empty($this->id)) { - $sql = "UPDATE users_groups SET group_name = ?, modified = now() WHERE id = ?"; - $formats = "si"; - $values = array($this->group_name,$this->id); - } else { - $sql = "INSERT INTO users_groups ( group_name, created, modified) VALUES (?,now(), now())"; - $formats = "s"; - $values = array($this->group_name); - } - if(sqlDAL::writeSql($sql,$formats,$values)){ - if (empty($this->id)) { - $id = $global['mysqli']->insert_id; - } else { - $id = $this->id; - } - return $id; - } else { - return false; - } - } - - function delete() { - if (!User::isAdmin()) { - return false; - } - - global $global; - if (!empty($this->id)) { - $sql = "DELETE FROM users_groups WHERE id = ?"; - } else { - return false; - } - return sqlDAL::writeSql($sql,"i",array($this->id)); - } - - private function getUserGroup($id) { - global $global; - $id = intval($id); - $sql = "SELECT * FROM users_groups WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "i", array($id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - $category = $data; - } else { - $category = false; - } - return $category; - } - - static function getAllUsersGroups() { - global $global; - $sql = "SELECT *," - . " (SELECT COUNT(*) FROM videos_group_view WHERE users_groups_id = ug.id ) as total_videos, " - . " (SELECT COUNT(*) FROM users_has_users_groups WHERE users_groups_id = ug.id ) as total_users " - . " FROM users_groups as ug WHERE 1=1 "; - - $sql .= BootGrid::getSqlFromPost(array('group_name')); - - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $arr = array(); - if ($res!=false) { - foreach ($fullData as $row) { - $arr[] = $row; - } - //$category = $res->fetch_all(MYSQLI_ASSOC); - } else { - $arr = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $arr; - } - - static function getAllUsersGroupsArray() { - global $global; - $sql = "SELECT * FROM users_groups as ug WHERE 1=1 "; - - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $arr = array(); - if ($res!=false) { - foreach ($fullData as $row) { - $arr[$row['id']] = $row['group_name']; - } - //$category = $res->fetch_all(MYSQLI_ASSOC); - } else { - $arr = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $arr; - } - - static function getTotalUsersGroups() { - global $global; - $sql = "SELECT id FROM users_groups WHERE 1=1 "; - - $sql .= BootGrid::getSqlSearchFromPost(array('group_name')); - $res = sqlDAL::readSql($sql); - $numRows = sqlDAL::num_rows($res); - sqlDAL::close($res); - return $numRows; - } - - function getGroup_name() { - return $this->group_name; - } - - function setGroup_name($group_name) { - $this->group_name = $group_name; - } - - static function getUserGroupByName($group_name, $refreshCache = false) { - global $global; - $sql = "SELECT * FROM users_groups WHERE group_name = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "s", array($group_name),$refreshCache); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - $category = $data; - } else { - $category = false; - } - return $category; - } - - static function getOrCreateUserGroups($group_name){ - $group_name = trim($group_name); - $group_name = _substr($group_name, 0, 255); - if(empty($group_name)){ - return false; - } - $group = self::getUserGroupByName($group_name, true); - if(empty($group)){ - $g = new UserGroups(0, $group_name); - return $g->save(); - }else{ - return $group['id']; - } - } - - // for users - - static function updateUserGroups($users_id, $array_groups_id, $byPassAdmin=false, $mergeWithCurrentUserGroups=false){ - if (!$byPassAdmin && !Permissions::canAdminUsers()) { - return false; - } - if (!is_array($array_groups_id)) { - return false; - } - if(empty($users_id)){ - return false; - } - - if($mergeWithCurrentUserGroups){ - $current_user_groups = self::getUserGroups($users_id); - foreach ($current_user_groups as $value) { - if(!in_array($value['id'], $array_groups_id)){ - $array_groups_id[] = $value['id']; - } - } - } - - self::deleteGroupsFromUser($users_id, true); - global $global; - $array_groups_id = array_unique($array_groups_id); - $sql = "INSERT INTO users_has_users_groups ( users_id, users_groups_id) VALUES (?,?)"; - foreach ($array_groups_id as $value) { - $value = intval($value); - if(empty($value)){ - continue; - } - sqlDAL::writeSql($sql,"ii",array($users_id,$value)); - } - - // make sure you do not save the dynamic user groups - $user_groups_ids = AVideoPlugin::getDynamicUserGroupsId($users_id); - if(!empty($user_groups_ids) && is_array($user_groups_ids)){ - $sql = "DELETE FROM users_has_users_groups WHERE users_id = ? AND users_groups_id IN (". implode(',', $user_groups_ids).") "; - return sqlDAL::writeSql($sql,"i",array($users_id)); - } - - return true; - } - - static function getAlUserGroupsFromUser($users_id) { - return self::getUserGroups($users_id); - } - - static function getUserGroups($users_id) { - global $global; - $res = sqlDAL::readSql("SHOW TABLES LIKE 'users_has_users_groups'"); - $result = sqlDAL::num_rows($res); - sqlDAL::close($res); - if (empty($result)) { - $_GET['error'] = "You need to update your system to ver 2.3"; - return array(); - } - if (empty($users_id)) { - return array(); - } - $sql = "SELECT uug.*, ug.* FROM users_groups ug" - . " LEFT JOIN users_has_users_groups uug ON users_groups_id = ug.id WHERE users_id = ? "; - - $ids = AVideoPlugin::getDynamicUserGroupsId($users_id); - if(!empty($ids) && is_array($ids)){ - $ids = array_unique($ids); - $sql .= " OR ug.id IN ('". implode("','", $ids)."') "; - } - //var_dump($ids);echo $sql;exit; - $res = sqlDAL::readSql($sql,"i",array($users_id)); - $fullData = sqlDal::fetchAllAssoc($res); - sqlDAL::close($res); - $arr = array(); - $doNotRepeat = array(); - if ($res!=false) { - foreach ($fullData as $row) { - if(in_array($row['id'], $doNotRepeat)){ - continue; - } - if(in_array($row['id'], $ids)){ - $row['isDynamic'] = 1; - }else{ - $row['isDynamic'] = 0; - } - $row = cleanUpRowFromDatabase($row); - $doNotRepeat[] = $row['id']; - $arr[] = $row; - } - } else { - $arr = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $arr; - } - - static private function deleteGroupsFromUser($users_id, $byPassAdmin=false){ - if (!$byPassAdmin && !User::isAdmin()) { - return false; - } - - global $global; - if (!empty($users_id)) { - $sql = "DELETE FROM users_has_users_groups WHERE users_id = ?"; - } else { - return false; - } - return sqlDAL::writeSql($sql,"i",array($users_id)); - } - - static function getVideoGroupsViewId($videos_id, $users_groups_id) { - if(empty($videos_id)){ - return false; - } - if(empty($users_groups_id)){ - return false; - } - global $global; - - $sql = "SELECT id FROM videos_group_view WHERE videos_id = ? AND users_groups_id = ? LIMIT 1 "; - $res = sqlDAL::readSql($sql,"ii",array($videos_id, $users_groups_id)); - $data = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($data)) { - return $data['id']; - } else { - return 0; - } - - } - - static function addVideoGroups($videos_id, $users_groups_id) { - if (!User::canUpload()) { - return false; - } - global $global; - - if(self::getVideoGroupsViewId($videos_id, $users_groups_id)){ - return false; - } - - $sql = "INSERT INTO videos_group_view ( videos_id, users_groups_id) VALUES (?,?)"; - $value = intval($value); - $response = sqlDAL::writeSql($sql,"ii",array($videos_id,$users_groups_id)); - - if($response){ - Video::clearCache($videos_id); - } - return $response; - } - - static function deleteVideoGroups($videos_id, $users_groups_id) { - if (!User::canUpload()) { - return false; - } - - $sql = "DELETE FROM videos_group_view WHERE videos_id = ? AND users_groups_id = ?"; - $response = sqlDAL::writeSql($sql,"ii",array($videos_id, $users_groups_id)); - - if($response){ - Video::clearCache($videos_id); - } - return $response; - } - - static function updateVideoGroups($videos_id, $array_groups_id, $mergeWithCurrentUserGroups=false) { - if (!User::canUpload()) { - return false; - } - if (!is_array($array_groups_id)) { - return false; - } - - if($mergeWithCurrentUserGroups){ - $current_user_groups = self::getVideoGroups($videos_id); - foreach ($current_user_groups as $value) { - if(!in_array($value['id'], $array_groups_id)){ - $array_groups_id[] = $value['id']; - } - } - } - - self::deleteGroupsFromVideo($videos_id); - global $global; - - $sql = "INSERT INTO videos_group_view ( videos_id, users_groups_id) VALUES (?,?)"; - foreach ($array_groups_id as $value) { - $value = intval($value); - sqlDAL::writeSql($sql,"ii",array($videos_id,$value)); - } - - return true; - } - - static function getVideoGroups($videos_id) { - if(empty($videos_id)){ - return array(); - } - global $global; - //check if table exists if not you need to update - $sql = "SELECT 1 FROM `videos_group_view` LIMIT 1"; - $res = sqlDAL::readSql($sql); - sqlDAL::close($res); - if (!$res) { - if (User::isAdmin()) { - $_GET['error'] = "You need to Update AVideo to version 2.3 Click here"; - } - return array(); - } - - $sql = "SELECT v.*, ug.*FROM videos_group_view as v " - . " LEFT JOIN users_groups as ug ON users_groups_id = ug.id WHERE videos_id = ? "; - $res = sqlDAL::readSql($sql,"i",array($videos_id)); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $arr = array(); - if ($res!=false) { - foreach ($fullData as $row) { - $row = cleanUpRowFromDatabase($row); - $arr[] = $row; - } - } else { - $arr = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $arr; - } - - static private function deleteGroupsFromVideo($videos_id){ - if (!User::canUpload()) { - return false; - } - - global $global; - if (!empty($videos_id)) { - $sql = "DELETE FROM videos_group_view WHERE videos_id = ?"; - } else { - return false; - } - return sqlDAL::writeSql($sql,"i",array($videos_id)); - } - -} +group_name = $group_name; + } else { + // get data from id + $this->load($id); + } + } + + private function load($id) + { + $user = self::getUserGroupsDb($id); + if (empty($user)) { + return false; + } + foreach ($user as $key => $value) { + $this->$key = $value; + } + } + + private static function getUserGroupsDb($id) + { + global $global; + $id = intval($id); + $sql = "SELECT * FROM users_groups WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + $user = $data; + } else { + $user = false; + } + return $user; + } + + public function save() + { + global $global; + if (empty($this->isAdmin)) { + $this->isAdmin = "false"; + } + $formats = ''; + $values = []; + $this->group_name = _substr($this->group_name, 0, 255); + if (!empty($this->id)) { + $sql = "UPDATE users_groups SET group_name = ?, modified = now() WHERE id = ?"; + $formats = "si"; + $values = [$this->group_name,$this->id]; + } else { + $sql = "INSERT INTO users_groups ( group_name, created, modified) VALUES (?,now(), now())"; + $formats = "s"; + $values = [$this->group_name]; + } + if (sqlDAL::writeSql($sql, $formats, $values)) { + if (empty($this->id)) { + $id = $global['mysqli']->insert_id; + } else { + $id = $this->id; + } + return $id; + } else { + return false; + } + } + + public function delete() + { + if (!User::isAdmin()) { + return false; + } + + global $global; + if (!empty($this->id)) { + $sql = "DELETE FROM users_groups WHERE id = ?"; + } else { + return false; + } + return sqlDAL::writeSql($sql, "i", [$this->id]); + } + + private function getUserGroup($id) + { + global $global; + $id = intval($id); + $sql = "SELECT * FROM users_groups WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + $category = $data; + } else { + $category = false; + } + return $category; + } + + public static function getAllUsersGroups() + { + global $global; + $sql = "SELECT *," + . " (SELECT COUNT(*) FROM videos_group_view WHERE users_groups_id = ug.id ) as total_videos, " + . " (SELECT COUNT(*) FROM users_has_users_groups WHERE users_groups_id = ug.id ) as total_users " + . " FROM users_groups as ug WHERE 1=1 "; + + $sql .= BootGrid::getSqlFromPost(['group_name']); + + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $arr = []; + if ($res!=false) { + foreach ($fullData as $row) { + $arr[] = $row; + } + //$category = $res->fetch_all(MYSQLI_ASSOC); + } else { + $arr = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $arr; + } + + public static function getAllUsersGroupsArray() + { + global $global; + $sql = "SELECT * FROM users_groups as ug WHERE 1=1 "; + + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $arr = []; + if ($res!=false) { + foreach ($fullData as $row) { + $arr[$row['id']] = $row['group_name']; + } + //$category = $res->fetch_all(MYSQLI_ASSOC); + } else { + $arr = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $arr; + } + + public static function getTotalUsersGroups() + { + global $global; + $sql = "SELECT id FROM users_groups WHERE 1=1 "; + + $sql .= BootGrid::getSqlSearchFromPost(['group_name']); + $res = sqlDAL::readSql($sql); + $numRows = sqlDAL::num_rows($res); + sqlDAL::close($res); + return $numRows; + } + + public function getGroup_name() + { + return $this->group_name; + } + + public function setGroup_name($group_name) + { + $this->group_name = $group_name; + } + + public static function getUserGroupByName($group_name, $refreshCache = false) + { + global $global; + $sql = "SELECT * FROM users_groups WHERE group_name = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "s", [$group_name], $refreshCache); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + $category = $data; + } else { + $category = false; + } + return $category; + } + + public static function getOrCreateUserGroups($group_name) + { + $group_name = trim($group_name); + $group_name = _substr($group_name, 0, 255); + if (empty($group_name)) { + return false; + } + $group = self::getUserGroupByName($group_name, true); + if (empty($group)) { + $g = new UserGroups(0, $group_name); + return $g->save(); + } else { + return $group['id']; + } + } + + // for users + + public static function updateUserGroups($users_id, $array_groups_id, $byPassAdmin=false, $mergeWithCurrentUserGroups=false) + { + if (!$byPassAdmin && !Permissions::canAdminUsers()) { + return false; + } + if (!is_array($array_groups_id)) { + return false; + } + if (empty($users_id)) { + return false; + } + + if ($mergeWithCurrentUserGroups) { + $current_user_groups = self::getUserGroups($users_id); + foreach ($current_user_groups as $value) { + if (!in_array($value['id'], $array_groups_id)) { + $array_groups_id[] = $value['id']; + } + } + } + + self::deleteGroupsFromUser($users_id, true); + global $global; + $array_groups_id = array_unique($array_groups_id); + $sql = "INSERT INTO users_has_users_groups ( users_id, users_groups_id) VALUES (?,?)"; + foreach ($array_groups_id as $value) { + $value = intval($value); + if (empty($value)) { + continue; + } + sqlDAL::writeSql($sql, "ii", [$users_id,$value]); + } + + // make sure you do not save the dynamic user groups + $user_groups_ids = AVideoPlugin::getDynamicUserGroupsId($users_id); + if (!empty($user_groups_ids) && is_array($user_groups_ids)) { + $sql = "DELETE FROM users_has_users_groups WHERE users_id = ? AND users_groups_id IN (". implode(',', $user_groups_ids).") "; + return sqlDAL::writeSql($sql, "i", [$users_id]); + } + + return true; + } + + public static function getAlUserGroupsFromUser($users_id) + { + return self::getUserGroups($users_id); + } + + public static function getUserGroups($users_id) + { + global $global; + $res = sqlDAL::readSql("SHOW TABLES LIKE 'users_has_users_groups'"); + $result = sqlDAL::num_rows($res); + sqlDAL::close($res); + if (empty($result)) { + $_GET['error'] = "You need to update your system to ver 2.3"; + return []; + } + if (empty($users_id)) { + return []; + } + $sql = "SELECT uug.*, ug.* FROM users_groups ug" + . " LEFT JOIN users_has_users_groups uug ON users_groups_id = ug.id WHERE users_id = ? "; + + $ids = AVideoPlugin::getDynamicUserGroupsId($users_id); + if (!empty($ids) && is_array($ids)) { + $ids = array_unique($ids); + $sql .= " OR ug.id IN ('". implode("','", $ids)."') "; + } + //var_dump($ids);echo $sql;exit; + $res = sqlDAL::readSql($sql, "i", [$users_id]); + $fullData = sqlDal::fetchAllAssoc($res); + sqlDAL::close($res); + $arr = []; + $doNotRepeat = []; + if ($res!=false) { + foreach ($fullData as $row) { + if (in_array($row['id'], $doNotRepeat)) { + continue; + } + if (in_array($row['id'], $ids)) { + $row['isDynamic'] = 1; + } else { + $row['isDynamic'] = 0; + } + $row = cleanUpRowFromDatabase($row); + $doNotRepeat[] = $row['id']; + $arr[] = $row; + } + } else { + $arr = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $arr; + } + + private static function deleteGroupsFromUser($users_id, $byPassAdmin=false) + { + if (!$byPassAdmin && !User::isAdmin()) { + return false; + } + + global $global; + if (!empty($users_id)) { + $sql = "DELETE FROM users_has_users_groups WHERE users_id = ?"; + } else { + return false; + } + return sqlDAL::writeSql($sql, "i", [$users_id]); + } + + public static function getVideoGroupsViewId($videos_id, $users_groups_id) + { + if (empty($videos_id)) { + return false; + } + if (empty($users_groups_id)) { + return false; + } + global $global; + + $sql = "SELECT id FROM videos_group_view WHERE videos_id = ? AND users_groups_id = ? LIMIT 1 "; + $res = sqlDAL::readSql($sql, "ii", [$videos_id, $users_groups_id]); + $data = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($data)) { + return $data['id']; + } else { + return 0; + } + } + + public static function addVideoGroups($videos_id, $users_groups_id) + { + if (!User::canUpload()) { + return false; + } + global $global; + + if (self::getVideoGroupsViewId($videos_id, $users_groups_id)) { + return false; + } + + $sql = "INSERT INTO videos_group_view ( videos_id, users_groups_id) VALUES (?,?)"; + $value = intval($value); + $response = sqlDAL::writeSql($sql, "ii", [$videos_id,$users_groups_id]); + + if ($response) { + Video::clearCache($videos_id); + } + return $response; + } + + public static function deleteVideoGroups($videos_id, $users_groups_id) + { + if (!User::canUpload()) { + return false; + } + + $sql = "DELETE FROM videos_group_view WHERE videos_id = ? AND users_groups_id = ?"; + $response = sqlDAL::writeSql($sql, "ii", [$videos_id, $users_groups_id]); + + if ($response) { + Video::clearCache($videos_id); + } + return $response; + } + + public static function updateVideoGroups($videos_id, $array_groups_id, $mergeWithCurrentUserGroups=false) + { + if (!User::canUpload()) { + return false; + } + if (!is_array($array_groups_id)) { + return false; + } + + if ($mergeWithCurrentUserGroups) { + $current_user_groups = self::getVideoGroups($videos_id); + foreach ($current_user_groups as $value) { + if (!in_array($value['id'], $array_groups_id)) { + $array_groups_id[] = $value['id']; + } + } + } + + self::deleteGroupsFromVideo($videos_id); + global $global; + + $sql = "INSERT INTO videos_group_view ( videos_id, users_groups_id) VALUES (?,?)"; + foreach ($array_groups_id as $value) { + $value = intval($value); + sqlDAL::writeSql($sql, "ii", [$videos_id,$value]); + } + + return true; + } + + public static function getVideoGroups($videos_id) + { + if (empty($videos_id)) { + return []; + } + global $global; + //check if table exists if not you need to update + $sql = "SELECT 1 FROM `videos_group_view` LIMIT 1"; + $res = sqlDAL::readSql($sql); + sqlDAL::close($res); + if (!$res) { + if (User::isAdmin()) { + $_GET['error'] = "You need to Update AVideo to version 2.3 Click here"; + } + return []; + } + + $sql = "SELECT v.*, ug.*FROM videos_group_view as v " + . " LEFT JOIN users_groups as ug ON users_groups_id = ug.id WHERE videos_id = ? "; + $res = sqlDAL::readSql($sql, "i", [$videos_id]); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $arr = []; + if ($res!=false) { + foreach ($fullData as $row) { + $row = cleanUpRowFromDatabase($row); + $arr[] = $row; + } + } else { + $arr = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $arr; + } + + private static function deleteGroupsFromVideo($videos_id) + { + if (!User::canUpload()) { + return false; + } + + global $global; + if (!empty($videos_id)) { + $sql = "DELETE FROM videos_group_view WHERE videos_id = ?"; + } else { + return false; + } + return sqlDAL::writeSql($sql, "i", [$videos_id]); + } +} diff --git a/objects/userGroupsAddNew.json.php b/objects/userGroupsAddNew.json.php index 99fffd2a8c..2115e70fb8 100644 --- a/objects/userGroupsAddNew.json.php +++ b/objects/userGroupsAddNew.json.php @@ -1,33 +1,32 @@ -setGroup_name($_POST['group_name']); - -if ($groups_id = $obj->save()) { - if(User::isAdmin()){ - Users_groups_permissions::deleteAllFromGroup($groups_id); - if (!empty($_REQUEST['permissions']) && is_array($_REQUEST['permissions'])) { - foreach ($_REQUEST['permissions'] as $key=>$value) { - if(!is_array($value)){ - continue; - } - foreach ($value as $value2) { - Users_groups_permissions::add($key, $groups_id, $value2); - } - } - } - } -} - -echo '{"status":"' . $groups_id . '"}'; +setGroup_name($_POST['group_name']); + +if ($groups_id = $obj->save()) { + if (User::isAdmin()) { + Users_groups_permissions::deleteAllFromGroup($groups_id); + if (!empty($_REQUEST['permissions']) && is_array($_REQUEST['permissions'])) { + foreach ($_REQUEST['permissions'] as $key=>$value) { + if (!is_array($value)) { + continue; + } + foreach ($value as $value2) { + Users_groups_permissions::add($key, $groups_id, $value2); + } + } + } + } +} + +echo '{"status":"' . $groups_id . '"}'; diff --git a/objects/userGroupsDelete.json.php b/objects/userGroupsDelete.json.php index eff0ba69f6..39f6c771ed 100644 --- a/objects/userGroupsDelete.json.php +++ b/objects/userGroupsDelete.json.php @@ -1,13 +1,13 @@ -delete().'"}'; +delete().'"}'; diff --git a/objects/userRecoverPass.php b/objects/userRecoverPass.php index 8677c3c3d8..aa806591fc 100644 --- a/objects/userRecoverPass.php +++ b/objects/userRecoverPass.php @@ -1,160 +1,159 @@ -getEmail())) { - $recoverPass = $user->setRecoverPass(); - if (!empty($_POST['captcha']) && $user->save()) { - require_once 'captcha.php'; - $valid = Captcha::validation($_POST['captcha']); - if ($valid) { - //Create a new PHPMailer instance - $mail = new \PHPMailer\PHPMailer\PHPMailer; - setSiteSendMessage($mail); - //Set who the message is to be sent from - $mail->setFrom($config->getContactEmail(), $config->getWebSiteTitle()); - //Set who the message is to be sent to - $mail->addAddress($user->getEmail()); - //Set the subject line - $mail->Subject = 'Recover Pass from ' . $config->getWebSiteTitle(); - - $msg = __("You asked for a recover link, click on the provided link") . " " . __("Reset password") . ""; - - $mail->msgHTML($msg); - - //send the message, check for errors - if (!$mail->send()) { - $obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo; - } else { - $obj->success = __("Message sent"); - } - } else { - $obj->error = __("Your code is not valid"); - } - } else { - $obj->error = __("Recover password could not be saved!"); - } - } else { - $obj->error = __("You do not have an e-mail"); - } - die(json_encode($obj)); -} else { - ?> - - - - - - - - - - -
- getRecoverPass() != $_GET['recoverpass']) { - ?> -
- -
-
- - - - -
- -
-
- - -
-
-
-
- -
-
- - -
-
-
- -
- -
- -
-
- -
- -
- -
-
- - - -
- -
- -
-
- -
-
- -
- - - - - - - - - - getEmail())) { + $recoverPass = $user->setRecoverPass(); + if (!empty($_POST['captcha']) && $user->save()) { + require_once 'captcha.php'; + $valid = Captcha::validation($_POST['captcha']); + if ($valid) { + //Create a new PHPMailer instance + $mail = new \PHPMailer\PHPMailer\PHPMailer(); + setSiteSendMessage($mail); + //Set who the message is to be sent from + $mail->setFrom($config->getContactEmail(), $config->getWebSiteTitle()); + //Set who the message is to be sent to + $mail->addAddress($user->getEmail()); + //Set the subject line + $mail->Subject = 'Recover Pass from ' . $config->getWebSiteTitle(); + + $msg = __("You asked for a recover link, click on the provided link") . " " . __("Reset password") . ""; + + $mail->msgHTML($msg); + + //send the message, check for errors + if (!$mail->send()) { + $obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo; + } else { + $obj->success = __("Message sent"); + } + } else { + $obj->error = __("Your code is not valid"); + } + } else { + $obj->error = __("Recover password could not be saved!"); + } + } else { + $obj->error = __("You do not have an e-mail"); + } + die(json_encode($obj)); +} else { + ?> + + + + + + + + + + +
+ getRecoverPass() != $_GET['recoverpass']) { + ?> +
+ +
+
+ + + + +
+ +
+
+ + +
+
+
+
+ +
+
+ + +
+
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ + + +
+ +
+ +
+
+ +
+
+ +
+ + + + + + + + + + error = __("There is missing data to recover your password"); - die(json_encode($obj)); -} -$user = new User(0, $_POST['user'], false); -if (empty($user)) { - $obj->error = __("User not found"); - die(json_encode($obj)); -} elseif ($user->getRecoverPass() !== $_POST['recoverPassword']) { - $obj->error = __("Recover password does not match"); - die(json_encode($obj)); -} elseif ($_POST['newPassword'] !== $_POST['newPasswordConfirm']) { - $obj->error = __("Confirmation password does not match"); - die(json_encode($obj)); -} else { - $user->setPassword($_POST['newPassword']); - $user->setRecoverPass(true); - if ($user->save()) { - $obj->success = __("Your Password has been set"); - die(json_encode($obj)); - } -} +error = __("There is missing data to recover your password"); + die(json_encode($obj)); +} +$user = new User(0, $_POST['user'], false); +if (empty($user)) { + $obj->error = __("User not found"); + die(json_encode($obj)); +} elseif ($user->getRecoverPass() !== $_POST['recoverPassword']) { + $obj->error = __("Recover password does not match"); + die(json_encode($obj)); +} elseif ($_POST['newPassword'] !== $_POST['newPasswordConfirm']) { + $obj->error = __("Confirmation password does not match"); + die(json_encode($obj)); +} else { + $user->setPassword($_POST['newPassword']); + $user->setRecoverPass(true); + if ($user->save()) { + $obj->success = __("Your Password has been set"); + die(json_encode($obj)); + } +} diff --git a/objects/userSaveBackground.php b/objects/userSaveBackground.php index 987019af36..5f049f604b 100644 --- a/objects/userSaveBackground.php +++ b/objects/userSaveBackground.php @@ -1,51 +1,51 @@ -error = __("You must be logged"); - die(json_encode($obj)); -} -$imagePath = "videos/userPhoto/"; - -//Check write Access to Directory -if (!file_exists($global['systemRootPath'].$imagePath)) { - mkdir($global['systemRootPath'].$imagePath, 0755, true); -} - -if (!is_writable($global['systemRootPath'].$imagePath)) { - $response = Array( - "status" => 'error', - "message" => 'No write Access' - ); - print json_encode($response); - return; -} - -$fileData = base64DataToImage($_POST['imgBase64']); -$fileName = 'background'. User::getId().'.png'; -$photoURL = $imagePath.$fileName; -$bytes = file_put_contents($global['systemRootPath'].$photoURL, $fileData); -if ($bytes) { - $response = array( - "status" => 'success', - "url" => $global['systemRootPath'].$photoURL - ); -} else { - $response = array( - "status" => 'error', - "msg" => 'We could not save this file', - "url" => $global['systemRootPath'].$photoURL - ); -} - -$user = new User(User::getId()); -$user->setBackgroundURL($photoURL); -$user->save(); -User::updateSessionInfo(); -print json_encode($response); +error = __("You must be logged"); + die(json_encode($obj)); +} +$imagePath = "videos/userPhoto/"; + +//Check write Access to Directory +if (!file_exists($global['systemRootPath'].$imagePath)) { + mkdir($global['systemRootPath'].$imagePath, 0755, true); +} + +if (!is_writable($global['systemRootPath'].$imagePath)) { + $response = [ + "status" => 'error', + "message" => 'No write Access', + ]; + print json_encode($response); + return; +} + +$fileData = base64DataToImage($_POST['imgBase64']); +$fileName = 'background'. User::getId().'.png'; +$photoURL = $imagePath.$fileName; +$bytes = file_put_contents($global['systemRootPath'].$photoURL, $fileData); +if ($bytes) { + $response = [ + "status" => 'success', + "url" => $global['systemRootPath'].$photoURL, + ]; +} else { + $response = [ + "status" => 'error', + "msg" => 'We could not save this file', + "url" => $global['systemRootPath'].$photoURL, + ]; +} + +$user = new User(User::getId()); +$user->setBackgroundURL($photoURL); +$user->save(); +User::updateSessionInfo(); +print json_encode($response); diff --git a/objects/userSavePhoto.php b/objects/userSavePhoto.php index b4ec20def2..e037d39894 100644 --- a/objects/userSavePhoto.php +++ b/objects/userSavePhoto.php @@ -1,49 +1,49 @@ -error = true; -$obj->url = ''; -$obj->status = 'error'; -$obj->msg = ''; -if (!User::isLogged()) { - $obj->msg = __("You must be logged"); - die(json_encode($obj)); -} -$imagePath = "videos/userPhoto/"; - -//Check write Access to Directory -$dirPath = $global['systemRootPath'].$imagePath; -if (!file_exists($dirPath)) { - mkdir($global['systemRootPath'].$imagePath, 0755, true); -} -/* -if (!is_writable($dirPath)) { - $obj->msg = __("No write Access on folder").' '.$dirPath; - die(json_encode($obj)); -} -*/ -$fileData = base64DataToImage($_POST['imgBase64']); -$fileName = 'photo'. User::getId().'.png'; -$photoURL = $imagePath.$fileName; - -$obj->url = $photoURL; - -$bytes = file_put_contents($global['systemRootPath'].$photoURL, $fileData); -if ($bytes) { - $obj->status = 'success'; - $obj->error = false; -} else { - $obj->msg = __("We could not save this file"); -} - -$user = new User(User::getId()); -$user->setPhotoURL($photoURL); -if($user->save()){ - User::deleteOGImage(User::getId()); - User::updateSessionInfo(); -} -die(json_encode($obj)); +error = true; +$obj->url = ''; +$obj->status = 'error'; +$obj->msg = ''; +if (!User::isLogged()) { + $obj->msg = __("You must be logged"); + die(json_encode($obj)); +} +$imagePath = "videos/userPhoto/"; + +//Check write Access to Directory +$dirPath = $global['systemRootPath'].$imagePath; +if (!file_exists($dirPath)) { + mkdir($global['systemRootPath'].$imagePath, 0755, true); +} +/* +if (!is_writable($dirPath)) { + $obj->msg = __("No write Access on folder").' '.$dirPath; + die(json_encode($obj)); +} +*/ +$fileData = base64DataToImage($_POST['imgBase64']); +$fileName = 'photo'. User::getId().'.png'; +$photoURL = $imagePath.$fileName; + +$obj->url = $photoURL; + +$bytes = file_put_contents($global['systemRootPath'].$photoURL, $fileData); +if ($bytes) { + $obj->status = 'success'; + $obj->error = false; +} else { + $obj->msg = __("We could not save this file"); +} + +$user = new User(User::getId()); +$user->setPhotoURL($photoURL); +if ($user->save()) { + User::deleteOGImage(User::getId()); + User::updateSessionInfo(); +} +die(json_encode($obj)); diff --git a/objects/userUpdate.json.php b/objects/userUpdate.json.php index cbbe44c1a7..bfaf728677 100644 --- a/objects/userUpdate.json.php +++ b/objects/userUpdate.json.php @@ -1,53 +1,52 @@ -error = __("Is not logged"); - die(json_encode($obj)); -} -$_REQUEST["do_not_login"]=1; -require_once $global['systemRootPath'] . 'objects/user.php'; -$user = new User(0); -$user->loadSelfUser(); -$user->setUser($_POST['user']); -$user->setPassword($_POST['pass']); -$user->setEmail($_POST['email']); -$user->setName($_POST['name']); -$user->setAbout($_POST['about']); -$user->setAnalyticsCode($_POST['analyticsCode']); -$user->setDonationLink($_POST['donationLink']); -$unique = $user->setChannelName($_POST['channelName']); -if (!$unique) { - $obj->error = __("Channel name already exists"); - die(json_encode($obj)); -} - -if(empty($user->getBdId())){ - $obj->error = __("User not found"); - die(json_encode($obj)); -} - -if (!empty($advancedCustomUser->emailMustBeUnique)) { - if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { - $obj->error = __("You must specify a valid email")." {$_POST['email']} (update)"; - die(json_encode($obj)); - } - $userFromEmail = User::getUserFromEmail($_POST['email']); - if (!empty($userFromEmail) && $userFromEmail['id'] !== $user->getBdId()) { - $obj->error = __("Email already exists"); - die(json_encode($obj)); - } -} - -if (User::isAdmin() && !empty($_POST['status'])) { - $user->setStatus($_POST['status']); -} -echo '{"status":"' . $user->save() . '"}'; -User::updateSessionInfo(); +error = __("Is not logged"); + die(json_encode($obj)); +} +$_REQUEST["do_not_login"]=1; +require_once $global['systemRootPath'] . 'objects/user.php'; +$user = new User(0); +$user->loadSelfUser(); +$user->setUser($_POST['user']); +$user->setPassword($_POST['pass']); +$user->setEmail($_POST['email']); +$user->setName($_POST['name']); +$user->setAbout($_POST['about']); +$user->setAnalyticsCode($_POST['analyticsCode']); +$user->setDonationLink($_POST['donationLink']); +$unique = $user->setChannelName($_POST['channelName']); +if (!$unique) { + $obj->error = __("Channel name already exists"); + die(json_encode($obj)); +} + +if (empty($user->getBdId())) { + $obj->error = __("User not found"); + die(json_encode($obj)); +} + +if (!empty($advancedCustomUser->emailMustBeUnique)) { + if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { + $obj->error = __("You must specify a valid email")." {$_POST['email']} (update)"; + die(json_encode($obj)); + } + $userFromEmail = User::getUserFromEmail($_POST['email']); + if (!empty($userFromEmail) && $userFromEmail['id'] !== $user->getBdId()) { + $obj->error = __("Email already exists"); + die(json_encode($obj)); + } +} + +if (User::isAdmin() && !empty($_POST['status'])) { + $user->setStatus($_POST['status']); +} +echo '{"status":"' . $user->save() . '"}'; +User::updateSessionInfo(); diff --git a/objects/userUpdatePersonal.json.php b/objects/userUpdatePersonal.json.php index 1edf85971a..284e810505 100644 --- a/objects/userUpdatePersonal.json.php +++ b/objects/userUpdatePersonal.json.php @@ -1,27 +1,27 @@ -loadSelfUser(); -$user->setFirst_name($_POST['first_name']); -$user->setLast_name($_POST['last_name']); -$user->setAddress($_POST['address']); -$user->setZip_code($_POST['zip_code']); -$user->setCountry($_POST['country']); -$user->setRegion($_POST['region']); -$user->setCity($_POST['city']); -$fileData = base64DataToImage($_POST['imgBase64']); - -User::saveDocumentImage($fileData, $user->getBdId()); - -echo '{"status":"'.$user->save().'"}'; -User::updateSessionInfo(); +loadSelfUser(); +$user->setFirst_name($_POST['first_name']); +$user->setLast_name($_POST['last_name']); +$user->setAddress($_POST['address']); +$user->setZip_code($_POST['zip_code']); +$user->setCountry($_POST['country']); +$user->setRegion($_POST['region']); +$user->setCity($_POST['city']); +$fileData = base64DataToImage($_POST['imgBase64']); + +User::saveDocumentImage($fileData, $user->getBdId()); + +echo '{"status":"'.$user->save().'"}'; +User::updateSessionInfo(); diff --git a/objects/userVerifyEmail.php b/objects/userVerifyEmail.php index 5804d192b1..e0c838efba 100644 --- a/objects/userVerifyEmail.php +++ b/objects/userVerifyEmail.php @@ -1,35 +1,35 @@ -error = true; -$obj->msg = "Unknown error"; - -if (!empty($_GET['users_id'])) { - $user = new User($_GET['users_id']); - $verified = $user->getEmailVerified(); - if(empty($verified)){ - if(User::sendVerificationLink($_GET['users_id'])){ - $obj->error = false; - $obj->msg = __("Verification Sent"); - } - }else{ - $obj->msg = __("Already verified"); - } -}else if(!empty($_GET['code'])){ - $result = User::verifyCode($_GET['code']); - - if($result){ - $msg = __("Email Verified"); - header("Location: {$global['webSiteRootURL']}?success={$msg}"); - }else{ - $msg = __("Email verification error"); - header("Location: {$global['webSiteRootURL']}?error={$msg}"); - } -} - -header('Content-Type: application/json'); -die(json_encode($obj)); +error = true; +$obj->msg = "Unknown error"; + +if (!empty($_GET['users_id'])) { + $user = new User($_GET['users_id']); + $verified = $user->getEmailVerified(); + if (empty($verified)) { + if (User::sendVerificationLink($_GET['users_id'])) { + $obj->error = false; + $obj->msg = __("Verification Sent"); + } + } else { + $obj->msg = __("Already verified"); + } +} elseif (!empty($_GET['code'])) { + $result = User::verifyCode($_GET['code']); + + if ($result) { + $msg = __("Email Verified"); + header("Location: {$global['webSiteRootURL']}?success={$msg}"); + } else { + $msg = __("Email verification error"); + header("Location: {$global['webSiteRootURL']}?error={$msg}"); + } +} + +header('Content-Type: application/json'); +die(json_encode($obj)); diff --git a/objects/users.json.php b/objects/users.json.php index eda58b2df4..00cc6f5d8c 100644 --- a/objects/users.json.php +++ b/objects/users.json.php @@ -1,49 +1,48 @@ -userCanChangeVideoOwner ? true : false, array('name', 'email', 'user', 'channelName', 'about'), @$_GET['status'], $isAdmin); - $total = User::getTotalUsers($advancedCustomUser->userCanChangeVideoOwner ? true : false, @$_GET['status'],$isAdmin); -}else{ - $users = User::getAllUsersFromUsergroup($_REQUEST['user_groups_id'], $advancedCustomUser->userCanChangeVideoOwner ? true : false, array('name', 'email', 'user', 'channelName', 'about'), @$_GET['status']); - $total = User::getTotalUsersFromUsergroup($_REQUEST['user_groups_id'], $advancedCustomUser->userCanChangeVideoOwner ? true : false, @$_GET['status']); -} -//echo examineJSONError($users);exit; -$json = json_encode($users); -if (json_last_error()) { - _error_log("users.json error 1: " . print_r($users, true)); - $users = object_to_array($users); - //echo examineJSONError($users);exit; - array_walk_recursive($users, function(&$item) { - if (is_string($item)) { - $item = cleanString($item); - } - }); - $json = json_encode($users); -} -if (json_last_error()) { - _error_log("users.json error 2 "); - foreach ($users as $key => $value) { - $users[$key]['about'] = ""; - } - $json = json_encode($users); -} - -echo '{ "current": ' . $_POST['current'] . ',"rowCount": ' . $_REQUEST['rowCount'] . ', "total": ' . $total . ', "rows":' . $json . '}'; +userCanChangeVideoOwner ? true : false, ['name', 'email', 'user', 'channelName', 'about'], @$_GET['status'], $isAdmin); + $total = User::getTotalUsers($advancedCustomUser->userCanChangeVideoOwner ? true : false, @$_GET['status'], $isAdmin); +} else { + $users = User::getAllUsersFromUsergroup($_REQUEST['user_groups_id'], $advancedCustomUser->userCanChangeVideoOwner ? true : false, ['name', 'email', 'user', 'channelName', 'about'], @$_GET['status']); + $total = User::getTotalUsersFromUsergroup($_REQUEST['user_groups_id'], $advancedCustomUser->userCanChangeVideoOwner ? true : false, @$_GET['status']); +} +//echo examineJSONError($users);exit; +$json = json_encode($users); +if (json_last_error()) { + _error_log("users.json error 1: " . print_r($users, true)); + $users = object_to_array($users); + //echo examineJSONError($users);exit; + array_walk_recursive($users, function (&$item) { + if (is_string($item)) { + $item = cleanString($item); + } + }); + $json = json_encode($users); +} +if (json_last_error()) { + _error_log("users.json error 2 "); + foreach ($users as $key => $value) { + $users[$key]['about'] = ''; + } + $json = json_encode($users); +} + +echo '{ "current": ' . $_POST['current'] . ',"rowCount": ' . $_REQUEST['rowCount'] . ', "total": ' . $total . ', "rows":' . $json . '}'; diff --git a/objects/usersGroups.json.php b/objects/usersGroups.json.php index 8782bff4e0..7cb73ba2e7 100644 --- a/objects/usersGroups.json.php +++ b/objects/usersGroups.json.php @@ -1,22 +1,22 @@ - 'Active', - 'k' => 'Active and Encoding', - 'i' => 'Inactive', - 'e' => 'Encoding', - 'x' => 'Encoding Error', - 'd' => 'Downloading', - 't' => 'Transferring', - 'u' => 'Unlisted', - 'r' => 'Recording', - 'f' => 'FansOnly', - 'b' => 'Broken Missing files'); - public static $statusIcons = array( - 'a' => '', - 'k' => '', - 'i' => '', - 'e' => '', - 'x' => '', - 'd' => '', - 't' => '', - 'u' => '', - 'r' => '', - 'f' => '', - 'b' => ''); - public static $statusActive = 'a'; - public static $statusActiveAndEncoding = 'k'; - public static $statusInactive = 'i'; - public static $statusEncoding = 'e'; - public static $statusEncodingError = 'x'; - public static $statusDownloading = 'd'; - public static $statusTranfering = 't'; - public static $statusUnlisted = 'u'; - public static $statusRecording = 'r'; - public static $statusFansOnly = 'f'; - public static $statusBrokenMissingFiles = 'b'; - public static $rratingOptions = array('', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma'); - //ver 3.4 - private $youtubeId; - public static $typeOptions = array('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'image', 'zip', 'notfound', 'blockedUser'); - - public function __construct($title = "", $filename = "", $id = 0) { - global $global; - $this->rotation = 0; - $this->zoom = 1; - if (!empty($id)) { - $this->load($id); - } - if (!empty($title)) { - $this->setTitle($title); - } - if (!empty($filename)) { - $this->filename = $filename; - } - } - - public function addView($currentTime = 0) { - global $global; - if (empty($this->id)) { - return false; - } - $sql = "UPDATE videos SET views_count = views_count+1, modified = now() WHERE id = ?"; - - $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); - - if ($insert_row) { - $obj = new stdClass(); - $obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime); - $obj->videos_id = $this->id; - $this->views_count++; - AVideoPlugin::addView($this->id, $this->views_count); - return $obj; - } - die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - - public function addSecondsWatching($seconds_watching) { - global $global; - - $seconds_watching = intval($seconds_watching); - - if (empty($seconds_watching)) { - return false; - } - - if (empty($this->id)) { - return false; - } - $sql = "UPDATE videos SET total_seconds_watching = total_seconds_watching+{$seconds_watching}, modified = now() WHERE id = ?"; - //_error_log($sql."={$this->id}"); - return sqlDAL::writeSql($sql, "i", array($this->id)); - } - - public function updateViewsCount($total) { - global $global; - if (empty($this->id)) { - return false; - } - $total = intval($total); - if ($total < 0) { - return false; - } - $sql = "UPDATE videos SET views_count = {$total}, modified = now() WHERE id = ?"; - - $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); - - if ($insert_row) { - return $insert_row; - } - die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - - public function addViewPercent($percent = 25) { - global $global; - if (empty($this->id)) { - return false; - } - $sql = "UPDATE videos SET views_count_{$percent} = IFNULL(views_count_{$percent}, 0)+1, modified = now() WHERE id = ?"; - - $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); - - if ($insert_row) { - return true; - } - die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - - // allow users to count a view again in case it is refreshed - public static function unsetAddView($videos_id) { - // allow users to count a view again in case it is refreshed - if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) { - _session_start(); - unset($_SESSION['addViewCount'][$videos_id]); - } - } - - public function load($id) { - $video = self::getVideoLight($id); - if (empty($video)) { - return false; - } - foreach ($video as $key => $value) { - $this->$key = $value; - } - } - - function getLive_transmitions_history_id() { - return $this->live_transmitions_history_id; - } - - function setLive_transmitions_history_id($live_transmitions_history_id) { - AVideoPlugin::onVideoSetLive_transmitions_history_id($this->id, $this->live_transmitions_history_id, intval($live_transmitions_history_id)); - $this->live_transmitions_history_id = intval($live_transmitions_history_id); - } - - public function getEncoderURL() { - return $this->encoderURL; - } - - public function getFilepath() { - return $this->filepath; - } - - public function getFilesize() { - return intval($this->filesize); - } - - public function setEncoderURL($encoderURL) { - if (filter_var($encoderURL, FILTER_VALIDATE_URL) !== false) { - AVideoPlugin::onVideoSetEncoderURL($this->id, $this->encoderURL, $encoderURL); - $this->encoderURL = $encoderURL; - } - } - - public function setFilepath($filepath) { - AVideoPlugin::onVideoSetFilepath($this->id, $this->filepath, $filepath); - $this->filepath = $filepath; - } - - public function setFilesize($filesize) { - AVideoPlugin::onVideoSetFilesize($this->id, $this->filesize, $filesize); - $this->filesize = intval($filesize); - } - - public function setUsers_id($users_id) { - AVideoPlugin::onVideoSetUsers_id($this->id, $this->users_id, $users_id); - $this->users_id = $users_id; - } - - public function getSites_id() { - return $this->sites_id; - } - - public function setSites_id($sites_id) { - AVideoPlugin::onVideoSetSites_id($this->id, $this->sites_id, $sites_id); - $this->sites_id = $sites_id; - } - - public function getVideo_password() { - return trim($this->video_password); - } - - public function setVideo_password($video_password) { - AVideoPlugin::onVideoSetVideo_password($this->id, $this->video_password, $video_password); - $this->video_password = trim($video_password); - } - - public function save($updateVideoGroups = false, $allowOfflineUser = false) { - global $advancedCustom; - global $global; - if (!User::isLogged() && !$allowOfflineUser) { - _error_log('Video::save permission denied to save'); - return false; - } - if (empty($this->title)) { - $this->title = uniqid(); - } - - $this->clean_title = substr($this->clean_title, 0, 187); - - if (empty($this->clean_title)) { - $this->setClean_title($this->title); - } - $this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id); - - if (empty($this->status)) { - $this->status = 'e'; - } - - if (empty($this->type) || !in_array($this->type, self::$typeOptions)) { - $this->type = 'video'; - } - - if (empty($this->isSuggested)) { - $this->isSuggested = 0; - } else { - $this->isSuggested = 1; - } - - if (empty($this->categories_id)) { - $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); - $category = Category::getCategoryDefault(); - $categories_id = $category['id']; - if (empty($categories_id)) { - $categories_id = 'NULL'; - } - if ($p) { - $this->categories_id = $p->getCategoryId(); - } else { - $this->categories_id = $categories_id; - } - if (empty($this->categories_id)) { - $this->categories_id = $categories_id; - } - } - // check if category exists - $cat = new Category($this->categories_id); - if (empty($cat->getName())) { - $catDefault = Category::getCategoryDefault(); - $this->categories_id = $catDefault['id']; - } - $this->setTitle($global['mysqli']->real_escape_string(trim($this->title))); - $this->description = ($global['mysqli']->real_escape_string($this->description)); - - if (forbiddenWords($this->title) || forbiddenWords($this->description)) { - return false; - } - - if (empty($this->users_id)) { - $this->users_id = User::getId(); - } - - $this->next_videos_id = intval($this->next_videos_id); - if (empty($this->next_videos_id)) { - $this->next_videos_id = 'NULL'; - } - - $this->sites_id = intval($this->sites_id); - if (empty($this->sites_id)) { - $this->sites_id = 'NULL'; - } - - $this->serie_playlists_id = intval($this->serie_playlists_id); - if (empty($this->serie_playlists_id)) { - $this->serie_playlists_id = 'NULL'; - } - - if (empty($this->filename)) { - $prefix = $this->type; - if (empty($prefix)) { - $prefix = 'v'; - } - $paths = self::getNewVideoFilename($prefix); - $this->filename = $paths['filename']; - } - - $this->can_download = intval($this->can_download); - $this->can_share = intval($this->can_share); - $this->only_for_paid = intval($this->only_for_paid); - $this->filesize = intval($this->filesize); - - $this->rate = floatval($this->rate); - - if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) { - $this->videoLink = ''; - if ($this->type == 'embed') { - $this->type = 'video'; - } - } - - if (empty($this->live_transmitions_history_id)) { - $this->live_transmitions_history_id = 'NULL'; - } - - if (empty($this->duration_in_seconds)) { - $this->duration_in_seconds = durationToSeconds($this->duration); - } - - 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}' , duration_in_seconds = '{$this->duration_in_seconds}' , modified = now()" - . " WHERE id = {$this->id}"; - - $saved = sqlDAL::writeSql($sql); - if ($saved) { - $insert_row = $this->id; - } - } else { - $sql = "INSERT INTO videos " - . "(duration_in_seconds, 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->duration_in_seconds}','{$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}"); - if (class_exists('Cache')) { - Cache::deleteCache("getVideoTags{$this->id}"); - } - self::deleteTagsAsync($this->id); - if ($updateVideoGroups) { - require_once $global['systemRootPath'] . 'objects/userGroups.php'; - // update the user groups - UserGroups::updateVideoGroups($id, $this->videoGroups); - } - - // I am not sure what is it for - //Video::autosetCategoryType($id); - if (!empty($this->old_categories_id)) { - //Video::autosetCategoryType($this->old_categories_id); - } - self::clearCache($this->id); - return $id; - } - _error_log('Video::save Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); - return false; - } - - public static function updateDurationInSeconds($videos_id, $duration) { - global $config; - $videos_id = intval($videos_id); - if ($config->currentVersionLowerThen('11.4')) { - return false; - } - if (empty($videos_id)) { - return false; - } - $duration_in_seconds = durationToSeconds($duration); - if (empty($duration_in_seconds)) { - _error_log("Video::updateDurationInSeconds empty duration {$videos_id}, {$duration}"); - return false; - } - _error_log("Video::updateDurationInSeconds update duration {$videos_id}, {$duration}, {$duration_in_seconds}"); - $sql = "UPDATE videos SET duration_in_seconds = '{$duration_in_seconds}' , modified = now() WHERE id = {$videos_id}"; - $saved = sqlDAL::writeSql($sql); - self::clearCache($videos_id); - return $duration_in_seconds; - } - - // i would like to simplify the big part of the method above in this method, but won't work as i want. - public static function internalAutoset($catId, $videoFound, $audioFound) { - global $config; - if ($config->currentVersionLowerThen('5.01')) { - return false; - } - $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $fullResult2 = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult2 as $row) { - if ($row['type'] == "audio") { - $audioFound = true; - } elseif ($row['type'] == "video") { - $videoFound = true; - } - } - } - if (($videoFound == false) || ($audioFound == false)) { - $sql = "SELECT parentId,categories_id FROM `categories` WHERE parentId = ?;"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $fullResult2 = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult2 as $cat) { - $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; - $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult as $row) { - if ($row['type'] == 'audio') { - $audioFound = true; - } elseif ($row['type'] == 'video') { - $videoFound = true; - } - } - } - } - } - } - return array($videoFound, audioFound); - } - - public function setClean_title($clean_title) { - if (preg_match("/video-automatically-booked/i", $clean_title) && !empty($this->clean_title)) { - return false; - } - $clean_title = cleanURLName($clean_title); - AVideoPlugin::onVideoSetClean_title($this->id, $this->clean_title, $clean_title); - $this->clean_title = $clean_title; - } - - public function setDuration($duration) { - AVideoPlugin::onVideoSetDuration($this->id, $this->duration, $duration); - $this->duration = $duration; - } - - public function getDuration() { - return $this->duration; - } - - public function getIsSuggested() { - return $this->isSuggested; - } - - public function setIsSuggested($isSuggested) { - if (empty($isSuggested) || $isSuggested === "false") { - $new_isSuggested = 0; - } else { - $new_isSuggested = 1; - } - AVideoPlugin::onVideoSetIsSuggested($this->id, $this->isSuggested, $new_isSuggested); - $this->isSuggested = $new_isSuggested; - } - - public function setStatus($status) { - if (!empty($this->id)) { - global $global; - - if (empty(Video::$statusDesc[$status])) { - _error_log("Video::setStatus({$status}) NOT found ", AVideoLog::$WARNING); - return false; - } - _error_log("Video::setStatus({$status}) " . json_encode(debug_backtrace()), AVideoLog::$WARNING); - $sql = "UPDATE videos SET status = ?, modified = now() WHERE id = ? "; - $res = sqlDAL::writeSql($sql, 'si', array($status, $this->id)); - if ($global['mysqli']->errno != 0) { - die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - self::clearCache($this->id); - if($this->status==Video::$statusActive || $status==Video::$statusActive && ($this->status != $status)){ - clearCache(true); - } - } - 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 ""; - } - - if (self::allowFreePlayWithAdsIsEnabled()) { - $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; - } - } - - static function allowFreePlayWithAdsIsEnabled() { - $obj = AVideoPlugin::getDataObjectIfEnabled('Subscription'); - if ($obj && $obj->allowFreePlayWithAds) { - return true; - } - $obj = AVideoPlugin::getDataObjectIfEnabled('PayPerView'); - if ($obj && $obj->allowFreePlayWithAds) { - return true; - } - $obj = AVideoPlugin::getDataObjectIfEnabled('FansSubscriptions'); - if ($obj && $obj->allowFreePlayWithAds) { - return true; - } - return false; - } - - static function getUserGroups($videos_id) { - return UserGroups::getVideoGroups($videos_id); - } - - public static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true) { - global $global, $config, $advancedCustom, $advancedCustomUser; - if ($config->currentVersionLowerThen('5')) { - return false; - } - $status = str_replace("'", "", $status); - $id = intval($id); - if (AVideoPlugin::isEnabledByName("VideoTags")) { - if (!empty($_GET['tags_id']) && empty($videosArrayId)) { - $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); - } - } - _mysql_connect(); - $sql = "SELECT u.*, v.*, " - . " nv.title as next_title," - . " nv.clean_title as next_clean_title," - . " nv.filename as next_filename," - . " nv.id as next_id," - . " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation " - //. ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes " - //. ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes " - ; - if (User::isLogged()) { - $sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote "; - } else { - $sql .= ", 0 as myVote "; - } - $sql .= " FROM videos as v " - . "LEFT JOIN categories c ON categories_id = c.id " - . "LEFT JOIN users u ON v.users_id = u.id " - . "LEFT JOIN videos nv ON v.next_videos_id = nv.id " - . " WHERE 1=1 "; - if ($activeUsersOnly) { - $sql .= " AND u.status = 'a' "; - } - - if (!empty($id)) { - $sql .= " AND v.id = '$id' "; - } - $sql .= AVideoPlugin::getVideoWhereClause(); - $sql .= static::getVideoQueryFileter(); - if (!$ignoreGroup) { - $sql .= self::getUserGroupsCanSeeSQL('v.'); - } - if (!empty($_SESSION['type'])) { - if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { - $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; - } elseif ($_SESSION['type'] == 'audio') { - $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; - } else { - $sql .= " AND v.type = '{$_SESSION['type']}' "; - } - } - - if (!empty($videosArrayId) && is_array($videosArrayId)) { - $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; - } - if ($status == "viewable") { - $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; - } elseif ($status == "viewableNotUnlisted") { - $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; - } elseif (!empty($status)) { - $sql .= " AND v.status = '{$status}'"; - } - - if (!empty($_GET['catName'])) { - $catName = $global['mysqli']->real_escape_string($_GET['catName']); - $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))"; - } - - if (empty($id) && !empty($_GET['channelName'])) { - $user = User::getChannelOwner($_GET['channelName']); - if (!empty($user['id'])) { - $sql .= " AND v.users_id = '{$user['id']}' "; - } - } - - if (!empty($_GET['search'])) { - $_POST['searchPhrase'] = $_GET['search']; - } - - if (!empty($_POST['searchPhrase'])) { - $_POST['searchPhrase'] = str_replace('"', '"', $_POST['searchPhrase']); - $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description', 'v.id', 'v.filename'); - 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(!empty($video['id'])){ - if (is_null($video['likes'])) { - $video['likes'] = self::updateLikesDislikes($video['id'], 'likes'); - } - if (is_null($video['dislikes'])) { - $video['dislikes'] = self::updateLikesDislikes($video['id'], 'dislikes'); - } - } - // if there is a search, and there is no data and is inside a channel try again without a channel - if (!empty($_GET['search']) && empty($video) && !empty($_GET['channelName'])) { - $channelName = $_GET['channelName']; - unset($_GET['channelName']); - $return = self::getVideo($id, $status, $ignoreGroup, $random, $suggestedOnly, $showUnlisted, $ignoreTags, $activeUsersOnly); - $_GET['channelName'] = $channelName; - return $return; - } - - sqlDAL::close($res); - if ($res != false) { - require_once $global['systemRootPath'] . 'objects/userGroups.php'; - if (!empty($video)) { - $video = self::getInfo($video); - } - } else { - $video = false; - } - return $video; - } - - public static function getVideoLikes($videos_id) { - global $global, $_getLikes; - - if (!isset($_getLikes)) { - $_getLikes = array(); - } - - if (!empty($_getLikes[$videos_id])) { - return $_getLikes[$videos_id]; - } - - require_once $global['systemRootPath'] . 'objects/like.php'; - $obj = new stdClass(); - $obj->videos_id = $videos_id; - $obj->likes = 0; - $obj->dislikes = 0; - $obj->myVote = Like::getMyVote($videos_id); - - $video = Video::getVideoLight($obj->videos_id); - $obj->likes = intval($video['likes']); - $obj->dislikes = intval($video['dislikes']); - $_getLikes[$videos_id] = $obj; - - return $obj; - } - - public static function getVideoLight($id) { - global $global, $config; - $id = intval($id); - $sql = "SELECT * FROM videos WHERE id = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, 'i', array($id), 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, $_getVideoFromFileName; - if (empty($fileName)) { - return false; - } - $parts = explode("/", $fileName); - if (!empty($parts[0])) { - $fileName = $parts[0]; - } - $fileName = self::getCleanFilenameFromFile($fileName); - - if (!isset($_getVideoFromFileName)) { - $_getVideoFromFileName = array(); - } - $indexName = "{$fileName}_{$ignoreGroup}_{$ignoreTags}"; - if (isset($_getVideoFromFileName[$indexName])) { - return $_getVideoFromFileName[$indexName]; - } - $_getVideoFromFileName[$indexName] = false; - $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'])) { - $_getVideoFromFileName[$indexName] = self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags); - } - } - return $_getVideoFromFileName[$indexName]; - } - - public static function getVideoFromFileNameLight($fileName) { - global $global; - $fileName = self::getCleanFilenameFromFile($fileName); - if (empty($fileName)) { - return false; - } - $sql = "SELECT * FROM videos WHERE filename = ? LIMIT 1"; - //var_dump($sql, $fileName); - $res = sqlDAL::readSql($sql, "s", array($fileName), true); - if ($res != false) { - $video = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - return $video; - } - return false; - } - - public static function getVideoFromCleanTitle($clean_title) { - // even increasing the max_allowed_packet it only goes away when close and reopen the connection - global $global; - $sql = "SELECT id FROM videos WHERE clean_title = ? LIMIT 1"; - $res = sqlDAL::readSql($sql, "s", array($clean_title)); - $video = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($video) && $res) { - return self::getVideo($video['id'], "", true, false, false, true); - //$video['groups'] = UserGroups::getVideoGroups($video['id']); - } else { - return false; - } - } - - static function getRelatedMovies($videos_id, $limit = 10) { - global $global; - $video = self::getVideoLight($videos_id); - if (empty($video)) { - return false; - } - $sql = "SELECT * FROM videos v WHERE v.id != {$videos_id} AND v.status='a' AND (categories_id = {$video['categories_id']} "; - if (AVideoPlugin::isEnabledByName("VideoTags")) { - $sql .= " OR ("; - $sql .= "v.id IN (select videos_id FROM tags_has_videos WHERE tags_id IN " - . " (SELECT tags_id FROM tags_has_videos WHERE videos_id = {$videos_id}))"; - $sql .= ")"; - } - - $sql .= ") "; - - $sql .= AVideoPlugin::getVideoWhereClause(); - - $sql .= "ORDER BY RAND() LIMIT {$limit} "; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - foreach ($fullData as $row) { - $row['images'] = self::getImageFromFilename($row['filename']); - if (empty($row['externalOptions'])) { - $row['externalOptions'] = json_encode(array('videoStartSeconds' => '00:00:00')); - } - $rows[] = $row; - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $rows; - } - - /** - * - * @global type $global - * @param type $status - * @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results - * @param type $ignoreGroup - * @param type $videosArrayId an array with videos to return (for filter only) - * @return boolean - */ - public static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false, $is_serie = null) { - global $global, $config, $advancedCustom, $advancedCustomUser; - if ($config->currentVersionLowerThen('11.5')) { - return false; - } - if ($dirh) { - while (($dirElement = readdir($dirh)) !== false) { - - } - closedir($dirh); - } - 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__, 0.2); - } - } - $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__, 0.2); - } - 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'])) { - $_POST['searchPhrase'] = str_replace('"', '"', $_POST['searchPhrase']); - $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description', 'v.id', 'v.filename'); - if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) { - $searchFieldsNames[] = 'u.channelName'; - } - if (AVideoPlugin::isEnabledByName("VideoTags")) { - $sql .= " AND ("; - $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; - $sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR"); - $searchFieldsNames = array('v.title'); - $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); - $sql .= ")"; - } else { - $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); - $searchFieldsNames = array('v.title'); - $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')'; - } - } - - $sql .= AVideoPlugin::getVideoWhereClause(); - - if ($suggestedOnly) { - $sql .= " AND v.isSuggested = 1 "; - $sql .= " ORDER BY RAND() "; - $sort = @$_POST['sort']; - unset($_POST['sort']); - $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); - if (strpos(strtolower($sql), 'limit') === false) { - $sql .= " LIMIT 60 "; - } - $_POST['sort'] = $sort; - } elseif (!isset($_POST['sort']['trending']) && !isset($_GET['sort']['trending'])) { - if (!empty($_POST['sort']['created']) && !empty($_POST['sort']['likes'])) { - $_POST['sort']['v.created'] = $_POST['sort']['created']; - unset($_POST['sort']['created']); - } - $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); - } else { - unset($_POST['sort']['trending'], $_GET['sort']['trending']); - $rows = array(); - if (!empty($_REQUEST['current']) && $_REQUEST['current'] == 1) { - $rows = VideoStatistic::getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); - } - $ids = array(); - foreach ($rows as $row) { - $ids[] = $row['id']; - } - if (!empty($ids)) { - $sql .= " ORDER BY FIND_IN_SET(v.id, '" . implode(",", $ids) . "') DESC, likes DESC "; - } else { - $sql .= " ORDER BY likes DESC "; - } - $sql .= ObjectYPT::getSqlLimit(); - } - if (strpos(strtolower($sql), 'limit') === false) { - if (!empty($_GET['limitOnceToOne'])) { - $sql .= " LIMIT 1"; - unset($_GET['limitOnceToOne']); - } else { - $_REQUEST['rowCount'] = getRowCount(); - if (!empty($_REQUEST['rowCount'])) { - $sql .= " LIMIT {$_REQUEST['rowCount']}"; - } else { - _error_log("getAllVideos without limit " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); - 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); - - $timeLogName = TimeLogStart("video::getAllVideos"); - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - TimeLogEnd($timeLogName, __LINE__, 0.2); - - // 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']); - TimeLogEnd($timeLogName, __LINE__, 1); - $return = self::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly, $suggestedOnly); - TimeLogEnd($timeLogName, __LINE__, 1); - $_GET['channelName'] = $channelName; - return $return; - } - - sqlDAL::close($res); - $videos = array(); - if ($res != false) { - //$global['mysqli']->commit(); - require_once 'userGroups.php'; - TimeLogStart("video::getAllVideos foreach"); - // for the cache on the database fast insert - - TimeLogEnd($timeLogName, __LINE__, 0.2); - $global['mysqli']->begin_transaction(); - foreach ($fullData as $row) { - if (is_null($row['likes'])) { - $row['likes'] = self::updateLikesDislikes($row['id'], 'likes'); - } - if (is_null($row['dislikes'])) { - $row['dislikes'] = self::updateLikesDislikes($row['id'], 'dislikes'); - } - if (empty($row['duration_in_seconds']) && $row['type']!=='article') { - $row['duration_in_seconds'] = self::updateDurationInSeconds($row['id'], $row['duration']); - } - $row = self::getInfo($row, $getStatistcs); - $videos[] = $row; - } - $global['mysqli']->commit(); - TimeLogEnd($timeLogName, __LINE__, 1); - $rowCount = getRowCount(); - $tolerance = $rowCount / 100; - if ($tolerance < 0.2) { - $tolerance = 0.2; - } else if ($tolerance > 2) { - $tolerance = 2; - } - TimeLogEnd("video::getAllVideos foreach", __LINE__, $tolerance); - //$videos = $res->fetch_all(MYSQLI_ASSOC); - } else { - $videos = false; - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $videos; - } - - private static function getInfo($row, $getStatistcs = false) { - $TimeLogLimit = 0.1; - $timeLogName = TimeLogStart("video::getInfo getStatistcs"); - $name = "_getVideoInfo_{$row['id']}"; - $cache = ObjectYPT::getCache($name, 3600); - if (!empty($cache)) { - $externalOptions = $cache->externalOptions; - $obj = object_to_array($cache); - if (!empty($externalOptions)) { - if (is_object($externalOptions)) { - $obj['externalOptions'] = $externalOptions; - } else if (is_string($externalOptions)) { - $obj['externalOptions'] = _json_decode($externalOptions); - } - $obj['externalOptions'] = json_encode($obj['externalOptions']); - } - if (empty($obj['externalOptions'])) { - $obj['externalOptions'] = json_encode(array('videoStartSeconds' => '00:00:00')); - } - return $obj; - } - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row = cleanUpRowFromDatabase($row); - if (!self::canEdit($row['id'])) { - if (!empty($row['video_password'])) { - $row['video_password'] = 1; - } else { - $row['video_password'] = 0; - } - } - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - if ($getStatistcs) { - $previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days")); - $previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days")); - $today = date('Y-m-d 23:59:59'); - $row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']); - $row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today); - $row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today); - $row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today); - $row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true); - } - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $otherInfocachename = "otherInfo{$row['id']}"; - $otherInfo = object_to_array(ObjectYPT::getCache($otherInfocachename, 600)); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - if (empty($otherInfo)) { - $otherInfo = array(); - $otherInfo['category'] = xss_esc_back($row['category']); - $otherInfo['groups'] = UserGroups::getVideoGroups($row['id']); - $otherInfo['tags'] = self::getTags($row['id']); - $cached = ObjectYPT::setCache($otherInfocachename, $otherInfo); - //_error_log("video::getInfo cache " . json_encode($cached)); - } - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $otherInfo['title'] = UTF8encode($row['title']); - $otherInfo['description'] = UTF8encode($row['description']); - $otherInfo['descriptionHTML'] = self::htmlDescription($otherInfo['description']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - foreach ($otherInfo as $key => $value) { - $row[$key] = $value; - } - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['hashId'] = idToHash($row['id']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['link'] = self::getLinkToVideo($row['id'], $row['clean_title']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['embedlink'] = self::getLinkToVideo($row['id'], $row['clean_title'], true); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['progress'] = self::getVideoPogressPercent($row['id']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['isFavorite'] = self::isFavorite($row['id']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['isWatchLater'] = self::isWatchLater($row['id']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $row['total_seconds_watching_human'] = seconds2human($row['total_seconds_watching']); - $row['views_count_short'] = number_format_short($row['views_count']); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - - if (empty($row['externalOptions'])) { - $row['externalOptions'] = json_encode(array('videoStartSeconds' => '00:00:00')); - } - $row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id'])); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - ObjectYPT::setCache($name, $row); - TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - return $row; - } - - public static function htmlDescription($description) { - if (strip_tags($description) != $description) { - return $description; - } else { - return nl2br(textToLink(htmlentities($description))); - } - } - - public static function isFavorite($videos_id) { - if (AVideoPlugin::isEnabledByName("PlayLists")) { - return PlayList::isVideoOnFavorite($videos_id, User::getId()); - } - return false; - } - - public static function isSerie($videos_id) { - $v = new Video("", "", $videos_id); - return !empty($v->getSerie_playlists_id()); - } - - public static function isWatchLater($videos_id) { - if (AVideoPlugin::isEnabledByName("PlayLists")) { - return PlayList::isVideoOnWatchLater($videos_id, User::getId()); - } - return false; - } - - public static function getFavoriteIdFromUser($users_id) { - if (AVideoPlugin::isEnabledByName("PlayLists")) { - return PlayList::getFavoriteIdFromUser($users_id); - } - return false; - } - - public static function getWatchLaterIdFromUser($users_id) { - if (AVideoPlugin::isEnabledByName("PlayLists")) { - return PlayList::getWatchLaterIdFromUser($users_id); - } - return false; - } - - public static function updateFilesizeFromFilename($filename) { - $value = Video::getVideoFromFileNameLight($filename); - return self::updateFilesize($value['id']); - } - - 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)) { - //_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 " . humanFileSize($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 " . humanFileSize($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 " . humanFileSize($filesize)); - Video::clearCache($videos_id); - return $filesize; - } else { - _error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize " . humanFileSize($filesize)); - return false; - } - } - - /** - * Same as getAllVideos() method but a lighter query - * @global type $global - * @global type $config - * @param type $showOnlyLoggedUserVideos - * @return boolean - */ - public static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false) { - global $global, $config; - if ($config->currentVersionLowerThen('5')) { - return false; - } - $status = str_replace("'", "", $status); - $sql = "SELECT v.* " - . " FROM videos as v " - . " WHERE 1=1 "; - $blockedUsers = self::getBlockedUsersIdsArray(); - if (!empty($blockedUsers)) { - $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; - } - if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { - $sql .= " AND v.users_id = '" . User::getId() . "'"; - } elseif (!empty($showOnlyLoggedUserVideos)) { - $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; - } - if ($status == "viewable") { - if (User::isLogged()) { - $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; - } else { - $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; - } - } elseif ($status == "viewableNotUnlisted") { - $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; - } elseif (!empty($status)) { - $sql .= " AND v.status = '{$status}'"; - } - - if (!empty($_GET['channelName'])) { - $user = User::getChannelOwner($_GET['channelName']); - $sql .= " AND v.users_id = '{$user['id']}' "; - } - $sql .= AVideoPlugin::getVideoWhereClause(); - - if ($suggestedOnly) { - $sql .= " AND v.isSuggested = 1 "; - $sql .= " ORDER BY RAND() "; - } - if (strpos(strtolower($sql), 'limit') === false) { - if (empty($global['limitForUnlimitedVideos'])) { - $global['limitForUnlimitedVideos'] = empty($global['rowCount']) ? 1000 : $global['rowCount']; - } - if ($global['limitForUnlimitedVideos'] > 0) { - $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; - } - } - //echo $sql; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - - // if there is a search, and there is no data and is inside a channel try again without a channel - if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) { - $channelName = $_GET['channelName']; - unset($_GET['channelName']); - $return = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); - $_GET['channelName'] = $channelName; - return $return; - } - - sqlDAL::close($res); - $videos = array(); - if ($res != false) { - foreach ($fullData as $row) { - if (empty($row['duration_in_seconds']) && $row['type']!=='article') { - $row['duration_in_seconds'] = self::updateDurationInSeconds($row['id'], $row['duration']); - } - 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}' OR c.parentId IN (SELECT cs.id from categories cs where cs.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'])) { - $_POST['searchPhrase'] = str_replace('"', '"', $_POST['searchPhrase']); - $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description', 'v.id', 'v.filename'); - if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) { - $searchFieldsNames[] = 'u.channelName'; - } - if (AVideoPlugin::isEnabledByName("VideoTags")) { - $sql .= " AND ("; - $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; - $sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR"); - $searchFieldsNames = array('v.title'); - $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); - $sql .= ")"; - } else { - $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); - $searchFieldsNames = array('v.title'); - $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')'; - } - } - - if ($suggestedOnly) { - $sql .= " AND v.isSuggested = 1 "; - } - $res = sqlDAL::readSql($sql); - $numRows = sqlDal::num_rows($res); - sqlDAL::close($res); - - // if there is a search, and there is no data and is inside a channel try again without a channel - if (!empty($_GET['search']) && empty($numRows) && !empty($_GET['channelName'])) { - $channelName = $_GET['channelName']; - unset($_GET['channelName']); - $return = self::getTotalVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly); - $_GET['channelName'] = $channelName; - return $return; - } - - return $numRows; - } - - public static function getTotalVideosInfo($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array()) { - $obj = new stdClass(); - $obj->likes = 0; - $obj->disLikes = 0; - $obj->views_count = 0; - $obj->total_minutes = 0; - - $videos = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId); - - foreach ($videos as $value) { - $obj->likes += intval($value['likes']); - $obj->disLikes += intval($value['dislikes']); - $obj->views_count += intval($value['views_count']); - $obj->total_minutes += intval(parseDurationToSeconds($value['duration']) / 60); - } - - return $obj; - } - - public static function getTotalVideosInfoAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false) { - global $global, $advancedCustom; - $path = getCacheDir() . "getTotalVideosInfo/"; - make_path($path); - $cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}"; - $return = array(); - if (!file_exists($cacheFileName)) { - if (file_exists($cacheFileName . ".lock")) { - return array(); - } - file_put_contents($cacheFileName . ".lock", 1); - $total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs); - file_put_contents($cacheFileName, json_encode($total)); - unlink($cacheFileName . ".lock"); - return $total; - } - $return = _json_decode(file_get_contents($cacheFileName)); - if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { - // file older than 1 min - $command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' " - . " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', " - . " '$getStatistcs', '$cacheFileName'"); - //_error_log("getTotalVideosInfoAsync: {$command}"); - exec($command . " > /dev/null 2>/dev/null &"); - } - return $return; - } - - public static function getViewableStatus($showUnlisted = false) { - $viewable = array('a', 'k', 'f'); - if ($showUnlisted) { - $viewable[] = "u"; - } - /* - * Cannot do that otherwise it will list videos on the list videos menu - $videos_id = getVideos_id(); - if (!empty($videos_id)) { - $post = $_POST; - if (self::isOwner($videos_id) || Permissions::canModerateVideos()) { - $viewable[] = "u"; - } - $_POST = $post; - } - * - */ - return $viewable; - } - - public static function getVideoConversionStatus($filename) { - global $global; - require_once $global['systemRootPath'] . 'objects/user.php'; - if (!User::isLogged()) { - die("Only logged users can upload"); - } - - $object = new stdClass(); - - foreach (self::$types as $value) { - $progressFilename = self::getStoragePathFromFileName($filename) . "progress_{$value}.txt"; - $content = @url_get_contents($progressFilename); - $object->$value = new stdClass(); - if (!empty($content)) { - $object->$value = self::parseProgress($content); - } else { - - } - - if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) { - $video = self::getVideoFromFileName($filename); - //var_dump($video, $filename); - if (!empty($video)) { - $object->$value->progress = self::$statusDesc[$video['status']]; - } - } - - $object->$value->filename = $progressFilename; - } - - return $object; - } - - private static function parseProgress($content) { - //get duration of source - - $obj = new stdClass(); - - $obj->duration = 0; - $obj->currentTime = 0; - $obj->progress = 0; - //var_dump($content);exit; - preg_match("/Duration: (.*?), start:/", $content, $matches); - if (!empty($matches[1])) { - $rawDuration = $matches[1]; - - //rawDuration is in 00:00:00.00 format. This converts it to seconds. - $ar = array_reverse(explode(":", $rawDuration)); - $duration = floatval($ar[0]); - if (!empty($ar[1])) { - $duration += intval($ar[1]) * 60; - } - if (!empty($ar[2])) { - $duration += intval($ar[2]) * 60 * 60; - } - - //get the time in the file that is already encoded - preg_match_all("/time=(.*?) bitrate/", $content, $matches); - - $rawTime = array_pop($matches); - - //this is needed if there is more than one match - if (is_array($rawTime)) { - $rawTime = array_pop($rawTime); - } - - //rawTime is in 00:00:00.00 format. This converts it to seconds. - $ar = array_reverse(explode(":", $rawTime)); - $time = floatval($ar[0]); - if (!empty($ar[1])) { - $time += intval($ar[1]) * 60; - } - if (!empty($ar[2])) { - $time += intval($ar[2]) * 60 * 60; - } - - if (!empty($duration)) { - //calculate the progress - $progress = round(($time / $duration) * 100); - } else { - $progress = 'undefined'; - } - $obj->duration = $duration; - $obj->currentTime = $time; - $obj->progress = $progress; - } - return $obj; - } - - public function delete($allowOfflineUser = false) { - if (!$allowOfflineUser && !$this->userCanManageVideo()) { - return false; - } - - global $global; - if (!empty($this->id)) { - $this->removeNextVideos($this->id); - $this->removeTrailerReference($this->id); - $this->removeCampaign($this->id); - $video = self::getVideoLight($this->id); - $sql = "DELETE FROM videos WHERE id = ?"; - } else { - return false; - } - - $resp = sqlDAL::writeSql($sql, "i", array($this->id)); - if ($resp == false) { - _error_log('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - return false; - } else { - $this->removeVideoFiles(); - } - return $resp; - } - - public function removeVideoFiles() { - $filename = $this->getFilename(); - if (empty($filename)) { - return false; - } - $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); - $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); - $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); - $YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); - $cdn = AVideoPlugin::loadPluginIfEnabled('CDN'); - if (!empty($cdn)) { - $cdn_obj = $cdn->getDataObject(); - if (!empty($cdn_obj->enable_storage) && !empty($this->getSites_id())) { - CDNStorage::deleteRemoteDirectoryFromFilename($filename); - } - } - if (!empty($aws_s3)) { - $aws_s3->removeFiles($filename); - } - if (!empty($bb_b2)) { - $bb_b2->removeFiles($filename); - } - if (!empty($ftp)) { - $ftp->removeFiles($filename); - } - if (!empty($YPTStorage) && !empty($this->getSites_id())) { - $YPTStorage->removeFiles($filename, $this->getSites_id()); - } - $this->removeFiles($filename); - self::deleteThumbs($filename); - } - - private function removeNextVideos($videos_id) { - if (!$this->userCanManageVideo()) { - return false; - } - - global $global; - - if (!empty($videos_id)) { - $sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?"; - sqlDAL::writeSql($sql, "s", array($videos_id)); - } else { - return false; - } - return true; - } - - private function removeTrailerReference($videos_id) { - if (!$this->userCanManageVideo()) { - return false; - } - - global $global; - - if (!empty($videos_id)) { - $videoURL = self::getLink($videos_id, '', true); - $sql = "UPDATE videos SET trailer1 = '' WHERE trailer1 = ?"; - sqlDAL::writeSql($sql, "s", array($videoURL)); - $sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?"; - sqlDAL::writeSql($sql, "s", array($videoURL)); - $sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?"; - sqlDAL::writeSql($sql, "s", array($videoURL)); - } else { - return false; - } - return true; - } - - private function removeCampaign($videos_id) { - if (ObjectYPT::isTableInstalled('vast_campaigns_has_videos')) { - if (!empty($this->id)) { - $sql = "DELETE FROM vast_campaigns_has_videos "; - $sql .= " WHERE videos_id = ?"; - $global['lastQuery'] = $sql; - return sqlDAL::writeSql($sql, "i", array($videos_id)); - } - } - return false; - } - - private function removeFiles($filename) { - if (empty($filename)) { - return false; - } - global $global; - $file = self::getStoragePath() . "original_{$filename}"; - $this->removeFilePath($file); - - $files = self::getStoragePath() . "{$filename}"; - $this->removeFilePath($files); - } - - private function removeFilePath($filePath) { - if (empty($filePath)) { - return false; - } - // Streamlined for less coding space. - $files = glob("{$filePath}*"); - foreach ($files as $file) { - if (file_exists($file)) { - if (is_dir($file)) { - self::rrmdir($file); - } else { - @unlink($file); - } - } - } - } - - private static function rrmdir($dir) { - if (is_dir($dir)) { - $objects = scandir($dir); - foreach ($objects as $object) { - if ($object != "." && $object != "..") { - if (is_dir($dir . "/" . $object)) { - self::rrmdir($dir . "/" . $object); - } else { - unlink($dir . "/" . $object); - } - } - } - rmdir($dir); - } - } - - public function setDescription($description) { - global $global, $advancedCustom; - if (empty($advancedCustom->disableHTMLDescription)) { - $articleObj = AVideoPlugin::getObjectData('Articles'); - $configPuri = HTMLPurifier_Config::createDefault(); - $configPuri->set('Cache.SerializerPath', getCacheDir()); - $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); - //$new_description= preg_replace('/[\xE2\x80\xAF\xBA\x96]/', '', $new_description); - - if (function_exists('mb_convert_encoding')) { - $new_description = mb_convert_encoding($new_description, 'UTF-8', 'UTF-8'); - } - - $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]; - } - - $videos_getTags[$name] = self::getTags_($video_id, $type); - return $videos_getTags[$name]; - } - - 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, $getTags_; - - if (!isset($getTags_)) { - $getTags_ = array(); - } - $index = "{$video_id}_{$type}"; - if (!empty($getTags_[$index])) { - return $getTags_[$index]; - } - - TimeLogStart("video::getTags_ $video_id, $type"); - if (empty($advancedCustom)) { - $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); - } - if (empty($advancedCustom)) { - $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); - } - $currentPage = getCurrentPage(); - $rowCount = getRowCount(); - $_REQUEST['current'] = 1; - $_REQUEST['rowCount'] = 1000; - - TimeLogStart("video::getTags_ new Video $video_id, $type"); - $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 ($video->getStatus() === self::$statusFansOnly) { - $objTag->type = "warning"; - $objTag->text = ''; - $objTag->tooltip = __("Fans Only"); - } elseif ($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(); - } - TimeLogEnd("video::getTags_ new Video $video_id, $type", __LINE__, 0.5); - - /** - a = active - i = inactive - e = encoding - x = encoding error - d = downloading - u = unlisted - */ - TimeLogStart("video::getTags_ status $video_id, $type"); - 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; - case Video::$statusRecording: - $objTag->type = "danger isRecording isRecordingIcon"; - break; - default: - $objTag->type = "danger"; - break; - } - $objTag->text = $objTag->text; - $tags[] = $objTag; - $objTag = new stdClass(); - } - TimeLogEnd("video::getTags_ status $video_id, $type", __LINE__, 0.5); - - TimeLogStart("video::getTags_ userGroups $video_id, $type"); - 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(); - } - } - } - TimeLogEnd("video::getTags_ userGroups $video_id, $type", __LINE__, 0.5); - - TimeLogStart("video::getTags_ category $video_id, $type"); - 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(); - } - } - TimeLogEnd("video::getTags_ category $video_id, $type", __LINE__, 0.5); - - TimeLogStart("video::getTags_ source $video_id, $type"); - 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(); - } - } - TimeLogEnd("video::getTags_ source $video_id, $type", __LINE__, 0.5); - - TimeLogStart("video::getTags_ AVideoPlugin::getVideoTags $video_id", __LINE__, 0.5); - $array2 = AVideoPlugin::getVideoTags($video_id); - if (is_array($array2)) { - $tags = array_merge($tags, $array2); - } - TimeLogEnd("video::getTags_ AVideoPlugin::getVideoTags $video_id", __LINE__, 0.5); - //var_dump($tags); - - TimeLogEnd("video::getTags_ $video_id, $type", __LINE__, 0.5); - $_REQUEST['current'] = $currentPage; - $_REQUEST['rowCount'] = $rowCount; - $getTags_[$index] = $tags; - return $tags; - } - - public static function deleteTagsAsync($video_id) { - global $global; - return false; - if (empty($video_id)) { - return false; - } - - $name = "getVideoTags{$video_id}"; - if(class_exists('Cache')){ - Cache::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['inputAutoHLS'] = 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); - Configuration::deleteEncoderURLCache(); - 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 (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 = "{$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'); - $cdn = AVideoPlugin::loadPluginIfEnabled('CDN'); - $yptStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); - if (!empty($cdn)) { - $cdn_obj = $cdn->getDataObject(); - if (!empty($cdn_obj->enable_storage)) { - $includeS3 = true; - } - } else 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'] = $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']); - $fsize = @filesize($source['path']); - $isValidType = (preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip"); - - if (!empty($video['sites_id'])) { - $site = new Sites($video['sites_id']); - } - - if (!empty($cdn_obj->enable_storage) && $isValidType && $fsize < 20 && !empty($site) && (empty($yptStorage) || $site->getUrl() == 'url/')) { - if ($type == ".m3u8") { - $f = "{$filename}/index{$type}"; - } else { - $f = "{$paths['relative']}{$filename}{$type}"; - } - $source['url'] = CDNStorage::getURL($f) . "{$token}"; - $source['url_noCDN'] = $source['url']; - } else if (!empty($yptStorage) && !empty($site) && $isValidType && $fsize < 20) { - $siteURL = getCDNOrURL($site->getUrl(), 'CDN_YPTStorage', $video['sites_id']); - $source['url'] = "{$siteURL}{$paths['relative']}{$filename}{$type}{$token}"; - $source['url_noCDN'] = $site->getUrl() . "{$paths['relative']}{$filename}{$type}{$token}"; - if ($type == ".m3u8") { - $source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}"; - $source['url_noCDN'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; - } - } elseif (!empty($advancedCustom->videosCDN) && $canUseCDN) { - $advancedCustom->videosCDN = addLastSlash($advancedCustom->videosCDN); - $source['url'] = "{$advancedCustom->videosCDN}{$paths['relative']}{$filename}{$type}{$token}"; - $source['url_noCDN'] = "{$global['webSiteRootURL']}{$paths['relative']}{$filename}{$type}{$token}"; - if ($type == ".m3u8") { - $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}"; - $source['url_noCDN'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; - } - } else { - $source['url'] = getCDN() . "{$paths['relative']}{$filename}{$type}{$token}"; - $source['url_noCDN'] = "{$global['webSiteRootURL']}{$paths['relative']}{$filename}{$type}{$token}"; - if ($type == ".m3u8") { - $source['url'] = getCDN() . "videos/{$filename}/index{$type}{$token}"; - $source['url_noCDN'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; - } - } - /* need it because getDurationFromFile */ - if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf" || $type == ".zip")) { - if (file_exists($source['path']) && filesize($source['path']) < 1024) { - if (!empty($cdn_obj->enable_storage)) { - $source['url'] = CDNStorage::getURL("{$filename}{$type}"); - $source['url_noCDN'] = $source['url']; - } else if (!empty($aws_s3)) { - $source = $aws_s3->getAddress("{$filename}{$type}"); - $source['url_noCDN'] = $source['url']; - $source['url'] = replaceCDNIfNeed($source['url'], 'CDN_S3'); - } elseif (!empty($bb_b2)) { - $source = $bb_b2->getAddress("{$filename}{$type}"); - $source['url_noCDN'] = $source['url']; - $source['url'] = replaceCDNIfNeed($source['url'], 'CDN_B2'); - } elseif (!empty($ftp)) { - $source = $ftp->getAddress("{$filename}{$type}"); - $source['url_noCDN'] = $source['url']; - $source['url'] = replaceCDNIfNeed($source['url'], 'CDN_FTP'); - } - } - } - 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); - //if($type=='.jpg'){echo '----'.PHP_EOL;var_dump($type, $source);echo '----'.PHP_EOL;}; - //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']) . filectime($source['path']); - } elseif (!empty($video)) { - $x = strtotime($video['modified']); - } - $source['url'] = addQueryStringParameter($source['url'], 'cache', $x); - $source['url_noCDN'] = addQueryStringParameter($source['url_noCDN'], 'cache', $x); - } - //ObjectYPT::setCache($name, $source); - $VideoGetSourceFile[$cacheName] = $source; - return $VideoGetSourceFile[$cacheName]; - } - - 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(); - make_path($paths['path']); - $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, $createDir = false) { - global $global, $__getPaths; - if (!isset($__getPaths)) { - $__getPaths = array(); - } - if (!empty($__getPaths[$videoFilename])) { - return $__getPaths[$videoFilename]; - } - $cleanVideoFilename = self::getCleanFilenameFromFile($videoFilename); - $videosDir = self::getStoragePath(); - - $path = addLastSlash("{$videosDir}{$cleanVideoFilename}"); - - $path = fixPath($path); - if ($createDir) { - make_path(addLastSlash($path)); - } - $relative = addLastSlash("videos/{$cleanVideoFilename}"); - $url = getCDN() . "{$relative}"; - $__getPaths[$videoFilename] = array('filename' => $cleanVideoFilename, 'path' => $path, 'url' => $url, 'relative' => $relative); - return $__getPaths[$videoFilename]; - } - - public static function getPathToFile($videoFilename, $createDir = false) { - $videosDir = self::getStoragePath(); - $videoFilename = str_replace($videosDir, '', $videoFilename); - $paths = Video::getPaths($videoFilename, $createDir); - if (preg_match('/index.m3u8$/', $videoFilename)) { - $paths['path'] = rtrim($paths['path'], DIRECTORY_SEPARATOR); - $videoFilename = str_replace($paths['filename'], '', $videoFilename); - } - return "{$paths['path']}{$videoFilename}"; - } - - public static function getURLToFile($videoFilename, $createDir = false) { - $videosDir = self::getStoragePath(); - $videoFilename = str_replace($videosDir, '', $videoFilename); - $paths = Video::getPaths($videoFilename, $createDir); - $parts = explode('/', $videoFilename); - if (!empty($parts[1]) && $parts[1] == 'index.m3u8') { - $videoFilename = $parts[1]; - } - 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}_v{$uid}"); - return self::getPaths($videoFilename); - } - - public static function isNewVideoFilename($filename) { - $filename = self::getCleanFilenameFromFile($filename); - return preg_match('/_([0-9]{12})_([0-9a-z]{4})$/i', $filename); - } - - 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; - } - - if (isAnyStorageEnabled()) { - $newFilename = self::getPaths($video['filename']); - $id = $video['id']; - } else { - $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); - $filename = str_replace(getVideosDir(), '', $filename); - if (preg_match('/videos[\/\\\]([^\/\\\]+)[\/\\\].*index.m3u8$/', $filename, $matches)) { - return $matches[1]; - } - $search = array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2', '_spectrum', '_tvg', '.notfound'); - - if (!empty($global['langs_codes_values_withdot']) && is_array($global['langs_codes_values_withdot'])) { - $search = array_merge($search, $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}"; - - $search[] = "res{$value}"; - } - $cleanName = str_replace($search, '', $filename); - - if ($cleanName == $filename) { - $cleanName = preg_replace('/([a-z]+_[0-9]{12}_[a-z0-9]{4})_[0-9]+/', '$1', $filename); - } - - $path_parts = pathinfo($cleanName); - 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') { - $parts = explode(DIRECTORY_SEPARATOR, $cleanName); - if (!empty($parts[0])) { - return $parts[0]; - } - return $parts[1]; - } 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); - - $return = array(); - - $cacheName = "getHigestResolution($filename)"; - $return = ObjectYPT::getSessionCache($cacheName, 0); - if (!empty($return)) { - return object_to_array($return); - } - $name0 = "Video:::getHigestResolution($filename)"; - TimeLogStart($name0); - $name1 = "Video:::getHigestResolution::getVideosURL_V2($filename)"; - TimeLogStart($name1); - - $v = self::getVideoFromFileNameLight($filename); - if (empty($v)) { - return array(); - } - if ($v['type'] !== 'video') { - return array(); - } - if ($v['status'] !== self::$statusActive && $v['status'] !== self::$statusUnlisted) { - return array(); - } - $video = new Video('', '', $v['id']); - if (empty($video)) { - return array(); - } - $HigestResolution = $video->getVideoHigestResolution(); - //_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) 1 FROM database $HigestResolution"); - if (!empty($HigestResolution)) { - //_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) 2 FROM database $HigestResolution"); - $resolution = $HigestResolution; - - $return['resolution'] = $resolution; - $return['resolution_text'] = getResolutionText($return['resolution']); - $return['resolution_label'] = getResolutionLabel($return['resolution']); - $return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}"); - return $return; - } else { - $validFileExtensions = array('webm', 'mp4', 'm3u8'); - $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__); - foreach ($sources as $key => $value) { - $ext = pathinfo($value["path"], PATHINFO_EXTENSION); - if (!in_array($ext, $validFileExtensions)) { - continue; - } - 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 - //var_dump(2, $filename, $resolution); - if (empty($resolution) && empty($global['onlyGetResolutionFromFilename'])) { - $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']}"); - } - } - } - } - _error_log("Video:::getHigestResolution::getVideosURL_V2($filename) 3 FROM database " . $return['resolution'] . ' - ' . $v['path']); //exit; - //if($filename=='video_210916143432_c426'){var_dump(1, $filename, $return);exit;} - $video->setVideoHigestResolution($return['resolution']); - TimeLogEnd($name0, __LINE__); - ObjectYPT::setSessionCache($cacheName, $return); - return $return; - } - - public static function getResolutionFromFilename($filename) { - global $global; - $resolution = false; - if (preg_match("/_([0-9]+).(mp4|webm)/i", $filename, $matches)) { - if (!empty($matches[1])) { - $resolution = intval($matches[1]); - } - //var_dump(__LINE__); - } elseif (preg_match('/res([0-9]+)\/index.m3u8/i', $filename, $matches)) { - if (!empty($matches[1])) { - $resolution = intval($matches[1]); - } - //var_dump(__LINE__); - } elseif (preg_match('/_(HD|Low|SD).(mp4|webm)/i', $filename, $matches)) { - if (!empty($matches[1])) { - if ($matches[1] == 'HD') { - $resolution = 1080; - } else if ($matches[1] == 'SD') { - $resolution = 720; - } else if ($matches[1] == 'Low') { - $resolution = 480; - } - } - //var_dump(__LINE__); - } elseif (preg_match('/\/(hd|low|sd)\/index.m3u8/', $filename, $matches)) { - if (!empty($matches[1])) { - if ($matches[1] == 'hd') { - $resolution = 1080; - } else if ($matches[1] == 'sd') { - $resolution = 720; - } else if ($matches[1] == 'low') { - $resolution = 480; - } - } - //var_dump(__LINE__); - } elseif (preg_match('/video_[0-9_a-z]+\/index.m3u8/i', $filename)) { - if (class_exists('VideoHLS')) { - $resolution = VideoHLS::getHLSHigestResolutionFromFile($filename); - //var_dump(5, $filename,$resolution); - } - //var_dump(__LINE__); - } - //echo PHP_EOL.PHP_EOL;var_dump(__LINE__, preg_match('/video_[0-9_a-z]+\/index.m3u8/i', $filename), $filename, $resolution, $matches);echo PHP_EOL.PHP_EOL; - //if($filename=='video_210916143432_c426'){var_dump(3, $filename, $resolution, $matches);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 getSourceFileURL($filename, $includeS3 = false) { - $sources = self::getVideosPaths($filename, $includeS3); - if (!empty($sources['mp3'])) { - return $sources['mp3']; - } - if (!empty($sources['webm'])) { - return end($sources['webm']); - } - if (!empty($sources['m3u8']) && !empty($sources['m3u8']['url'])) { - return $sources['m3u8']['url']; - } - if (!empty($sources['mp4'])) { - return end($sources['mp4']); - } - return false; - } - - public static function getVideosPaths($filename, $includeS3 = false) { - global $global, $_getVideosPaths; - - $cacheName = "getVideosPaths_$filename" . ($includeS3 ? 1 : 0); - $cache = ObjectYPT::getCache($cacheName, 0); - //var_dump($cacheName, $cache, _json_decode($cache));//exit; - if (!empty($cache)) { - return object_to_array(_json_decode($cache)); - } - - $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']; - } - $c = ObjectYPT::setCache($cacheName, $videos); - //var_dump($cacheName, $c);exit; - 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 (!$async) { - return self::getImageFromFilename_($filename, $type); - } else { - return self::getImageFromFilenameAsync($filename, $type); - } - } - - public static function getPoster($videos_id) { - global $_getPoster; - if (!isset($_getPoster)) { - $_getPoster = array(); - } - if (isset($_getPoster[$videos_id])) { - return $_getPoster[$videos_id]; - } - $images = self::getImageFromID($videos_id); - $_getPoster[$videos_id] = false; - if (!empty($images->poster)) { - $_getPoster[$videos_id] = $images->poster; - } else if (!empty($images->posterPortrait)) { - $_getPoster[$videos_id] = $images->posterPortrait; - } - return $_getPoster[$videos_id]; - } - - 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)) { - $relativePath = str_replace($global['systemRootPath'], '', $rokuImage); - return getURL($relativePath); - } - return getURL("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 1 {$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 2 {$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) { - if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { - //_error_log("Resize JPG 3 useFFMPEGToGenerateThumbs {$jpegSource['path']}, {$thumbsSource['path']}"); - im_resizeV3($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); - } else { - //_error_log("Resize JPG 3 {$jpegSource['path']}, {$thumbsSource['path']}"); - im_resizeV2($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); - } - } - // create thumbs - if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) { - if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { - //_error_log("Resize Small JPG 4 useFFMPEGToGenerateThumbs {$jpegSource['path']}, {$thumbsSmallSource['path']}"); - im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); - } else { - //_error_log("Resize Small JPG 4 {$jpegSource['path']}, {$thumbsSmallSource['path']}"); - 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 (!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()); - if(empty($return->posterLandscapePath)){ - $path = Video::getPaths($video->getFilename()); - $return->posterLandscapePath = "{$path['path']}{$path['filename']}.jpg"; - $return->posterLandscape = "{$path['url']}{$path['filename']}.jpg"; - } - if(empty($return->posterPortraitPath)){ - $path = Video::getPaths($video->getFilename()); - $return->posterPortraitPath = "{$path['path']}{$path['filename']}_portrait.jpg"; - $return->posterPortrait = "{$path['url']}{$path['filename']}_portrait.jpg"; - } - return $return; - } - - 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(), $ignoreChannelname = false) { - global $global, $advancedCustomUser, $advancedCustom; - if (!empty($_GET['evideo'])) { - $v = self::decodeEvideo(); - if (!empty($v['video']['videoLink'])) { - if ($embed) { - return parseVideos($v['video']['videoLink'], $advancedCustom->embedAutoplay, $advancedCustom->embedLoop, $advancedCustom->embedStartMuted, $advancedCustom->embedShowinfo, $advancedCustom->embedControls->value); - } else { - return $v['video']['videoLink']; - } - } - } - - if (!is_object($advancedCustomUser)) { - $advancedCustomUser = AVideoPlugin::getDataObject('CustomizeUser'); - } - if (empty($advancedCustom)) { - $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); - } - if (empty($videos_id) && !empty($clean_title)) { - $videos_id = self::get_id_from_clean_title($clean_title); - } - $video = new Video("", "", $videos_id); - - if (!$ignoreChannelname && $advancedCustomUser->addChannelNameOnLinks) { - $get['channelName'] = $video->getChannelName(); - }else if($ignoreChannelname){ - $get['channelName'] = null; - } - - unset($get['v'], $get['videoName'], $get['videoName'], $get['isMediaPlaySite'], $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)) { - $url = "{$global['webSiteRootURL']}{$subEmbedDir}/{$clean_title}{$get_http}"; - } else { - $url = "{$global['webSiteRootURL']}{$subEmbedDir}/{$videos_id}/{$clean_title}{$get_http}"; - } - return parseVideos($url, $advancedCustom->embedAutoplay, $advancedCustom->embedLoop, $advancedCustom->embedStartMuted, $advancedCustom->embedShowinfo, $advancedCustom->embedControls->value); - } 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) { - $url = "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}"; - return parseVideos($url, $advancedCustom->embedAutoplay, $advancedCustom->embedLoop, $advancedCustom->embedStartMuted, $advancedCustom->embedShowinfo, $advancedCustom->embedControls->value); - } 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 getTotalVideosThumbsUpFromUserFromVideos($users_id) { - global $global; - - $sql = "SELECT sum(likes) as thumbsUp, sum(dislikes) as thumbsDown 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) { - $r['thumbsUp'] += intval($row['thumbsUp']); - $r['thumbsDown'] += intval($row['thumbsDown']); - } - } - return $r; - } - - public static function deleteThumbs($filename, $doNotDeleteSprit = false, $checkIfIsCorrupted = false) { - if (empty($filename)) { - return false; - } - global $global; - - $filePath = Video::getPathToFile($filename); - // Streamlined for less coding space. - $files = glob("{$filePath}*_thumbs*.jpg"); - $files[] = "{$filePath}_roku.jpg"; - $totalDeleted = 0; - foreach ($files as $file) { - if (file_exists($file)) { - if($checkIfIsCorrupted && !isImageCorrupted($file)){ - continue; - } - if ($doNotDeleteSprit && strpos($file, '_thumbsSprit.jpg') !== false) { - continue; - } - if (isCommandLineInterface()) { - echo "Deleting {$file} ". humanFileSize(filesize($file)).PHP_EOL; - } - @unlink($file); - $totalDeleted++; - } - } - if($totalDeleted){ - 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 $totalDeleted; - } - - public static function deleteGifAndWebp($filename) { - if (empty($filename)) { - return false; - } - global $global; - - $filePath = Video::getPathToFile($filename); - @unlink("{$filePath}.gif"); - @unlink("{$filePath}.webp"); - 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("PlayeSkins_getVideoTags{$videos_id}"); - ObjectYPT::deleteCache("_getVideoInfo_{$videos_id}"); - 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")); - if(class_exists('Cache')){ - Cache::deleteCache("getSourceFile($filename)1"); - Cache::deleteCache("getSourceFile($filename)0"); - Cache::deleteCache("getVideosPaths_($filename)1"); - Cache::deleteCache("getVideosPaths_($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) { - if ($fileName == '.zip') { - return false; - } - _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); - //var_dump($paths);exit; - $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); - if(!is_string($externalOptions)){ - $externalOptions = _json_encode($externalOptions); - } - $this->externalOptions = $externalOptions; - } - - public function setVideoTags($tags) { - $externalOptions = _json_decode($this->getExternalOptions()); - if (!is_object($externalOptions)) { - $externalOptions = new stdClass(); - } - $externalOptions->VideoTags = $tags; - $this->setExternalOptions(json_encode($externalOptions)); - } - - public function getVideoTags() { - $externalOptions = _json_decode($this->getExternalOptions()); - if (empty($externalOptions->VideoTags)) { - return false; - } - return $externalOptions->VideoTags; - } - - public function setVideoHigestResolution($HigestResolution) { - $externalOptions = _json_decode($this->getExternalOptions()); - if (!is_object($externalOptions)) { - $externalOptions = new stdClass(); - } - $externalOptions->HigestResolution = $HigestResolution; - $this->setExternalOptions(json_encode($externalOptions)); - return $this->save(false, true); - } - - public function getVideoHigestResolution() { - $externalOptions = _json_decode($this->getExternalOptions()); - if (empty($externalOptions->HigestResolution)) { - return false; - } - return $externalOptions->HigestResolution; - } - - public function setVideoStartSeconds($videoStartSeconds) { - $externalOptions = _json_decode($this->getExternalOptions()); - AVideoPlugin::onVideoSetVideoStartSeconds($this->id, $this->videoStartSeconds, $videoStartSeconds); - $externalOptions->videoStartSeconds = intval($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)); - $search = str_replace('"', '"', $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}"; - } - - static function canVideoBePurchased($videos_id) { - global $global; - $obj = new stdClass(); - $obj->plugin = ''; - $obj->buyURL = ''; - $obj->canVideoBePurchased = false; - // check for Subscription plugin - if (AVideoPlugin::isEnabledByName('Subscription')) { - $sub = new Subscription(); - $plans = $sub->getPlansFromVideo($videos_id); - if (!empty($plans)) { - $obj->plugin = 'Subscription'; - $obj->buyURL = "{$global['webSiteRootURL']}plugin/Subscription/showPlans.php?videos_id={$videos_id}"; - $obj->canVideoBePurchased = true; - return $obj; - } - } - - // check for PPV plugin - if (AVideoPlugin::isEnabledByName('PayPerView')) { - if (PayPerView::isVideoPayPerView($videos_id) || $obj->onlyPlayVideosWithPayPerViewActive) { - $url = "{$global['webSiteRootURL']}plugin/PayPerView/page/buy.php"; - if (isSerie()) { - $redirectUri = getSelfURI(); - } else { - $redirectUri = getRedirectToVideo($videos_id); - } - if (!empty($redirectUri)) { - $url = addQueryStringParameter($url, 'redirectUri', $redirectUri); - } - $url = addQueryStringParameter($url, 'videos_id', $videos_id); - $obj->plugin = 'PayPerView'; - $obj->buyURL = $url; - $obj->canVideoBePurchased = true; - return $obj; - } - } - - // check for fansSubscription - if (AVideoPlugin::isEnabledByName('FansSubscriptions')) { - if (FansSubscriptions::hasPlansFromVideosID($videos_id)) { - $url = "{$global['webSiteRootURL']}plugin/FansSubscriptions/View/buy.php"; - if (isSerie()) { - $redirectUri = getSelfURI(); - } else { - $redirectUri = getRedirectToVideo($videos_id); - } - if (!empty($redirectUri)) { - $url = addQueryStringParameter($url, 'redirectUri', $redirectUri); - } - $url = addQueryStringParameter($url, 'videos_id', $videos_id); - $obj->plugin = 'FansSubscriptions'; - $obj->buyURL = $url; - $obj->canVideoBePurchased = true; - return $obj; - } - } - return false; - } - - static function getCreatorHTML($users_id, $html = '', $small = false, $ignoreLinks=false) { - global $global; - if ($small) { - $template = $global['systemRootPath'] . 'view/videoCreatorSmall.html'; - } else { - $template = $global['systemRootPath'] . 'view/videoCreator.html'; - } - - require_once $global['systemRootPath'] . 'objects/subscribe.php'; - $content = local_get_contents($template); - $name = User::getNameIdentificationById($users_id); - - $search = array( - '{photo}', - '{channelLink}', - '{name}', - '{icon}', - '{subscriptionButton}', - '{html}'); - - if($ignoreLinks){ - $channelLink = '#'; - }else{ - $channelLink = User::getChannelLink($users_id); - } - - $replace = array( - User::getPhoto($users_id), - $channelLink, - strip_tags($name), - User::getEmailVerifiedIcon($users_id), - Subscribe::getButton($users_id), - $html - ); - - $btnHTML = str_replace($search, $replace, $content); - return $btnHTML; - } - - static function getVideosListItem($videos_id, $divID = '', $style = '') { - global $global, $advancedCustom; - $get = array(); - $get = array('channelName' => @$_GET['channelName'], 'catName' => @$_GET['catName']); - - if (empty($divID)) { - $divID = "divVideo-{$videos_id}"; - } - $objGallery = AVideoPlugin::getObjectData("Gallery"); - $program = AVideoPlugin::loadPluginIfEnabled('PlayLists'); - $template = $global['systemRootPath'] . 'view/videosListItem.html'; - $templateContent = file_get_contents($template); - $value = Video::getVideoLight($videos_id); - $link = Video::getLink($value['id'], $value['clean_title'], "", $get); - if (!empty($_GET['page']) && $_GET['page'] > 1) { - $link = addQueryStringParameter($link, 'page', $_GET['page']); - } - - $title = $value['title']; - - $images = Video::getImageFromFilename($value['filename'], $value['type']); - - if (!is_object($images)) { - $images = new stdClass(); - $images->thumbsGif = ""; - $images->poster = getCDN() . "view/img/notfound.jpg"; - $images->thumbsJpg = getCDN() . "view/img/notfoundThumbs.jpg"; - $images->thumbsJpgSmall = getCDN() . "view/img/notfoundThumbsSmall.jpg"; - } - $imgJPGLow = $images->thumbsJpgSmall; - $imgJPGHight = $images->thumbsJpg; - $imgGif = $images->thumbsGif; - $imgGifHTML = ''; - - if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { - $imgGif = $images->gifPortrait; - $imgJPGHight = $images->posterPortrait; - } - if (!empty($imgGif)) { - $imgGifHTML = ''; - } - - $timeHTML = ''; - if (isToShowDuration($value['type'])) { - $timeHTML = ''; - } - - $loggedUserHTML = ''; - if (User::isLogged() && !empty($program)) { - $value['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); - $value['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); - if (!empty($value['isWatchLater'])) { - $watchLaterBtnAddedStyle = ""; - $watchLaterBtnStyle = "display: none;"; - } else { - $watchLaterBtnAddedStyle = "display: none;"; - $watchLaterBtnStyle = ""; - } - if (!empty($value['isFavorite'])) { - $favoriteBtnAddedStyle = ""; - $favoriteBtnStyle = "display: none;"; - } else { - $favoriteBtnAddedStyle = "display: none;"; - $favoriteBtnStyle = ""; - } - $loggedUserHTML = '
'; - $loggedUserHTML .= ' '; - $loggedUserHTML .= ''; - $loggedUserHTML .= '
'; - $loggedUserHTML .= ' '; - $loggedUserHTML .= ' '; - $loggedUserHTML .= '
'; - } - $progress = self::getVideoPogressPercent($value['id']); - $category = new Category($value['categories_id']); - - $categoryLink = $category->getLink(); - $categoryIcon = $category->getIconClass(); - $category = $category->getName(); - $tagsHTML = ''; - $tagsWhitelist = array(__("Paid Content"), __("Group"), __("Plugin")); - if (!empty($objGallery->showTags) && !empty($value['tags']) && is_array($value['tags'])) { - foreach ($value['tags'] as $value2) { - if (!empty($value2->label) && in_array($value2->label, $tagsWhitelist)) { - $tagsHTML .= '' . $value2->text . ''; - } - } - } - $viewsHTML = ''; - - if (empty($advancedCustom->doNotDisplayViews)) { - if (AVideoPlugin::isEnabledByName('LiveUsers')) { - $viewsHTML = '
' . getLiveUsersLabelVideo($value['id'], $value['views_count']) . '
'; - } else { - $viewsHTML = '
' . number_format($value['views_count'], 0) . '
'; - } - } - $creator = self::getCreatorHTML($value['users_id'], '', true); - - - $search = array( - '{style}', - '{divID}', - '{link}', - '{title}', - '{imgJPGLow}', - '{imgJPGHight}', - '{imgGifHTML}', - '{timeHTML}', - '{loggedUserHTML}', - '{progress}', - '{categoryLink}', - '{categoryIcon}', - '{category}', - '{tagsHTML}', - '{viewsHTML}', - '{creator}'); - - $replace = array( - $style, - $divID, - $link, - $title, - $imgJPGLow, - $imgJPGHight, - $imgGifHTML, - $timeHTML, - $loggedUserHTML, - $progress, - $categoryLink, - $categoryIcon, - $category, - $tagsHTML, - $viewsHTML, - $creator - ); - $btnHTML = @str_replace( - $search, - $replace, - $templateContent - ); - return $btnHTML; - } - - function getTotal_seconds_watching() { - return $this->total_seconds_watching; - } - - function setTotal_seconds_watching($total_seconds_watching) { - $this->total_seconds_watching = $total_seconds_watching; - } - - function getDuration_in_seconds() { - return $this->duration_in_seconds; - } - - function setDuration_in_seconds($duration_in_seconds) { - $this->duration_in_seconds = intval($duration_in_seconds); - } - - function getLikes() { - return $this->likes; - } - - function getDislikes() { - return $this->dislikes; - } - - function setLikes($likes): void { - $this->likes = intval($likes); - } - - function setDislikes($dislikes): void { - $this->dislikes = intval($dislikes); - } - - /** - * - * @param type $videos_id - * @param type $type [like or dislike] - * @param type $value - * @return boolean - * - * automatic = will get from like table - * +1 = add one - * -1 = remove one - * any number = will change the database - */ - public static function updateLikesDislikes($videos_id, $type, $value = 'automatic') { - global $config, $global, $_updateLikesDislikes; - if ($config->currentVersionLowerThen('11.5')) { - return false; - } - - $index = "$videos_id, $type, $value"; - if(!isset($_updateLikesDislikes)){ - $_updateLikesDislikes = array(); - } - - if(isset($_updateLikesDislikes[$index])){ - return $_updateLikesDislikes[$index]; - } - - require_once $global['systemRootPath'] . 'objects/like.php'; - $videos_id = intval($videos_id); - if (empty($videos_id)) { - return false; - } - - if (strtolower($type) == 'likes') { - $type = 'likes'; - } else { - $type = 'dislikes'; - } - //var_dump($videos_id, $type, $value); - $sql = "UPDATE videos SET "; - if ($value === 'automatic') { - $likes = Like::getLikes($videos_id); - return self::updateLikesDislikes($videos_id, $type, $likes->$type); - } else if (preg_match('/\+([0-9]+)/', $value, $matches)) { - $value = intval($matches[1]); - $sql .= " {$type} = {$type}+{$value} "; - } else if (preg_match('/-([0-9]+)/', $value, $matches)) { - $value = intval($matches[1]); - $sql .= " {$type} = {$type}-{$value} "; - } else { - $value = intval($value); - $sql .= " {$type} = {$value} "; - } - $sql .= ", modified = now() WHERE id = {$videos_id}"; - //secho $sql.PHP_EOL; - $saved = sqlDAL::writeSql($sql); - self::clearCache($videos_id); - $_updateLikesDislikes[$index] = $value; - return $value; - } - - static function checkIfIsBroken($videos_id) { - $video = new Video('', '', $videos_id); - if ($video->getStatus() == Video::$statusActive || $video->getStatus() == Video::$statusUnlisted) { - if ($video->getType() == 'audio' || $video->getType() == 'video') { - if (self::isMediaFileMissing($video->getFilename())) { - _error_log("Video::checkIfIsBroken($videos_id) true ".$video->getFilename()); - $video->setStatus(Video::$statusBrokenMissingFiles); - Video::clearCache($videos_id); - return true; - } - } - } - return false; - } - - public static function isMediaFileMissing($filename, $cacheCleared = false) { - $sources = getVideosURL_V2($filename); - $search = array('mp3', 'mp4', 'm3u8', 'webm'); - $found = false; - foreach ($sources as $key => $value1) { - foreach ($search as $value2) { - if (preg_match("/^{$value2}/i", $key)) { - $found = true; - break 2; - } - } - } - - if(!$cacheCleared && !$found){ - global $getVideosURL_V2Array; - ObjectYPT::deleteCache("getVideosURL_V2$filename"); - unset($getVideosURL_V2Array); - return self::isMediaFileMissing($filename, true); - } - - return !$found; - } - - } - -} -// Just to convert permalink into clean_title -if (!empty($_GET['v']) && empty($_GET['videoName'])) { - $_GET['videoName'] = Video::get_clean_title($_GET['v']); -} + 'Active', + 'k' => 'Active and Encoding', + 'i' => 'Inactive', + 'e' => 'Encoding', + 'x' => 'Encoding Error', + 'd' => 'Downloading', + 't' => 'Transferring', + 'u' => 'Unlisted', + 'r' => 'Recording', + 'f' => 'FansOnly', + 'b' => 'Broken Missing files', ]; + public static $statusIcons = [ + 'a' => '', + 'k' => '', + 'i' => '', + 'e' => '', + 'x' => '', + 'd' => '', + 't' => '', + 'u' => '', + 'r' => '', + 'f' => '', + 'b' => '', ]; + public static $statusActive = 'a'; + public static $statusActiveAndEncoding = 'k'; + public static $statusInactive = 'i'; + public static $statusEncoding = 'e'; + public static $statusEncodingError = 'x'; + public static $statusDownloading = 'd'; + public static $statusTranfering = 't'; + public static $statusUnlisted = 'u'; + public static $statusRecording = 'r'; + public static $statusFansOnly = 'f'; + public static $statusBrokenMissingFiles = 'b'; + public static $rratingOptions = ['', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma']; + //ver 3.4 + private $youtubeId; + public static $typeOptions = ['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", [$this->id]); + + if ($insert_row) { + $obj = new stdClass(); + $obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime); + $obj->videos_id = $this->id; + $this->views_count++; + AVideoPlugin::addView($this->id, $this->views_count); + return $obj; + } + die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + + public function addSecondsWatching($seconds_watching) + { + global $global; + + $seconds_watching = intval($seconds_watching); + + if (empty($seconds_watching)) { + return false; + } + + if (empty($this->id)) { + return false; + } + $sql = "UPDATE videos SET total_seconds_watching = total_seconds_watching+{$seconds_watching}, modified = now() WHERE id = ?"; + //_error_log($sql."={$this->id}"); + return sqlDAL::writeSql($sql, "i", [$this->id]); + } + + public function updateViewsCount($total) + { + global $global; + if (empty($this->id)) { + return false; + } + $total = intval($total); + if ($total < 0) { + return false; + } + $sql = "UPDATE videos SET views_count = {$total}, modified = now() WHERE id = ?"; + + $insert_row = sqlDAL::writeSql($sql, "i", [$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", [$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; + } + } + + public function getLive_transmitions_history_id() + { + return $this->live_transmitions_history_id; + } + + public function setLive_transmitions_history_id($live_transmitions_history_id) + { + AVideoPlugin::onVideoSetLive_transmitions_history_id($this->id, $this->live_transmitions_history_id, intval($live_transmitions_history_id)); + $this->live_transmitions_history_id = intval($live_transmitions_history_id); + } + + public function getEncoderURL() + { + return $this->encoderURL; + } + + public function getFilepath() + { + return $this->filepath; + } + + public function getFilesize() + { + return intval($this->filesize); + } + + public function setEncoderURL($encoderURL) + { + if (filter_var($encoderURL, FILTER_VALIDATE_URL) !== false) { + AVideoPlugin::onVideoSetEncoderURL($this->id, $this->encoderURL, $encoderURL); + $this->encoderURL = $encoderURL; + } + } + + public function setFilepath($filepath) + { + AVideoPlugin::onVideoSetFilepath($this->id, $this->filepath, $filepath); + $this->filepath = $filepath; + } + + public function setFilesize($filesize) + { + AVideoPlugin::onVideoSetFilesize($this->id, $this->filesize, $filesize); + $this->filesize = intval($filesize); + } + + public function setUsers_id($users_id) + { + AVideoPlugin::onVideoSetUsers_id($this->id, $this->users_id, $users_id); + $this->users_id = $users_id; + } + + public function getSites_id() + { + return $this->sites_id; + } + + public function setSites_id($sites_id) + { + AVideoPlugin::onVideoSetSites_id($this->id, $this->sites_id, $sites_id); + $this->sites_id = $sites_id; + } + + public function getVideo_password() + { + return trim($this->video_password); + } + + public function setVideo_password($video_password) + { + AVideoPlugin::onVideoSetVideo_password($this->id, $this->video_password, $video_password); + $this->video_password = trim($video_password); + } + + public function save($updateVideoGroups = false, $allowOfflineUser = false) + { + global $advancedCustom; + global $global; + if (!User::isLogged() && !$allowOfflineUser) { + _error_log('Video::save permission denied to save'); + return false; + } + if (empty($this->title)) { + $this->title = uniqid(); + } + + $this->clean_title = substr($this->clean_title, 0, 187); + + if (empty($this->clean_title)) { + $this->setClean_title($this->title); + } + $this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id); + + if (empty($this->status)) { + $this->status = 'e'; + } + + if (empty($this->type) || !in_array($this->type, self::$typeOptions)) { + $this->type = 'video'; + } + + if (empty($this->isSuggested)) { + $this->isSuggested = 0; + } else { + $this->isSuggested = 1; + } + + if (empty($this->categories_id)) { + $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); + $category = Category::getCategoryDefault(); + $categories_id = $category['id']; + if (empty($categories_id)) { + $categories_id = 'NULL'; + } + if ($p) { + $this->categories_id = $p->getCategoryId(); + } else { + $this->categories_id = $categories_id; + } + if (empty($this->categories_id)) { + $this->categories_id = $categories_id; + } + } + // check if category exists + $cat = new Category($this->categories_id); + if (empty($cat->getName())) { + $catDefault = Category::getCategoryDefault(); + $this->categories_id = $catDefault['id']; + } + $this->setTitle($global['mysqli']->real_escape_string(trim($this->title))); + $this->description = ($global['mysqli']->real_escape_string($this->description)); + + if (forbiddenWords($this->title) || forbiddenWords($this->description)) { + return false; + } + + if (empty($this->users_id)) { + $this->users_id = User::getId(); + } + + $this->next_videos_id = intval($this->next_videos_id); + if (empty($this->next_videos_id)) { + $this->next_videos_id = 'NULL'; + } + + $this->sites_id = intval($this->sites_id); + if (empty($this->sites_id)) { + $this->sites_id = 'NULL'; + } + + $this->serie_playlists_id = intval($this->serie_playlists_id); + if (empty($this->serie_playlists_id)) { + $this->serie_playlists_id = 'NULL'; + } + + if (empty($this->filename)) { + $prefix = $this->type; + if (empty($prefix)) { + $prefix = 'v'; + } + $paths = self::getNewVideoFilename($prefix); + $this->filename = $paths['filename']; + } + + $this->can_download = intval($this->can_download); + $this->can_share = intval($this->can_share); + $this->only_for_paid = intval($this->only_for_paid); + $this->filesize = intval($this->filesize); + + $this->rate = floatval($this->rate); + + if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) { + $this->videoLink = ''; + if ($this->type == 'embed') { + $this->type = 'video'; + } + } + + if (empty($this->live_transmitions_history_id)) { + $this->live_transmitions_history_id = 'NULL'; + } + + if (empty($this->duration_in_seconds)) { + $this->duration_in_seconds = durationToSeconds($this->duration); + } + + 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}' , duration_in_seconds = '{$this->duration_in_seconds}' , modified = now()" + . " WHERE id = {$this->id}"; + + $saved = sqlDAL::writeSql($sql); + if ($saved) { + $insert_row = $this->id; + } + } else { + $sql = "INSERT INTO videos " + . "(duration_in_seconds, 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->duration_in_seconds}','{$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}"); + if (class_exists('Cache')) { + Cache::deleteCache("getVideoTags{$this->id}"); + } + self::deleteTagsAsync($this->id); + if ($updateVideoGroups) { + require_once $global['systemRootPath'] . 'objects/userGroups.php'; + // update the user groups + UserGroups::updateVideoGroups($id, $this->videoGroups); + } + + // I am not sure what is it for + //Video::autosetCategoryType($id); + if (!empty($this->old_categories_id)) { + //Video::autosetCategoryType($this->old_categories_id); + } + self::clearCache($this->id); + return $id; + } + _error_log('Video::save Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); + return false; + } + + public static function updateDurationInSeconds($videos_id, $duration) + { + global $config; + $videos_id = intval($videos_id); + if ($config->currentVersionLowerThen('11.4')) { + return false; + } + if (empty($videos_id)) { + return false; + } + $duration_in_seconds = durationToSeconds($duration); + if (empty($duration_in_seconds)) { + _error_log("Video::updateDurationInSeconds empty duration {$videos_id}, {$duration}"); + return false; + } + _error_log("Video::updateDurationInSeconds update duration {$videos_id}, {$duration}, {$duration_in_seconds}"); + $sql = "UPDATE videos SET duration_in_seconds = '{$duration_in_seconds}' , modified = now() WHERE id = {$videos_id}"; + $saved = sqlDAL::writeSql($sql); + self::clearCache($videos_id); + return $duration_in_seconds; + } + + // 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", [$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", [$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", [$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 [$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', [$status, $this->id]); + if ($global['mysqli']->errno != 0) { + die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + self::clearCache($this->id); + if ($this->status==Video::$statusActive || $status==Video::$statusActive && ($this->status != $status)) { + clearCache(true); + } + } + 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 ""; + } + + if (self::allowFreePlayWithAdsIsEnabled()) { + $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 = []; + 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 allowFreePlayWithAdsIsEnabled() + { + $obj = AVideoPlugin::getDataObjectIfEnabled('Subscription'); + if ($obj && $obj->allowFreePlayWithAds) { + return true; + } + $obj = AVideoPlugin::getDataObjectIfEnabled('PayPerView'); + if ($obj && $obj->allowFreePlayWithAds) { + return true; + } + $obj = AVideoPlugin::getDataObjectIfEnabled('FansSubscriptions'); + if ($obj && $obj->allowFreePlayWithAds) { + return true; + } + return false; + } + + public static function getUserGroups($videos_id) + { + return UserGroups::getVideoGroups($videos_id); + } + + public static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true) + { + global $global, $config, $advancedCustom, $advancedCustomUser; + if ($config->currentVersionLowerThen('5')) { + return false; + } + $status = str_replace("'", "", $status); + $id = intval($id); + if (AVideoPlugin::isEnabledByName("VideoTags")) { + if (!empty($_GET['tags_id']) && empty($videosArrayId)) { + $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); + } + } + _mysql_connect(); + $sql = "SELECT u.*, v.*, " + . " nv.title as next_title," + . " nv.clean_title as next_clean_title," + . " nv.filename as next_filename," + . " nv.id as next_id," + . " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation " + //. ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes " + //. ", (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes " + ; + if (User::isLogged()) { + $sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote "; + } else { + $sql .= ", 0 as myVote "; + } + $sql .= " FROM videos as v " + . "LEFT JOIN categories c ON categories_id = c.id " + . "LEFT JOIN users u ON v.users_id = u.id " + . "LEFT JOIN videos nv ON v.next_videos_id = nv.id " + . " WHERE 1=1 "; + if ($activeUsersOnly) { + $sql .= " AND u.status = 'a' "; + } + + if (!empty($id)) { + $sql .= " AND v.id = '$id' "; + } + $sql .= AVideoPlugin::getVideoWhereClause(); + $sql .= static::getVideoQueryFileter(); + if (!$ignoreGroup) { + $sql .= self::getUserGroupsCanSeeSQL('v.'); + } + if (!empty($_SESSION['type'])) { + if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { + $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; + } elseif ($_SESSION['type'] == 'audio') { + $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; + } else { + $sql .= " AND v.type = '{$_SESSION['type']}' "; + } + } + + if (!empty($videosArrayId) && is_array($videosArrayId)) { + $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; + } + if ($status == "viewable") { + $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; + } elseif ($status == "viewableNotUnlisted") { + $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; + } elseif (!empty($status)) { + $sql .= " AND v.status = '{$status}'"; + } + + if (!empty($_GET['catName'])) { + $catName = $global['mysqli']->real_escape_string($_GET['catName']); + $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))"; + } + + if (empty($id) && !empty($_GET['channelName'])) { + $user = User::getChannelOwner($_GET['channelName']); + if (!empty($user['id'])) { + $sql .= " AND v.users_id = '{$user['id']}' "; + } + } + + if (!empty($_GET['search'])) { + $_POST['searchPhrase'] = $_GET['search']; + } + + if (!empty($_POST['searchPhrase'])) { + $_POST['searchPhrase'] = str_replace('"', '"', $_POST['searchPhrase']); + $searchFieldsNames = ['v.title', 'v.description', 'c.name', 'c.description', 'v.id', 'v.filename']; + 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 = ['v.title']; + $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); + $sql .= ")"; + } else { + $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); + $searchFieldsNames = ['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 (!empty($video['id'])) { + if (is_null($video['likes'])) { + $video['likes'] = self::updateLikesDislikes($video['id'], 'likes'); + } + if (is_null($video['dislikes'])) { + $video['dislikes'] = self::updateLikesDislikes($video['id'], 'dislikes'); + } + } + // if there is a search, and there is no data and is inside a channel try again without a channel + if (!empty($_GET['search']) && empty($video) && !empty($_GET['channelName'])) { + $channelName = $_GET['channelName']; + unset($_GET['channelName']); + $return = self::getVideo($id, $status, $ignoreGroup, $random, $suggestedOnly, $showUnlisted, $ignoreTags, $activeUsersOnly); + $_GET['channelName'] = $channelName; + return $return; + } + + sqlDAL::close($res); + if ($res != false) { + require_once $global['systemRootPath'] . 'objects/userGroups.php'; + if (!empty($video)) { + $video = self::getInfo($video); + } + } else { + $video = false; + } + return $video; + } + + public static function getVideoLikes($videos_id) + { + global $global, $_getLikes; + + if (!isset($_getLikes)) { + $_getLikes = []; + } + + if (!empty($_getLikes[$videos_id])) { + return $_getLikes[$videos_id]; + } + + require_once $global['systemRootPath'] . 'objects/like.php'; + $obj = new stdClass(); + $obj->videos_id = $videos_id; + $obj->likes = 0; + $obj->dislikes = 0; + $obj->myVote = Like::getMyVote($videos_id); + + $video = Video::getVideoLight($obj->videos_id); + $obj->likes = intval($video['likes']); + $obj->dislikes = intval($video['dislikes']); + $_getLikes[$videos_id] = $obj; + + return $obj; + } + + public static function getVideoLight($id) + { + global $global, $config; + $id = intval($id); + $sql = "SELECT * FROM videos WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, 'i', [$id], 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, "", [], 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, "", [], true); + $video = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + return intval($video['total']); + } + + public static function getVideoFromFileName($fileName, $ignoreGroup = false, $ignoreTags = false) + { + global $global, $_getVideoFromFileName; + if (empty($fileName)) { + return false; + } + $parts = explode("/", $fileName); + if (!empty($parts[0])) { + $fileName = $parts[0]; + } + $fileName = self::getCleanFilenameFromFile($fileName); + + if (!isset($_getVideoFromFileName)) { + $_getVideoFromFileName = []; + } + $indexName = "{$fileName}_{$ignoreGroup}_{$ignoreTags}"; + if (isset($_getVideoFromFileName[$indexName])) { + return $_getVideoFromFileName[$indexName]; + } + $_getVideoFromFileName[$indexName] = false; + $sql = "SELECT id FROM videos WHERE filename = ? LIMIT 1"; + + $res = sqlDAL::readSql($sql, "s", [$fileName]); + if ($res != false) { + $video = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($video['id'])) { + $_getVideoFromFileName[$indexName] = self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags); + } + } + return $_getVideoFromFileName[$indexName]; + } + + 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", [$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", [$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; + } + } + + public static function getRelatedMovies($videos_id, $limit = 10) + { + global $global; + $video = self::getVideoLight($videos_id); + if (empty($video)) { + return false; + } + $sql = "SELECT * FROM videos v WHERE v.id != {$videos_id} AND v.status='a' AND (categories_id = {$video['categories_id']} "; + if (AVideoPlugin::isEnabledByName("VideoTags")) { + $sql .= " OR ("; + $sql .= "v.id IN (select videos_id FROM tags_has_videos WHERE tags_id IN " + . " (SELECT tags_id FROM tags_has_videos WHERE videos_id = {$videos_id}))"; + $sql .= ")"; + } + + $sql .= ") "; + + $sql .= AVideoPlugin::getVideoWhereClause(); + + $sql .= "ORDER BY RAND() LIMIT {$limit} "; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + + sqlDAL::close($res); + $rows = []; + if ($res != false) { + foreach ($fullData as $row) { + $row['images'] = self::getImageFromFilename($row['filename']); + if (empty($row['externalOptions'])) { + $row['externalOptions'] = json_encode(['videoStartSeconds' => '00:00:00']); + } + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + /** + * + * @global type $global + * @param type $status + * @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results + * @param type $ignoreGroup + * @param type $videosArrayId an array with videos to return (for filter only) + * @return boolean + */ + public static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = [], $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false, $is_serie = null) + { + global $global, $config, $advancedCustom, $advancedCustomUser; + if ($config->currentVersionLowerThen('11.5')) { + return false; + } + if ($dirh) { + while (($dirElement = readdir($dirh)) !== false) { + } + closedir($dirh); + } + 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__, 0.2); + } + } + $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__, 0.2); + } + 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'])) { + $_POST['searchPhrase'] = str_replace('"', '"', $_POST['searchPhrase']); + $searchFieldsNames = ['v.title', 'v.description', 'c.name', 'c.description', 'v.id', 'v.filename']; + 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 = ['v.title']; + $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); + $sql .= ")"; + } else { + $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); + $searchFieldsNames = ['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([], 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([], empty($_POST['sort']['likes']) ? "v." : "", "", true); + } else { + unset($_POST['sort']['trending'], $_GET['sort']['trending']); + $rows = []; + if (!empty($_REQUEST['current']) && $_REQUEST['current'] == 1) { + $rows = VideoStatistic::getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); + } + $ids = []; + 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(DEBUG_BACKTRACE_IGNORE_ARGS))); + 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); + + $timeLogName = TimeLogStart("video::getAllVideos"); + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + TimeLogEnd($timeLogName, __LINE__, 0.2); + + // 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']); + TimeLogEnd($timeLogName, __LINE__, 1); + $return = self::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly, $suggestedOnly); + TimeLogEnd($timeLogName, __LINE__, 1); + $_GET['channelName'] = $channelName; + return $return; + } + + sqlDAL::close($res); + $videos = []; + if ($res != false) { + //$global['mysqli']->commit(); + require_once 'userGroups.php'; + TimeLogStart("video::getAllVideos foreach"); + // for the cache on the database fast insert + + TimeLogEnd($timeLogName, __LINE__, 0.2); + $global['mysqli']->begin_transaction(); + foreach ($fullData as $row) { + if (is_null($row['likes'])) { + $row['likes'] = self::updateLikesDislikes($row['id'], 'likes'); + } + if (is_null($row['dislikes'])) { + $row['dislikes'] = self::updateLikesDislikes($row['id'], 'dislikes'); + } + if (empty($row['duration_in_seconds']) && $row['type']!=='article') { + $row['duration_in_seconds'] = self::updateDurationInSeconds($row['id'], $row['duration']); + } + $row = self::getInfo($row, $getStatistcs); + $videos[] = $row; + } + $global['mysqli']->commit(); + TimeLogEnd($timeLogName, __LINE__, 1); + $rowCount = getRowCount(); + $tolerance = $rowCount / 100; + if ($tolerance < 0.2) { + $tolerance = 0.2; + } elseif ($tolerance > 2) { + $tolerance = 2; + } + TimeLogEnd("video::getAllVideos foreach", __LINE__, $tolerance); + //$videos = $res->fetch_all(MYSQLI_ASSOC); + } else { + $videos = false; + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $videos; + } + + private static function getInfo($row, $getStatistcs = false) + { + $TimeLogLimit = 0.1; + $timeLogName = TimeLogStart("video::getInfo getStatistcs"); + $name = "_getVideoInfo_{$row['id']}"; + $cache = ObjectYPT::getCache($name, 3600); + if (!empty($cache)) { + $externalOptions = $cache->externalOptions; + $obj = object_to_array($cache); + if (!empty($externalOptions)) { + if (is_object($externalOptions)) { + $obj['externalOptions'] = $externalOptions; + } elseif (is_string($externalOptions)) { + $obj['externalOptions'] = _json_decode($externalOptions); + } + $obj['externalOptions'] = json_encode($obj['externalOptions']); + } + if (empty($obj['externalOptions'])) { + $obj['externalOptions'] = json_encode(['videoStartSeconds' => '00:00:00']); + } + return $obj; + } + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row = cleanUpRowFromDatabase($row); + if (!self::canEdit($row['id'])) { + if (!empty($row['video_password'])) { + $row['video_password'] = 1; + } else { + $row['video_password'] = 0; + } + } + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + if ($getStatistcs) { + $previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days")); + $previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days")); + $today = date('Y-m-d 23:59:59'); + $row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']); + $row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today); + $row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today); + $row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today); + $row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true); + } + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $otherInfocachename = "otherInfo{$row['id']}"; + $otherInfo = object_to_array(ObjectYPT::getCache($otherInfocachename, 600)); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + if (empty($otherInfo)) { + $otherInfo = []; + $otherInfo['category'] = xss_esc_back($row['category']); + $otherInfo['groups'] = UserGroups::getVideoGroups($row['id']); + $otherInfo['tags'] = self::getTags($row['id']); + $cached = ObjectYPT::setCache($otherInfocachename, $otherInfo); + //_error_log("video::getInfo cache " . json_encode($cached)); + } + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $otherInfo['title'] = UTF8encode($row['title']); + $otherInfo['description'] = UTF8encode($row['description']); + $otherInfo['descriptionHTML'] = self::htmlDescription($otherInfo['description']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + foreach ($otherInfo as $key => $value) { + $row[$key] = $value; + } + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['hashId'] = idToHash($row['id']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['link'] = self::getLinkToVideo($row['id'], $row['clean_title']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['embedlink'] = self::getLinkToVideo($row['id'], $row['clean_title'], true); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['progress'] = self::getVideoPogressPercent($row['id']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['isFavorite'] = self::isFavorite($row['id']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['isWatchLater'] = self::isWatchLater($row['id']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $row['total_seconds_watching_human'] = seconds2human($row['total_seconds_watching']); + $row['views_count_short'] = number_format_short($row['views_count']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + + if (empty($row['externalOptions'])) { + $row['externalOptions'] = json_encode(['videoStartSeconds' => '00:00:00']); + } + $row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id'])); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + ObjectYPT::setCache($name, $row); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + return $row; + } + + public static function htmlDescription($description) + { + if (strip_tags($description) != $description) { + return $description; + } else { + return nl2br(textToLink(htmlentities($description))); + } + } + + public static function isFavorite($videos_id) + { + if (AVideoPlugin::isEnabledByName("PlayLists")) { + return PlayList::isVideoOnFavorite($videos_id, User::getId()); + } + return false; + } + + public static function isSerie($videos_id) + { + $v = new Video("", "", $videos_id); + return !empty($v->getSerie_playlists_id()); + } + + public static function isWatchLater($videos_id) + { + if (AVideoPlugin::isEnabledByName("PlayLists")) { + return PlayList::isVideoOnWatchLater($videos_id, User::getId()); + } + return false; + } + + public static function getFavoriteIdFromUser($users_id) + { + if (AVideoPlugin::isEnabledByName("PlayLists")) { + return PlayList::getFavoriteIdFromUser($users_id); + } + return false; + } + + public static function getWatchLaterIdFromUser($users_id) + { + if (AVideoPlugin::isEnabledByName("PlayLists")) { + return PlayList::getWatchLaterIdFromUser($users_id); + } + return false; + } + + public static function updateFilesizeFromFilename($filename) + { + $value = Video::getVideoFromFileNameLight($filename); + return self::updateFilesize($value['id']); + } + + 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)) { + //_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 " . humanFileSize($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 " . humanFileSize($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 " . humanFileSize($filesize)); + Video::clearCache($videos_id); + return $filesize; + } else { + _error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize " . humanFileSize($filesize)); + return false; + } + } + + /** + * Same as getAllVideos() method but a lighter query + * @global type $global + * @global type $config + * @param type $showOnlyLoggedUserVideos + * @return boolean + */ + public static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false) + { + global $global, $config; + if ($config->currentVersionLowerThen('5')) { + return false; + } + $status = str_replace("'", "", $status); + $sql = "SELECT v.* " + . " FROM videos as v " + . " WHERE 1=1 "; + $blockedUsers = self::getBlockedUsersIdsArray(); + if (!empty($blockedUsers)) { + $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; + } + if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { + $sql .= " AND v.users_id = '" . User::getId() . "'"; + } elseif (!empty($showOnlyLoggedUserVideos)) { + $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; + } + if ($status == "viewable") { + if (User::isLogged()) { + $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; + } else { + $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; + } + } elseif ($status == "viewableNotUnlisted") { + $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; + } elseif (!empty($status)) { + $sql .= " AND v.status = '{$status}'"; + } + + if (!empty($_GET['channelName'])) { + $user = User::getChannelOwner($_GET['channelName']); + $sql .= " AND v.users_id = '{$user['id']}' "; + } + $sql .= AVideoPlugin::getVideoWhereClause(); + + if ($suggestedOnly) { + $sql .= " AND v.isSuggested = 1 "; + $sql .= " ORDER BY RAND() "; + } + if (strpos(strtolower($sql), 'limit') === false) { + if (empty($global['limitForUnlimitedVideos'])) { + $global['limitForUnlimitedVideos'] = empty($global['rowCount']) ? 1000 : $global['rowCount']; + } + if ($global['limitForUnlimitedVideos'] > 0) { + $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; + } + } + //echo $sql; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + + // if there is a search, and there is no data and is inside a channel try again without a channel + if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) { + $channelName = $_GET['channelName']; + unset($_GET['channelName']); + $return = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); + $_GET['channelName'] = $channelName; + return $return; + } + + sqlDAL::close($res); + $videos = []; + if ($res != false) { + foreach ($fullData as $row) { + if (empty($row['duration_in_seconds']) && $row['type']!=='article') { + $row['duration_in_seconds'] = self::updateDurationInSeconds($row['id'], $row['duration']); + } + 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}' OR c.parentId IN (SELECT cs.id from categories cs where cs.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'])) { + $_POST['searchPhrase'] = str_replace('"', '"', $_POST['searchPhrase']); + $searchFieldsNames = ['v.title', 'v.description', 'c.name', 'c.description', 'v.id', 'v.filename']; + 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 = ['v.title']; + $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); + $sql .= ")"; + } else { + $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); + $searchFieldsNames = ['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 = []) + { + $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 = [], $getStatistcs = false) + { + global $global, $advancedCustom; + $path = getCacheDir() . "getTotalVideosInfo/"; + make_path($path); + $cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}"; + $return = []; + if (!file_exists($cacheFileName)) { + if (file_exists($cacheFileName . ".lock")) { + return []; + } + file_put_contents($cacheFileName . ".lock", 1); + $total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs); + file_put_contents($cacheFileName, json_encode($total)); + unlink($cacheFileName . ".lock"); + return $total; + } + $return = _json_decode(file_get_contents($cacheFileName)); + if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { + // file older than 1 min + $command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' " + . " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', " + . " '$getStatistcs', '$cacheFileName'"); + //_error_log("getTotalVideosInfoAsync: {$command}"); + exec($command . " > /dev/null 2>/dev/null &"); + } + return $return; + } + + public static function getViewableStatus($showUnlisted = false) + { + $viewable = ['a', 'k', 'f']; + if ($showUnlisted) { + $viewable[] = "u"; + } + /* + * Cannot do that otherwise it will list videos on the list videos menu + $videos_id = getVideos_id(); + if (!empty($videos_id)) { + $post = $_POST; + if (self::isOwner($videos_id) || Permissions::canModerateVideos()) { + $viewable[] = "u"; + } + $_POST = $post; + } + * + */ + return $viewable; + } + + public static function getVideoConversionStatus($filename) + { + global $global; + require_once $global['systemRootPath'] . 'objects/user.php'; + if (!User::isLogged()) { + die("Only logged users can upload"); + } + + $object = new stdClass(); + + foreach (self::$types as $value) { + $progressFilename = self::getStoragePathFromFileName($filename) . "progress_{$value}.txt"; + $content = @url_get_contents($progressFilename); + $object->$value = new stdClass(); + if (!empty($content)) { + $object->$value = self::parseProgress($content); + } else { + } + + if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) { + $video = self::getVideoFromFileName($filename); + //var_dump($video, $filename); + if (!empty($video)) { + $object->$value->progress = self::$statusDesc[$video['status']]; + } + } + + $object->$value->filename = $progressFilename; + } + + return $object; + } + + private static function parseProgress($content) + { + //get duration of source + + $obj = new stdClass(); + + $obj->duration = 0; + $obj->currentTime = 0; + $obj->progress = 0; + //var_dump($content);exit; + preg_match("/Duration: (.*?), start:/", $content, $matches); + if (!empty($matches[1])) { + $rawDuration = $matches[1]; + + //rawDuration is in 00:00:00.00 format. This converts it to seconds. + $ar = array_reverse(explode(":", $rawDuration)); + $duration = floatval($ar[0]); + if (!empty($ar[1])) { + $duration += intval($ar[1]) * 60; + } + if (!empty($ar[2])) { + $duration += intval($ar[2]) * 60 * 60; + } + + //get the time in the file that is already encoded + preg_match_all("/time=(.*?) bitrate/", $content, $matches); + + $rawTime = array_pop($matches); + + //this is needed if there is more than one match + if (is_array($rawTime)) { + $rawTime = array_pop($rawTime); + } + + //rawTime is in 00:00:00.00 format. This converts it to seconds. + $ar = array_reverse(explode(":", $rawTime)); + $time = floatval($ar[0]); + if (!empty($ar[1])) { + $time += intval($ar[1]) * 60; + } + if (!empty($ar[2])) { + $time += intval($ar[2]) * 60 * 60; + } + + if (!empty($duration)) { + //calculate the progress + $progress = round(($time / $duration) * 100); + } else { + $progress = 'undefined'; + } + $obj->duration = $duration; + $obj->currentTime = $time; + $obj->progress = $progress; + } + return $obj; + } + + public function delete($allowOfflineUser = false) + { + if (!$allowOfflineUser && !$this->userCanManageVideo()) { + return false; + } + + global $global; + if (!empty($this->id)) { + $this->removeNextVideos($this->id); + $this->removeTrailerReference($this->id); + $this->removeCampaign($this->id); + $video = self::getVideoLight($this->id); + $sql = "DELETE FROM videos WHERE id = ?"; + } else { + return false; + } + + $resp = sqlDAL::writeSql($sql, "i", [$this->id]); + if ($resp == false) { + _error_log('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + return false; + } else { + $this->removeVideoFiles(); + } + return $resp; + } + + public function removeVideoFiles() + { + $filename = $this->getFilename(); + if (empty($filename)) { + return false; + } + $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); + $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); + $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); + $YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); + $cdn = AVideoPlugin::loadPluginIfEnabled('CDN'); + if (!empty($cdn)) { + $cdn_obj = $cdn->getDataObject(); + if (!empty($cdn_obj->enable_storage) && !empty($this->getSites_id())) { + CDNStorage::deleteRemoteDirectoryFromFilename($filename); + } + } + if (!empty($aws_s3)) { + $aws_s3->removeFiles($filename); + } + if (!empty($bb_b2)) { + $bb_b2->removeFiles($filename); + } + if (!empty($ftp)) { + $ftp->removeFiles($filename); + } + if (!empty($YPTStorage) && !empty($this->getSites_id())) { + $YPTStorage->removeFiles($filename, $this->getSites_id()); + } + $this->removeFiles($filename); + self::deleteThumbs($filename); + } + + private function removeNextVideos($videos_id) + { + if (!$this->userCanManageVideo()) { + return false; + } + + global $global; + + if (!empty($videos_id)) { + $sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?"; + sqlDAL::writeSql($sql, "s", [$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", [$videoURL]); + $sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?"; + sqlDAL::writeSql($sql, "s", [$videoURL]); + $sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?"; + sqlDAL::writeSql($sql, "s", [$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", [$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(); + $configPuri->set('Cache.SerializerPath', getCacheDir()); + $purifier = new HTMLPurifier($configPuri); + if (empty($articleObj->allowAttributes)) { + $configPuri->set('HTML.AllowedAttributes', ['a.href', 'a.target', 'a.title', 'a.title', 'img.src', 'img.width', 'img.height']); // remove all attributes except a.href + $configPuri->set('Attr.AllowedFrameTargets', ['_blank']); + } + if (empty($articleObj->allowAttributes)) { + $configPuri->set('CSS.AllowedProperties', []); // 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); + //$new_description= preg_replace('/[\xE2\x80\xAF\xBA\x96]/', '', $new_description); + + if (function_exists('mb_convert_encoding')) { + $new_description = mb_convert_encoding($new_description, 'UTF-8', 'UTF-8'); + } + + $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 = []; + } + 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", [$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 = []; + } + $name = "{$video_id}_{$type}"; + if (!empty($videos_getTags[$name])) { + return $videos_getTags[$name]; + } + + $videos_getTags[$name] = self::getTags_($video_id, $type); + return $videos_getTags[$name]; + } + + public static function getTagsHTMLLabelArray($video_id) + { + global $_getTagsHTMLLabelArray; + + if (!isset($_getTagsHTMLLabelArray)) { + $_getTagsHTMLLabelArray = []; + } + + if (isset($_getTagsHTMLLabelArray[$video_id])) { + return $_getTagsHTMLLabelArray[$video_id]; + } + + $tags = Video::getTags($video_id); + $_getTagsHTMLLabelArray[$video_id] = []; + 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, $getTags_; + + if (!isset($getTags_)) { + $getTags_ = []; + } + $index = "{$video_id}_{$type}"; + if (!empty($getTags_[$index])) { + return $getTags_[$index]; + } + + TimeLogStart("video::getTags_ $video_id, $type"); + if (empty($advancedCustom)) { + $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); + } + if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); + } + $currentPage = getCurrentPage(); + $rowCount = getRowCount(); + $_REQUEST['current'] = 1; + $_REQUEST['rowCount'] = 1000; + + TimeLogStart("video::getTags_ new Video $video_id, $type"); + $video = new Video("", "", $video_id); + $tags = []; + 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 ($video->getStatus() === self::$statusFansOnly) { + $objTag->type = "warning"; + $objTag->text = ''; + $objTag->tooltip = __("Fans Only"); + } elseif ($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(); + } + TimeLogEnd("video::getTags_ new Video $video_id, $type", __LINE__, 0.5); + + /** + a = active + i = inactive + e = encoding + x = encoding error + d = downloading + u = unlisted + */ + TimeLogStart("video::getTags_ status $video_id, $type"); + 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; + case Video::$statusRecording: + $objTag->type = "danger isRecording isRecordingIcon"; + break; + default: + $objTag->type = "danger"; + break; + } + $objTag->text = $objTag->text; + $tags[] = $objTag; + $objTag = new stdClass(); + } + TimeLogEnd("video::getTags_ status $video_id, $type", __LINE__, 0.5); + + TimeLogStart("video::getTags_ userGroups $video_id, $type"); + 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(); + } + } + } + TimeLogEnd("video::getTags_ userGroups $video_id, $type", __LINE__, 0.5); + + TimeLogStart("video::getTags_ category $video_id, $type"); + 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(); + } + } + TimeLogEnd("video::getTags_ category $video_id, $type", __LINE__, 0.5); + + TimeLogStart("video::getTags_ source $video_id, $type"); + 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(); + } + } + TimeLogEnd("video::getTags_ source $video_id, $type", __LINE__, 0.5); + + TimeLogStart("video::getTags_ AVideoPlugin::getVideoTags $video_id", __LINE__, 0.5); + $array2 = AVideoPlugin::getVideoTags($video_id); + if (is_array($array2)) { + $tags = array_merge($tags, $array2); + } + TimeLogEnd("video::getTags_ AVideoPlugin::getVideoTags $video_id", __LINE__, 0.5); + //var_dump($tags); + + TimeLogEnd("video::getTags_ $video_id, $type", __LINE__, 0.5); + $_REQUEST['current'] = $currentPage; + $_REQUEST['rowCount'] = $rowCount; + $getTags_[$index] = $tags; + return $tags; + } + + public static function deleteTagsAsync($video_id) + { + global $global; + return false; + if (empty($video_id)) { + return false; + } + + $name = "getVideoTags{$video_id}"; + if (class_exists('Cache')) { + Cache::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 = []; + if (!file_exists($cacheFileName)) { + if (file_exists($cacheFileName . ".lock")) { + return []; + } + 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, "", [], 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", [$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 = []) + { + global $config; + if (!User::canUpload()) { + return false; + } + global $global; + $obj = new stdClass(); + $obj->error = true; + + $target = $config->getEncoderURL() . "queue"; + $postFields = [ + '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['inputAutoHLS'] = 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); + Configuration::deleteEncoderURLCache(); + 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 ['path' => $global['systemRootPath'] . 'view/img/loading-gif.png', 'url' => getCDN() . 'view/img/loading-gif.png']; + } + + $cacheName = md5($filename . $type . $includeS3); + if (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 = "{$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'); + $cdn = AVideoPlugin::loadPluginIfEnabled('CDN'); + $yptStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); + if (!empty($cdn)) { + $cdn_obj = $cdn->getDataObject(); + if (!empty($cdn_obj->enable_storage)) { + $includeS3 = true; + } + } elseif (!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 = []; + if (!empty($secure)) { + $vars[] = $secure->getToken($filename); + } + if (!empty($vars)) { + $token = "?" . implode("&", $vars); + } + } + + + $paths = self::getPaths($filename); + + $source = []; + $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']); + $fsize = @filesize($source['path']); + $isValidType = (preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip"); + + if (!empty($video['sites_id'])) { + $site = new Sites($video['sites_id']); + } + + if (!empty($cdn_obj->enable_storage) && $isValidType && $fsize < 20 && !empty($site) && (empty($yptStorage) || $site->getUrl() == 'url/')) { + if ($type == ".m3u8") { + $f = "{$filename}/index{$type}"; + } else { + $f = "{$paths['relative']}{$filename}{$type}"; + } + $source['url'] = CDNStorage::getURL($f) . "{$token}"; + $source['url_noCDN'] = $source['url']; + } elseif (!empty($yptStorage) && !empty($site) && $isValidType && $fsize < 20) { + $siteURL = getCDNOrURL($site->getUrl(), 'CDN_YPTStorage', $video['sites_id']); + $source['url'] = "{$siteURL}{$paths['relative']}{$filename}{$type}{$token}"; + $source['url_noCDN'] = $site->getUrl() . "{$paths['relative']}{$filename}{$type}{$token}"; + if ($type == ".m3u8") { + $source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}"; + $source['url_noCDN'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; + } + } elseif (!empty($advancedCustom->videosCDN) && $canUseCDN) { + $advancedCustom->videosCDN = addLastSlash($advancedCustom->videosCDN); + $source['url'] = "{$advancedCustom->videosCDN}{$paths['relative']}{$filename}{$type}{$token}"; + $source['url_noCDN'] = "{$global['webSiteRootURL']}{$paths['relative']}{$filename}{$type}{$token}"; + if ($type == ".m3u8") { + $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}"; + $source['url_noCDN'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; + } + } else { + $source['url'] = getCDN() . "{$paths['relative']}{$filename}{$type}{$token}"; + $source['url_noCDN'] = "{$global['webSiteRootURL']}{$paths['relative']}{$filename}{$type}{$token}"; + if ($type == ".m3u8") { + $source['url'] = getCDN() . "videos/{$filename}/index{$type}{$token}"; + $source['url_noCDN'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; + } + } + /* need it because getDurationFromFile */ + if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf" || $type == ".zip")) { + if (file_exists($source['path']) && filesize($source['path']) < 1024) { + if (!empty($cdn_obj->enable_storage)) { + $source['url'] = CDNStorage::getURL("{$filename}{$type}"); + $source['url_noCDN'] = $source['url']; + } elseif (!empty($aws_s3)) { + $source = $aws_s3->getAddress("{$filename}{$type}"); + $source['url_noCDN'] = $source['url']; + $source['url'] = replaceCDNIfNeed($source['url'], 'CDN_S3'); + } elseif (!empty($bb_b2)) { + $source = $bb_b2->getAddress("{$filename}{$type}"); + $source['url_noCDN'] = $source['url']; + $source['url'] = replaceCDNIfNeed($source['url'], 'CDN_B2'); + } elseif (!empty($ftp)) { + $source = $ftp->getAddress("{$filename}{$type}"); + $source['url_noCDN'] = $source['url']; + $source['url'] = replaceCDNIfNeed($source['url'], 'CDN_FTP'); + } + } + } + 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] = ['path' => false, 'url' => false]; + //if($type=='.jpg'){echo '----'.PHP_EOL;var_dump($type, $source);echo '----'.PHP_EOL;}; + //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']) . filectime($source['path']); + } elseif (!empty($video)) { + $x = strtotime($video['modified']); + } + $source['url'] = addQueryStringParameter($source['url'], 'cache', $x); + $source['url_noCDN'] = addQueryStringParameter($source['url_noCDN'], 'cache', $x); + } + //ObjectYPT::setCache($name, $source); + $VideoGetSourceFile[$cacheName] = $source; + return $VideoGetSourceFile[$cacheName]; + } + + 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(); + make_path($paths['path']); + $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, $createDir = false) + { + global $global, $__getPaths; + if (!isset($__getPaths)) { + $__getPaths = []; + } + if (!empty($__getPaths[$videoFilename])) { + return $__getPaths[$videoFilename]; + } + $cleanVideoFilename = self::getCleanFilenameFromFile($videoFilename); + $videosDir = self::getStoragePath(); + + $path = addLastSlash("{$videosDir}{$cleanVideoFilename}"); + + $path = fixPath($path); + if ($createDir) { + make_path(addLastSlash($path)); + } + $relative = addLastSlash("videos/{$cleanVideoFilename}"); + $url = getCDN() . "{$relative}"; + $__getPaths[$videoFilename] = ['filename' => $cleanVideoFilename, 'path' => $path, 'url' => $url, 'relative' => $relative]; + return $__getPaths[$videoFilename]; + } + + public static function getPathToFile($videoFilename, $createDir = false) + { + $videosDir = self::getStoragePath(); + $videoFilename = str_replace($videosDir, '', $videoFilename); + $paths = Video::getPaths($videoFilename, $createDir); + if (preg_match('/index.m3u8$/', $videoFilename)) { + $paths['path'] = rtrim($paths['path'], DIRECTORY_SEPARATOR); + $videoFilename = str_replace($paths['filename'], '', $videoFilename); + } + return "{$paths['path']}{$videoFilename}"; + } + + public static function getURLToFile($videoFilename, $createDir = false) + { + $videosDir = self::getStoragePath(); + $videoFilename = str_replace($videosDir, '', $videoFilename); + $paths = Video::getPaths($videoFilename, $createDir); + $parts = explode('/', $videoFilename); + if (!empty($parts[1]) && $parts[1] == 'index.m3u8') { + $videoFilename = $parts[1]; + } + 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}_v{$uid}"); + return self::getPaths($videoFilename); + } + + public static function isNewVideoFilename($filename) + { + $filename = self::getCleanFilenameFromFile($filename); + return preg_match('/_([0-9]{12})_([0-9a-z]{4})$/i', $filename); + } + + 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; + } + + if (isAnyStorageEnabled()) { + $newFilename = self::getPaths($video['filename']); + $id = $video['id']; + } else { + $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 ['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); + $filename = str_replace(getVideosDir(), '', $filename); + if (preg_match('/videos[\/\\\]([^\/\\\]+)[\/\\\].*index.m3u8$/', $filename, $matches)) { + return $matches[1]; + } + $search = ['_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2', '_spectrum', '_tvg', '.notfound']; + + if (!empty($global['langs_codes_values_withdot']) && is_array($global['langs_codes_values_withdot'])) { + $search = array_merge($search, $global['langs_codes_values_withdot']); + } + + if (empty($global['avideo_resolutions']) || !is_array($global['avideo_resolutions'])) { + $global['avideo_resolutions'] = [240, 360, 480, 540, 720, 1080, 1440, 2160]; + } + + foreach ($global['avideo_resolutions'] as $value) { + $search[] = "_{$value}"; + + $search[] = "res{$value}"; + } + $cleanName = str_replace($search, '', $filename); + + if ($cleanName == $filename) { + $cleanName = preg_replace('/([a-z]+_[0-9]{12}_[a-z0-9]{4})_[0-9]+/', '$1', $filename); + } + + $path_parts = pathinfo($cleanName); + if (empty($path_parts['extension'])) { + //_error_log("Video::getCleanFilenameFromFile could not find extension of ".$filename); + if (!empty($path_parts['filename'])) { + return $path_parts['filename']; + } else { + return $filename; + } + } elseif (strlen($path_parts['extension']) > 4) { + return $cleanName; + } elseif ($path_parts['filename'] == 'index' && $path_parts['extension'] == 'm3u8') { + $parts = explode(DIRECTORY_SEPARATOR, $cleanName); + if (!empty($parts[0])) { + return $parts[0]; + } + return $parts[1]; + } 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 []; + } + TimeLogEnd($name1, __LINE__); + $return = []; + 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); + + $return = []; + + $cacheName = "getHigestResolution($filename)"; + $return = ObjectYPT::getSessionCache($cacheName, 0); + if (!empty($return)) { + return object_to_array($return); + } + $name0 = "Video:::getHigestResolution($filename)"; + TimeLogStart($name0); + $name1 = "Video:::getHigestResolution::getVideosURL_V2($filename)"; + TimeLogStart($name1); + + $v = self::getVideoFromFileNameLight($filename); + if (empty($v)) { + return []; + } + if ($v['type'] !== 'video') { + return []; + } + if ($v['status'] !== self::$statusActive && $v['status'] !== self::$statusUnlisted) { + return []; + } + $video = new Video('', '', $v['id']); + if (empty($video)) { + return []; + } + $HigestResolution = $video->getVideoHigestResolution(); + //_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) 1 FROM database $HigestResolution"); + if (!empty($HigestResolution)) { + //_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) 2 FROM database $HigestResolution"); + $resolution = $HigestResolution; + + $return['resolution'] = $resolution; + $return['resolution_text'] = getResolutionText($return['resolution']); + $return['resolution_label'] = getResolutionLabel($return['resolution']); + $return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}"); + return $return; + } else { + $validFileExtensions = ['webm', 'mp4', 'm3u8']; + $sources = getVideosURL_V2($filename); + if (!is_array($sources)) { + //_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources)); + return []; + } + TimeLogEnd($name1, __LINE__); + foreach ($sources as $key => $value) { + $ext = pathinfo($value["path"], PATHINFO_EXTENSION); + if (!in_array($ext, $validFileExtensions)) { + continue; + } + 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 + //var_dump(2, $filename, $resolution); + if (empty($resolution) && empty($global['onlyGetResolutionFromFilename'])) { + $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']}"); + } + } + } + } + _error_log("Video:::getHigestResolution::getVideosURL_V2($filename) 3 FROM database " . $return['resolution'] . ' - ' . $v['path']); //exit; + //if($filename=='video_210916143432_c426'){var_dump(1, $filename, $return);exit;} + $video->setVideoHigestResolution($return['resolution']); + TimeLogEnd($name0, __LINE__); + ObjectYPT::setSessionCache($cacheName, $return); + return $return; + } + + public static function getResolutionFromFilename($filename) + { + global $global; + $resolution = false; + if (preg_match("/_([0-9]+).(mp4|webm)/i", $filename, $matches)) { + if (!empty($matches[1])) { + $resolution = intval($matches[1]); + } + //var_dump(__LINE__); + } elseif (preg_match('/res([0-9]+)\/index.m3u8/i', $filename, $matches)) { + if (!empty($matches[1])) { + $resolution = intval($matches[1]); + } + //var_dump(__LINE__); + } elseif (preg_match('/_(HD|Low|SD).(mp4|webm)/i', $filename, $matches)) { + if (!empty($matches[1])) { + if ($matches[1] == 'HD') { + $resolution = 1080; + } elseif ($matches[1] == 'SD') { + $resolution = 720; + } elseif ($matches[1] == 'Low') { + $resolution = 480; + } + } + //var_dump(__LINE__); + } elseif (preg_match('/\/(hd|low|sd)\/index.m3u8/', $filename, $matches)) { + if (!empty($matches[1])) { + if ($matches[1] == 'hd') { + $resolution = 1080; + } elseif ($matches[1] == 'sd') { + $resolution = 720; + } elseif ($matches[1] == 'low') { + $resolution = 480; + } + } + //var_dump(__LINE__); + } elseif (preg_match('/video_[0-9_a-z]+\/index.m3u8/i', $filename)) { + if (class_exists('VideoHLS')) { + $resolution = VideoHLS::getHLSHigestResolutionFromFile($filename); + //var_dump(5, $filename,$resolution); + } + //var_dump(__LINE__); + } + //echo PHP_EOL.PHP_EOL;var_dump(__LINE__, preg_match('/video_[0-9_a-z]+\/index.m3u8/i', $filename), $filename, $resolution, $matches);echo PHP_EOL.PHP_EOL; + //if($filename=='video_210916143432_c426'){var_dump(3, $filename, $resolution, $matches);exit;} + return $resolution; + } + + public static function getHigestResolutionVideoMP4Source($filename, $includeS3 = false) + { + global $global; + $types = ['', '_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 = [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 getSourceFileURL($filename, $includeS3 = false) + { + $sources = self::getVideosPaths($filename, $includeS3); + if (!empty($sources['mp3'])) { + return $sources['mp3']; + } + if (!empty($sources['webm'])) { + return end($sources['webm']); + } + if (!empty($sources['m3u8']) && !empty($sources['m3u8']['url'])) { + return $sources['m3u8']['url']; + } + if (!empty($sources['mp4'])) { + return end($sources['mp4']); + } + return false; + } + + public static function getVideosPaths($filename, $includeS3 = false) + { + global $global, $_getVideosPaths; + + $cacheName = "getVideosPaths_$filename" . ($includeS3 ? 1 : 0); + $cache = ObjectYPT::getCache($cacheName, 0); + //var_dump($cacheName, $cache, _json_decode($cache));//exit; + if (!empty($cache)) { + return object_to_array(_json_decode($cache)); + } + + $types = ['', '_Low', '_SD', '_HD']; + + foreach ($global['avideo_resolutions'] as $value) { + $types[] = "_{$value}"; + } + + $videos = []; + + $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']; + } + $c = ObjectYPT::setCache($cacheName, $videos); + //var_dump($cacheName, $c);exit; + 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 (!$async) { + return self::getImageFromFilename_($filename, $type); + } else { + return self::getImageFromFilenameAsync($filename, $type); + } + } + + public static function getPoster($videos_id) + { + global $_getPoster; + if (!isset($_getPoster)) { + $_getPoster = []; + } + if (isset($_getPoster[$videos_id])) { + return $_getPoster[$videos_id]; + } + $images = self::getImageFromID($videos_id); + $_getPoster[$videos_id] = false; + if (!empty($images->poster)) { + $_getPoster[$videos_id] = $images->poster; + } elseif (!empty($images->posterPortrait)) { + $_getPoster[$videos_id] = $images->posterPortrait; + } + return $_getPoster[$videos_id]; + } + + 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)) { + $relativePath = str_replace($global['systemRootPath'], '', $rokuImage); + return getURL($relativePath); + } + return getURL("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 []; + } + global $_getImageFromFilename_; + if (empty($_getImageFromFilename_)) { + $_getImageFromFilename_ = []; + } + + $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 []; + } + $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 1 {$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 2 {$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) { + if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { + //_error_log("Resize JPG 3 useFFMPEGToGenerateThumbs {$jpegSource['path']}, {$thumbsSource['path']}"); + im_resizeV3($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); + } else { + //_error_log("Resize JPG 3 {$jpegSource['path']}, {$thumbsSource['path']}"); + im_resizeV2($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); + } + } + // create thumbs + if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) { + if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { + //_error_log("Resize Small JPG 4 useFFMPEGToGenerateThumbs {$jpegSource['path']}, {$thumbsSmallSource['path']}"); + im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); + } else { + //_error_log("Resize Small JPG 4 {$jpegSource['path']}, {$thumbsSmallSource['path']}"); + 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 = []; + $path = getCacheDir() . "getImageFromFilenameAsync/"; + make_path($path); + $cacheFileName = "{$path}_{$filename}_{$type}"; + if (!file_exists($cacheFileName)) { + if (file_exists($cacheFileName . ".lock")) { + return []; + } + 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()); + if (empty($return->posterLandscapePath)) { + $path = Video::getPaths($video->getFilename()); + $return->posterLandscapePath = "{$path['path']}{$path['filename']}.jpg"; + $return->posterLandscape = "{$path['url']}{$path['filename']}.jpg"; + } + if (empty($return->posterPortraitPath)) { + $path = Video::getPaths($video->getFilename()); + $return->posterPortraitPath = "{$path['path']}{$path['filename']}_portrait.jpg"; + $return->posterPortrait = "{$path['url']}{$path['filename']}_portrait.jpg"; + } + return $return; + } + + 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", [$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", [$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 = [], $ignoreChannelname = false) + { + global $global, $advancedCustomUser, $advancedCustom; + if (!empty($_GET['evideo'])) { + $v = self::decodeEvideo(); + if (!empty($v['video']['videoLink'])) { + if ($embed) { + return parseVideos($v['video']['videoLink'], $advancedCustom->embedAutoplay, $advancedCustom->embedLoop, $advancedCustom->embedStartMuted, $advancedCustom->embedShowinfo, $advancedCustom->embedControls->value); + } else { + return $v['video']['videoLink']; + } + } + } + + if (!is_object($advancedCustomUser)) { + $advancedCustomUser = AVideoPlugin::getDataObject('CustomizeUser'); + } + if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); + } + if (empty($videos_id) && !empty($clean_title)) { + $videos_id = self::get_id_from_clean_title($clean_title); + } + $video = new Video("", "", $videos_id); + + if (!$ignoreChannelname && $advancedCustomUser->addChannelNameOnLinks) { + $get['channelName'] = $video->getChannelName(); + } elseif ($ignoreChannelname) { + $get['channelName'] = null; + } + + unset($get['v'], $get['videoName'], $get['videoName'], $get['isMediaPlaySite'], $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)) { + $url = "{$global['webSiteRootURL']}{$subEmbedDir}/{$clean_title}{$get_http}"; + } else { + $url = "{$global['webSiteRootURL']}{$subEmbedDir}/{$videos_id}/{$clean_title}{$get_http}"; + } + return parseVideos($url, $advancedCustom->embedAutoplay, $advancedCustom->embedLoop, $advancedCustom->embedStartMuted, $advancedCustom->embedShowinfo, $advancedCustom->embedControls->value); + } 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) { + $url = "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}"; + return parseVideos($url, $advancedCustom->embedAutoplay, $advancedCustom->embedLoop, $advancedCustom->embedStartMuted, $advancedCustom->embedShowinfo, $advancedCustom->embedControls->value); + } else { + return "{$global['webSiteRootURL']}v/{$videos_id}{$get_http}"; + } + } + } + + public static function getPermaLink($videos_id, $embed = false, $get = []) + { + return self::getLinkToVideo($videos_id, "", $embed, "permalink", $get); + } + + public static function getURLFriendly($videos_id, $embed = false, $get = []) + { + return self::getLinkToVideo($videos_id, "", $embed, "URLFriendly", $get); + } + + public static function getPermaLinkFromCleanTitle($clean_title, $embed = false, $get = []) + { + return self::getLinkToVideo("", $clean_title, $embed, "permalink", $get); + } + + public static function getURLFriendlyFromCleanTitle($clean_title, $embed = false, $get = []) + { + return self::getLinkToVideo("", $clean_title, $embed, "URLFriendly", $get); + } + + public static function getLink($videos_id, $clean_title, $embed = false, $get = []) + { + 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", [$users_id]); + $videoRows = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + + $r = ['thumbsUp' => 0, 'thumbsDown' => 0]; + + if ($res != false) { + foreach ($videoRows as $row) { + $values = [$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 = []; + $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 getTotalVideosThumbsUpFromUserFromVideos($users_id) + { + global $global; + + $sql = "SELECT sum(likes) as thumbsUp, sum(dislikes) as thumbsDown from videos WHERE users_id = ? "; + + $res = sqlDAL::readSql($sql, "i", [$users_id]); + $videoRows = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + + $r = ['thumbsUp' => 0, 'thumbsDown' => 0]; + + if ($res != false) { + foreach ($videoRows as $row) { + $r['thumbsUp'] += intval($row['thumbsUp']); + $r['thumbsDown'] += intval($row['thumbsDown']); + } + } + return $r; + } + + public static function deleteThumbs($filename, $doNotDeleteSprit = false, $checkIfIsCorrupted = false) + { + if (empty($filename)) { + return false; + } + global $global; + + $filePath = Video::getPathToFile($filename); + // Streamlined for less coding space. + $files = glob("{$filePath}*_thumbs*.jpg"); + $files[] = "{$filePath}_roku.jpg"; + $totalDeleted = 0; + foreach ($files as $file) { + if (file_exists($file)) { + if ($checkIfIsCorrupted && !isImageCorrupted($file)) { + continue; + } + if ($doNotDeleteSprit && strpos($file, '_thumbsSprit.jpg') !== false) { + continue; + } + if (isCommandLineInterface()) { + echo "Deleting {$file} ". humanFileSize(filesize($file)).PHP_EOL; + } + @unlink($file); + $totalDeleted++; + } + } + if ($totalDeleted) { + 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 $totalDeleted; + } + + public static function deleteGifAndWebp($filename) + { + if (empty($filename)) { + return false; + } + global $global; + + $filePath = Video::getPathToFile($filename); + @unlink("{$filePath}.gif"); + @unlink("{$filePath}.webp"); + 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("PlayeSkins_getVideoTags{$videos_id}"); + ObjectYPT::deleteCache("_getVideoInfo_{$videos_id}"); + 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")); + if (class_exists('Cache')) { + Cache::deleteCache("getSourceFile($filename)1"); + Cache::deleteCache("getSourceFile($filename)0"); + Cache::deleteCache("getVideosPaths_($filename)1"); + Cache::deleteCache("getVideosPaths_($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) + { + if ($fileName == '.zip') { + return false; + } + _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 ['percent' => 0, 'lastVideoTime' => 0]; + } + + // start incremental search and save + $sql = "SELECT duration FROM `videos` WHERE id = ? LIMIT 1"; + $res = sqlDAL::readSql($sql, "i", [$videos_id]); + $row = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + + if (empty($row) || empty($row['duration'])) { + return ['percent' => 0, 'lastVideoTime' => 0]; + } + + $duration = parseDurationToSeconds($row['duration']); + + if (empty($duration)) { + return ['percent' => 0, 'lastVideoTime' => 0]; + } + + if ($lastVideoTime > $duration) { + return ['percent' => 100, 'lastVideoTime' => $lastVideoTime]; + } + + return ['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 = []; + } + if (isset($_getVideoType[$filename])) { + return $_getVideoType[$filename]; + } + + $obj = new stdClass(); + $paths = self::getVideosPaths($filename); + //var_dump($paths);exit; + $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); + if (!is_string($externalOptions)) { + $externalOptions = _json_encode($externalOptions); + } + $this->externalOptions = $externalOptions; + } + + public function setVideoTags($tags) + { + $externalOptions = _json_decode($this->getExternalOptions()); + if (!is_object($externalOptions)) { + $externalOptions = new stdClass(); + } + $externalOptions->VideoTags = $tags; + $this->setExternalOptions(json_encode($externalOptions)); + } + + public function getVideoTags() + { + $externalOptions = _json_decode($this->getExternalOptions()); + if (empty($externalOptions->VideoTags)) { + return false; + } + return $externalOptions->VideoTags; + } + + public function setVideoHigestResolution($HigestResolution) + { + $externalOptions = _json_decode($this->getExternalOptions()); + if (!is_object($externalOptions)) { + $externalOptions = new stdClass(); + } + $externalOptions->HigestResolution = $HigestResolution; + $this->setExternalOptions(json_encode($externalOptions)); + return $this->save(false, true); + } + + public function getVideoHigestResolution() + { + $externalOptions = _json_decode($this->getExternalOptions()); + if (empty($externalOptions->HigestResolution)) { + return false; + } + return $externalOptions->HigestResolution; + } + + public function setVideoStartSeconds($videoStartSeconds) + { + $externalOptions = _json_decode($this->getExternalOptions()); + AVideoPlugin::onVideoSetVideoStartSeconds($this->id, $this->videoStartSeconds, $videoStartSeconds); + $externalOptions->videoStartSeconds = intval($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; + } + + public static 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, "", [], 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 = []; + 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 ['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 []; + } + if (!User::isLogged()) { + return []; + } + $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); + if (empty($report)) { + return []; + } + 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)); + $search = str_replace('"', '"', $search); + if (empty($columnsArray) || empty($search)) { + return ""; + } + $sql = "("; + $matches = []; + 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}"; + } + + public static function canVideoBePurchased($videos_id) + { + global $global; + $obj = new stdClass(); + $obj->plugin = ''; + $obj->buyURL = ''; + $obj->canVideoBePurchased = false; + // check for Subscription plugin + if (AVideoPlugin::isEnabledByName('Subscription')) { + $sub = new Subscription(); + $plans = $sub->getPlansFromVideo($videos_id); + if (!empty($plans)) { + $obj->plugin = 'Subscription'; + $obj->buyURL = "{$global['webSiteRootURL']}plugin/Subscription/showPlans.php?videos_id={$videos_id}"; + $obj->canVideoBePurchased = true; + return $obj; + } + } + + // check for PPV plugin + if (AVideoPlugin::isEnabledByName('PayPerView')) { + if (PayPerView::isVideoPayPerView($videos_id) || $obj->onlyPlayVideosWithPayPerViewActive) { + $url = "{$global['webSiteRootURL']}plugin/PayPerView/page/buy.php"; + if (isSerie()) { + $redirectUri = getSelfURI(); + } else { + $redirectUri = getRedirectToVideo($videos_id); + } + if (!empty($redirectUri)) { + $url = addQueryStringParameter($url, 'redirectUri', $redirectUri); + } + $url = addQueryStringParameter($url, 'videos_id', $videos_id); + $obj->plugin = 'PayPerView'; + $obj->buyURL = $url; + $obj->canVideoBePurchased = true; + return $obj; + } + } + + // check for fansSubscription + if (AVideoPlugin::isEnabledByName('FansSubscriptions')) { + if (FansSubscriptions::hasPlansFromVideosID($videos_id)) { + $url = "{$global['webSiteRootURL']}plugin/FansSubscriptions/View/buy.php"; + if (isSerie()) { + $redirectUri = getSelfURI(); + } else { + $redirectUri = getRedirectToVideo($videos_id); + } + if (!empty($redirectUri)) { + $url = addQueryStringParameter($url, 'redirectUri', $redirectUri); + } + $url = addQueryStringParameter($url, 'videos_id', $videos_id); + $obj->plugin = 'FansSubscriptions'; + $obj->buyURL = $url; + $obj->canVideoBePurchased = true; + return $obj; + } + } + return false; + } + + public static function getCreatorHTML($users_id, $html = '', $small = false, $ignoreLinks=false) + { + global $global; + if ($small) { + $template = $global['systemRootPath'] . 'view/videoCreatorSmall.html'; + } else { + $template = $global['systemRootPath'] . 'view/videoCreator.html'; + } + + require_once $global['systemRootPath'] . 'objects/subscribe.php'; + $content = local_get_contents($template); + $name = User::getNameIdentificationById($users_id); + + $search = [ + '{photo}', + '{channelLink}', + '{name}', + '{icon}', + '{subscriptionButton}', + '{html}', ]; + + if ($ignoreLinks) { + $channelLink = '#'; + } else { + $channelLink = User::getChannelLink($users_id); + } + + $replace = [ + User::getPhoto($users_id), + $channelLink, + strip_tags($name), + User::getEmailVerifiedIcon($users_id), + Subscribe::getButton($users_id), + $html, + ]; + + $btnHTML = str_replace($search, $replace, $content); + return $btnHTML; + } + + public static function getVideosListItem($videos_id, $divID = '', $style = '') + { + global $global, $advancedCustom; + $get = []; + $get = ['channelName' => @$_GET['channelName'], 'catName' => @$_GET['catName']]; + + if (empty($divID)) { + $divID = "divVideo-{$videos_id}"; + } + $objGallery = AVideoPlugin::getObjectData("Gallery"); + $program = AVideoPlugin::loadPluginIfEnabled('PlayLists'); + $template = $global['systemRootPath'] . 'view/videosListItem.html'; + $templateContent = file_get_contents($template); + $value = Video::getVideoLight($videos_id); + $link = Video::getLink($value['id'], $value['clean_title'], "", $get); + if (!empty($_GET['page']) && $_GET['page'] > 1) { + $link = addQueryStringParameter($link, 'page', $_GET['page']); + } + + $title = $value['title']; + + $images = Video::getImageFromFilename($value['filename'], $value['type']); + + if (!is_object($images)) { + $images = new stdClass(); + $images->thumbsGif = ''; + $images->poster = getCDN() . "view/img/notfound.jpg"; + $images->thumbsJpg = getCDN() . "view/img/notfoundThumbs.jpg"; + $images->thumbsJpgSmall = getCDN() . "view/img/notfoundThumbsSmall.jpg"; + } + $imgJPGLow = $images->thumbsJpgSmall; + $imgJPGHight = $images->thumbsJpg; + $imgGif = $images->thumbsGif; + $imgGifHTML = ''; + + if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { + $imgGif = $images->gifPortrait; + $imgJPGHight = $images->posterPortrait; + } + if (!empty($imgGif)) { + $imgGifHTML = ''; + } + + $timeHTML = ''; + if (isToShowDuration($value['type'])) { + $timeHTML = ''; + } + + $loggedUserHTML = ''; + if (User::isLogged() && !empty($program)) { + $value['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); + $value['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); + if (!empty($value['isWatchLater'])) { + $watchLaterBtnAddedStyle = ''; + $watchLaterBtnStyle = "display: none;"; + } else { + $watchLaterBtnAddedStyle = "display: none;"; + $watchLaterBtnStyle = ''; + } + if (!empty($value['isFavorite'])) { + $favoriteBtnAddedStyle = ''; + $favoriteBtnStyle = "display: none;"; + } else { + $favoriteBtnAddedStyle = "display: none;"; + $favoriteBtnStyle = ''; + } + $loggedUserHTML = '
'; + $loggedUserHTML .= ' '; + $loggedUserHTML .= ''; + $loggedUserHTML .= '
'; + $loggedUserHTML .= ' '; + $loggedUserHTML .= ' '; + $loggedUserHTML .= '
'; + } + $progress = self::getVideoPogressPercent($value['id']); + $category = new Category($value['categories_id']); + + $categoryLink = $category->getLink(); + $categoryIcon = $category->getIconClass(); + $category = $category->getName(); + $tagsHTML = ''; + $tagsWhitelist = [__("Paid Content"), __("Group"), __("Plugin")]; + if (!empty($objGallery->showTags) && !empty($value['tags']) && is_array($value['tags'])) { + foreach ($value['tags'] as $value2) { + if (!empty($value2->label) && in_array($value2->label, $tagsWhitelist)) { + $tagsHTML .= '' . $value2->text . ''; + } + } + } + $viewsHTML = ''; + + if (empty($advancedCustom->doNotDisplayViews)) { + if (AVideoPlugin::isEnabledByName('LiveUsers')) { + $viewsHTML = '
' . getLiveUsersLabelVideo($value['id'], $value['views_count']) . '
'; + } else { + $viewsHTML = '
' . number_format($value['views_count'], 0) . '
'; + } + } + $creator = self::getCreatorHTML($value['users_id'], '', true); + + + $search = [ + '{style}', + '{divID}', + '{link}', + '{title}', + '{imgJPGLow}', + '{imgJPGHight}', + '{imgGifHTML}', + '{timeHTML}', + '{loggedUserHTML}', + '{progress}', + '{categoryLink}', + '{categoryIcon}', + '{category}', + '{tagsHTML}', + '{viewsHTML}', + '{creator}', ]; + + $replace = [ + $style, + $divID, + $link, + $title, + $imgJPGLow, + $imgJPGHight, + $imgGifHTML, + $timeHTML, + $loggedUserHTML, + $progress, + $categoryLink, + $categoryIcon, + $category, + $tagsHTML, + $viewsHTML, + $creator, + ]; + $btnHTML = @str_replace( + $search, + $replace, + $templateContent + ); + return $btnHTML; + } + + public function getTotal_seconds_watching() + { + return $this->total_seconds_watching; + } + + public function setTotal_seconds_watching($total_seconds_watching) + { + $this->total_seconds_watching = $total_seconds_watching; + } + + public function getDuration_in_seconds() + { + return $this->duration_in_seconds; + } + + public function setDuration_in_seconds($duration_in_seconds) + { + $this->duration_in_seconds = intval($duration_in_seconds); + } + + public function getLikes() + { + return $this->likes; + } + + public function getDislikes() + { + return $this->dislikes; + } + + public function setLikes($likes): void + { + $this->likes = intval($likes); + } + + public function setDislikes($dislikes): void + { + $this->dislikes = intval($dislikes); + } + + /** + * + * @param type $videos_id + * @param type $type [like or dislike] + * @param type $value + * @return boolean + * + * automatic = will get from like table + * +1 = add one + * -1 = remove one + * any number = will change the database + */ + public static function updateLikesDislikes($videos_id, $type, $value = 'automatic') + { + global $config, $global, $_updateLikesDislikes; + if ($config->currentVersionLowerThen('11.5')) { + return false; + } + + $index = "$videos_id, $type, $value"; + if (!isset($_updateLikesDislikes)) { + $_updateLikesDislikes = []; + } + + if (isset($_updateLikesDislikes[$index])) { + return $_updateLikesDislikes[$index]; + } + + require_once $global['systemRootPath'] . 'objects/like.php'; + $videos_id = intval($videos_id); + if (empty($videos_id)) { + return false; + } + + if (strtolower($type) == 'likes') { + $type = 'likes'; + } else { + $type = 'dislikes'; + } + //var_dump($videos_id, $type, $value); + $sql = "UPDATE videos SET "; + if ($value === 'automatic') { + $likes = Like::getLikes($videos_id); + return self::updateLikesDislikes($videos_id, $type, $likes->$type); + } elseif (preg_match('/\+([0-9]+)/', $value, $matches)) { + $value = intval($matches[1]); + $sql .= " {$type} = {$type}+{$value} "; + } elseif (preg_match('/-([0-9]+)/', $value, $matches)) { + $value = intval($matches[1]); + $sql .= " {$type} = {$type}-{$value} "; + } else { + $value = intval($value); + $sql .= " {$type} = {$value} "; + } + $sql .= ", modified = now() WHERE id = {$videos_id}"; + //secho $sql.PHP_EOL; + $saved = sqlDAL::writeSql($sql); + self::clearCache($videos_id); + $_updateLikesDislikes[$index] = $value; + return $value; + } + + public static function checkIfIsBroken($videos_id) + { + $video = new Video('', '', $videos_id); + if ($video->getStatus() == Video::$statusActive || $video->getStatus() == Video::$statusUnlisted) { + if ($video->getType() == 'audio' || $video->getType() == 'video') { + if (self::isMediaFileMissing($video->getFilename())) { + _error_log("Video::checkIfIsBroken($videos_id) true ".$video->getFilename()); + $video->setStatus(Video::$statusBrokenMissingFiles); + Video::clearCache($videos_id); + return true; + } + } + } + return false; + } + + public static function isMediaFileMissing($filename, $cacheCleared = false) + { + $sources = getVideosURL_V2($filename); + $search = ['mp3', 'mp4', 'm3u8', 'webm']; + $found = false; + foreach ($sources as $key => $value1) { + foreach ($search as $value2) { + if (preg_match("/^{$value2}/i", $key)) { + $found = true; + break 2; + } + } + } + + if (!$cacheCleared && !$found) { + global $getVideosURL_V2Array; + ObjectYPT::deleteCache("getVideosURL_V2$filename"); + unset($getVideosURL_V2Array); + return self::isMediaFileMissing($filename, true); + } + + return !$found; + } + } +} +// Just to convert permalink into clean_title +if (!empty($_GET['v']) && empty($_GET['videoName'])) { + $_GET['videoName'] = Video::get_clean_title($_GET['v']); +} diff --git a/objects/videoAddNew.json.php b/objects/videoAddNew.json.php index 36f89d4bbd..812f5a8b0d 100644 --- a/objects/videoAddNew.json.php +++ b/objects/videoAddNew.json.php @@ -1,172 +1,171 @@ -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))) { - $getLinkInfo = $config->getEncoderURL() . "getLinkInfo/" . base64_encode($_POST['videoLink']); - _error_log('videoAddNew: '.$getLinkInfo); - $info = url_get_contents($getLinkInfo, '', 180, true); - $infoObj = _json_decode($info); - $paths = Video::getNewVideoFilename(); - $filename = $paths['filename']; - $filename = $obj->setFilename($filename); - if(is_object($infoObj)){ - $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'])) { - $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'); - } - $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']); -} - -$externalOptions = new stdClass(); - -$externalOptionsOriginal = json_decode($obj->getExternalOptions()); -if(!empty($externalOptionsOriginal) && is_object($externalOptionsOriginal)){ - foreach ($externalOptionsOriginal as $key => $value) { - $externalOptions->$key = $value; - } -} - -$externalOptionsPost = json_decode(@$_POST['externalOptions']); -if(!empty($externalOptionsPost) && is_object($externalOptionsPost)){ - foreach ($externalOptionsPost as $key => $value) { - $externalOptions->$key = $value; - } -} - -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($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::getVideoLight($obj->videos_id); -if($obj->video['status'] == Video::$statusActive){ - $obj->clearFirstPageCache = clearFirstPageCache(); - //clearAllUsersSessionCache(); -} - -TimeLogEnd(__FILE__, __LINE__); -echo json_encode($obj); +setClean_Title($_POST['clean_title']); +$audioLinks = ['mp3', 'ogg']; +$videoLinks = ['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))) { + $getLinkInfo = $config->getEncoderURL() . "getLinkInfo/" . base64_encode($_POST['videoLink']); + _error_log('videoAddNew: '.$getLinkInfo); + $info = url_get_contents($getLinkInfo, '', 180, true); + $infoObj = _json_decode($info); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; + $filename = $obj->setFilename($filename); + if (is_object($infoObj)) { + $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"; + } elseif (empty($_POST['id'])) { + $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'); + } + } elseif (!empty($obj->getType())) { + $obj->setType('embed'); + } + + if (!empty($_POST['videoLinkType'])) { + $obj->setType($_POST['videoLinkType']); + } + if (empty($_POST['id'])) { + $obj->setStatus('a'); + } +} elseif (!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'); + } + $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']) ? [] : $_POST['videoGroups']); +} +if ($advancedCustomUser->userCanChangeVideoOwner || Permissions::canModerateVideos()) { + $obj->setUsers_id($_POST['users_id']); +} + +$externalOptions = new stdClass(); + +$externalOptionsOriginal = json_decode($obj->getExternalOptions()); +if (!empty($externalOptionsOriginal) && is_object($externalOptionsOriginal)) { + foreach ($externalOptionsOriginal as $key => $value) { + $externalOptions->$key = $value; + } +} + +$externalOptionsPost = json_decode(@$_POST['externalOptions']); +if (!empty($externalOptionsPost) && is_object($externalOptionsPost)) { + foreach ($externalOptionsPost as $key => $value) { + $externalOptions->$key = $value; + } +} + +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($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::getVideoLight($obj->videos_id); +if ($obj->video['status'] == Video::$statusActive) { + $obj->clearFirstPageCache = clearFirstPageCache(); + //clearAllUsersSessionCache(); +} + +TimeLogEnd(__FILE__, __LINE__); +echo json_encode($obj); diff --git a/objects/videoAddViewCount.json.php b/objects/videoAddViewCount.json.php index 1965f9ac8a..d4f5d8b19e 100644 --- a/objects/videoAddViewCount.json.php +++ b/objects/videoAddViewCount.json.php @@ -1,73 +1,73 @@ -getDuration()); - -if (!empty($seconds)) { - $percent = (intval($_REQUEST['currentTime']) / $seconds) * 100; - $percentOptions = array(25,50,75,100); - foreach ($percentOptions as $value) { - if ($percent >= $value) { - if (empty($_SESSION['addViewCount'][$_REQUEST['id']][$value]) && !empty($_REQUEST['currentTime'])) { - if ($obj->addViewPercent($value)) { - _session_start(); - $_SESSION['addViewCount'][$_REQUEST['id']][$value] = 1; - } - } - } - } -} - -$obj2 = new stdClass(); -$seconds_watching_video = intval(@$_REQUEST['seconds_watching_video']); -if($seconds_watching_video<0){ - $seconds_watching_video = 0; -} - -$obj2->seconds_watching_video = $seconds_watching_video; -if (empty($_SESSION['addViewCount'][$_REQUEST['id']]['time'])) { - $resp = $obj->addView(); - _session_start(); - $_SESSION['addViewCount'][$_REQUEST['id']]['time'] = strtotime("+{$seconds} seconds"); -} elseif (isset($_REQUEST['currentTime'])) { - $currentTime = intval($_REQUEST['currentTime']); - if($currentTime<0){ - $currentTime = 0; - } - $resp = VideoStatistic::updateStatistic($obj->getId(), User::getId(), $currentTime, $seconds_watching_video); -} else { - $resp = 0; -} -$count = $obj->getViews_count(); - -$obj2->status = !empty($resp); -$obj2->count = $count; -$obj2->countHTML = number_format_short($count); -$obj2->resp = $resp; - -echo json_encode($obj2); +getDuration()); + +if (!empty($seconds)) { + $percent = (intval($_REQUEST['currentTime']) / $seconds) * 100; + $percentOptions = [25,50,75,100]; + foreach ($percentOptions as $value) { + if ($percent >= $value) { + if (empty($_SESSION['addViewCount'][$_REQUEST['id']][$value]) && !empty($_REQUEST['currentTime'])) { + if ($obj->addViewPercent($value)) { + _session_start(); + $_SESSION['addViewCount'][$_REQUEST['id']][$value] = 1; + } + } + } + } +} + +$obj2 = new stdClass(); +$seconds_watching_video = intval(@$_REQUEST['seconds_watching_video']); +if ($seconds_watching_video<0) { + $seconds_watching_video = 0; +} + +$obj2->seconds_watching_video = $seconds_watching_video; +if (empty($_SESSION['addViewCount'][$_REQUEST['id']]['time'])) { + $resp = $obj->addView(); + _session_start(); + $_SESSION['addViewCount'][$_REQUEST['id']]['time'] = strtotime("+{$seconds} seconds"); +} elseif (isset($_REQUEST['currentTime'])) { + $currentTime = intval($_REQUEST['currentTime']); + if ($currentTime<0) { + $currentTime = 0; + } + $resp = VideoStatistic::updateStatistic($obj->getId(), User::getId(), $currentTime, $seconds_watching_video); +} else { + $resp = 0; +} +$count = $obj->getViews_count(); + +$obj2->status = !empty($resp); +$obj2->count = $count; +$obj2->countHTML = number_format_short($count); +$obj2->resp = $resp; + +echo json_encode($obj2); diff --git a/objects/videoCategory.json.php b/objects/videoCategory.json.php index 9d25619dc2..02f7271103 100644 --- a/objects/videoCategory.json.php +++ b/objects/videoCategory.json.php @@ -1,31 +1,31 @@ -userCanManageVideo()) { - $obj->msg = __("You can not Manage This Video"); - die(json_encode($obj)); - } - $obj->setCategories_id($_POST['category_id']); - $resp = $obj->save(); -} -echo '{"status":"' . !empty($resp) . '"}'; +userCanManageVideo()) { + $obj->msg = __("You can not Manage This Video"); + die(json_encode($obj)); + } + $obj->setCategories_id($_POST['category_id']); + $resp = $obj->save(); +} +echo '{"status":"' . !empty($resp) . '"}'; diff --git a/objects/videoDelete.json.php b/objects/videoDelete.json.php index 261397cc8a..31f0c870d9 100644 --- a/objects/videoDelete.json.php +++ b/objects/videoDelete.json.php @@ -1,25 +1,25 @@ -userCanManageVideo()) { - $obj->msg = __("You can not Manage This Video"); - die(json_encode($obj)); - } - $id = $obj->delete(); -} - -echo '{"status":"'.$id.'"}'; +userCanManageVideo()) { + $obj->msg = __("You can not Manage This Video"); + die(json_encode($obj)); + } + $id = $obj->delete(); +} + +echo '{"status":"'.$id.'"}'; diff --git a/objects/videoEditLight.php b/objects/videoEditLight.php index f4803b86be..f39037fea5 100644 --- a/objects/videoEditLight.php +++ b/objects/videoEditLight.php @@ -1,49 +1,48 @@ -videos_id = @$_REQUEST['videos_id']; -$obj->error = true; -$obj->msg = ''; - -if (empty($obj->videos_id)) { - $obj->msg = 'Videos ID empty'; - die(json_encode($obj)); -} - -if (!Video::canEdit($obj->videos_id)) { - $obj->msg = 'You cannot edit this video'; - die(json_encode($obj)); -} - -$video = new Video('', '', $obj->videos_id); - -if(isset($_REQUEST['title'])){ - $video->setTitle($_REQUEST['title']); - $video->setClean_title($_REQUEST['title']); -} -if(isset($_REQUEST['categories_id'])){ - $video->setCategories_id($_REQUEST['categories_id']); -} -if(isset($_REQUEST['description'])){ - $video->setDescription($_REQUEST['description']); -} -if(isset($_REQUEST['image'])){ - $images = Video::getImageFromID($obj->videos_id); - if(!empty($_REQUEST['portrait'])){ - $path = $images->posterPortraitPath; - }else{ - $path = $images->posterLandscapePath; - } - $obj->path = $path; - $obj->image = saveCroppieImage($path, "image"); -} -$obj->save = $video->save(); -$obj->error = empty($obj->save); -if(empty($obj->error)){ - Video::clearCache($obj->videos_id); -} -die(json_encode($obj)); \ No newline at end of file +videos_id = @$_REQUEST['videos_id']; +$obj->error = true; +$obj->msg = ''; + +if (empty($obj->videos_id)) { + $obj->msg = 'Videos ID empty'; + die(json_encode($obj)); +} + +if (!Video::canEdit($obj->videos_id)) { + $obj->msg = 'You cannot edit this video'; + die(json_encode($obj)); +} + +$video = new Video('', '', $obj->videos_id); + +if (isset($_REQUEST['title'])) { + $video->setTitle($_REQUEST['title']); + $video->setClean_title($_REQUEST['title']); +} +if (isset($_REQUEST['categories_id'])) { + $video->setCategories_id($_REQUEST['categories_id']); +} +if (isset($_REQUEST['description'])) { + $video->setDescription($_REQUEST['description']); +} +if (isset($_REQUEST['image'])) { + $images = Video::getImageFromID($obj->videos_id); + if (!empty($_REQUEST['portrait'])) { + $path = $images->posterPortraitPath; + } else { + $path = $images->posterLandscapePath; + } + $obj->path = $path; + $obj->image = saveCroppieImage($path, "image"); +} +$obj->save = $video->save(); +$obj->error = empty($obj->save); +if (empty($obj->error)) { + Video::clearCache($obj->videos_id); +} +die(json_encode($obj)); diff --git a/objects/videoRefresh.json.php b/objects/videoRefresh.json.php index 91cd4cb665..260187a31a 100644 --- a/objects/videoRefresh.json.php +++ b/objects/videoRefresh.json.php @@ -1,43 +1,43 @@ -getFilename(); - -if(!file_exists($file)){ - $file = $global['systemRootPath']."videos/".$obj->getFilename().".mp4"; - if(!file_exists($file)){ - $file = $global['systemRootPath']."videos/".$obj->getFilename().".mp3"; - } -} -if(file_exists($file)){ - $duration = Video::getDurationFromFile($file); - $data = Video::getVideoConversionStatus($obj->getFilename()); - - $obj->setDuration($duration); - if($data->webm->progress == 100 && $data->mp4->progress == 100 && $obj->getStatus()!='i'){ - $obj->setStatus('a'); - } -}else{ - $obj->setStatus('i'); - $obj->setDuration('0:00:00.000000'); -} -$resp = $obj->save(); -$obj->updateDurationIfNeed(); -$obj->updateHLSDurationIfNeed(); -echo '{"status":"'.!empty($resp).'"}'; +getFilename(); + +if (!file_exists($file)) { + $file = $global['systemRootPath']."videos/".$obj->getFilename().".mp4"; + if (!file_exists($file)) { + $file = $global['systemRootPath']."videos/".$obj->getFilename().".mp3"; + } +} +if (file_exists($file)) { + $duration = Video::getDurationFromFile($file); + $data = Video::getVideoConversionStatus($obj->getFilename()); + + $obj->setDuration($duration); + if ($data->webm->progress == 100 && $data->mp4->progress == 100 && $obj->getStatus()!='i') { + $obj->setStatus('a'); + } +} else { + $obj->setStatus('i'); + $obj->setDuration('0:00:00.000000'); +} +$resp = $obj->save(); +$obj->updateDurationIfNeed(); +$obj->updateHLSDurationIfNeed(); +echo '{"status":"'.!empty($resp).'"}'; diff --git a/objects/videoRotate.json.php b/objects/videoRotate.json.php index 3c6d2697dd..effa7ba807 100644 --- a/objects/videoRotate.json.php +++ b/objects/videoRotate.json.php @@ -1,42 +1,42 @@ - "Video not found"]); -} - -$currentRotation = $obj->getRotation(); -$newRotation = $currentRotation; -$status = ["success" => "video rotated"]; - -switch ($type) { -case 'left': - $newRotation = ($currentRotation - 90) % 360; - $status["rotation"] = $newRotation; - $obj->setRotation($newRotation); - break; -case 'right': - $newRotation = ($currentRotation + 90) % 360; - $status["rotation"] = $newRotation; - $obj->setRotation($newRotation); - break; -default: - $status = ["error" => "I don't know how to rotate '{$type}'"]; - break; -} - -status($status); + "Video not found"]); +} + +$currentRotation = $obj->getRotation(); +$newRotation = $currentRotation; +$status = ["success" => "video rotated"]; + +switch ($type) { +case 'left': + $newRotation = ($currentRotation - 90) % 360; + $status["rotation"] = $newRotation; + $obj->setRotation($newRotation); + break; +case 'right': + $newRotation = ($currentRotation + 90) % 360; + $status["rotation"] = $newRotation; + $obj->setRotation($newRotation); + break; +default: + $status = ["error" => "I don't know how to rotate '{$type}'"]; + break; +} + +status($status); diff --git a/objects/videoStatus.json.php b/objects/videoStatus.json.php index c8e71ac8e3..8c8639203f 100644 --- a/objects/videoStatus.json.php +++ b/objects/videoStatus.json.php @@ -1,56 +1,55 @@ -error = true; -$obj->status = array(); -$obj->msg = ''; - -foreach ($_POST['id'] as $value) { - $obj2 = new stdClass(); - $obj2->error = true; - $obj2->videos_id = $value; - $obj2->status = $_POST['status']; - $obj2->msg = ''; - - - $v = new Video("", "", $value); - if (empty($v)) { - $obj2->msg = __("Video NOT Found"); - $obj->status[] = $obj2; - continue; - } - if (!$v->userCanManageVideo() && !Permissions::canModerateVideos()) { - $obj2->msg = __("You can not Manage This Video"); - $obj->status[] = $obj2; - continue; - } - $v->setStatus($_POST['status']); - $obj2->error = false; - $obj->status[] = $obj2; -} - -foreach ($obj->status as $value) { - if($value->error){ - break; - } - $obj->error = false; -} - -die(json_encode($obj)); +error = true; +$obj->status = []; +$obj->msg = ''; + +foreach ($_POST['id'] as $value) { + $obj2 = new stdClass(); + $obj2->error = true; + $obj2->videos_id = $value; + $obj2->status = $_POST['status']; + $obj2->msg = ''; + + $v = new Video("", "", $value); + if (empty($v)) { + $obj2->msg = __("Video NOT Found"); + $obj->status[] = $obj2; + continue; + } + if (!$v->userCanManageVideo() && !Permissions::canModerateVideos()) { + $obj2->msg = __("You can not Manage This Video"); + $obj->status[] = $obj2; + continue; + } + $v->setStatus($_POST['status']); + $obj2->error = false; + $obj->status[] = $obj2; +} + +foreach ($obj->status as $value) { + if ($value->error) { + break; + } + $obj->error = false; +} + +die(json_encode($obj)); diff --git a/objects/videoSuggest.php b/objects/videoSuggest.php index 42664af631..27d608669e 100644 --- a/objects/videoSuggest.php +++ b/objects/videoSuggest.php @@ -1,22 +1,22 @@ -setIsSuggested($_POST['isSuggested']); - $id = $obj->save(); -} - -echo '{"status":"'.$id.'"}'; +setIsSuggested($_POST['isSuggested']); + $id = $obj->save(); +} + +echo '{"status":"'.$id.'"}'; diff --git a/objects/videoSwap.json.php b/objects/videoSwap.json.php index 226d6752a4..3c747c3b46 100644 --- a/objects/videoSwap.json.php +++ b/objects/videoSwap.json.php @@ -1,69 +1,68 @@ -msg = ""; -$obj->error = true; - -if (($advancedCustom->disableVideoSwap) || ($advancedCustom->makeSwapVideosOnlyForAdmin && !Permissions::canModerateVideos())) { - $obj->msg = __("Swap Disabled"); - die(json_encode($obj)); -} - -if (!User::canUpload()) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -if (empty($_POST['videos_id_1']) || empty($_POST['videos_id_2'])) { - $obj->msg = __("Mou MUST select 2 videos to swap"); - die(json_encode($obj)); -} - -$video1 = new Video("", "", $_POST['videos_id_1']); -if (!$video1->userCanManageVideo()) { - $obj->msg = __("You can not Manage This Video 1"); - die(json_encode($obj)); -} - -$video2 = new Video("", "", $_POST['videos_id_2']); -if (!$video2->userCanManageVideo()) { - $obj->msg = __("You can not Manage This Video 2"); - die(json_encode($obj)); -} - -$video1Filename = $video1->getFilename(); -$video1Sites_id = $video1->getSites_id(); -$video1Duration = $video1->getDuration(); - -$video2Filename = $video2->getFilename(); -$video2Sites_id = $video2->getSites_id(); -$video2Duration = $video2->getDuration(); - -$video1->setFilename($video2Filename, true); -$video1->setSites_id($video2Sites_id); -$video1->setDuration($video2Duration); - -$video2->setFilename($video1Filename, true); -$video2->setSites_id($video1Sites_id); -$video2->setDuration($video1Duration); - -$global['mysqli']->autocommit(false); -if(!$video1->save()){ - $obj->msg = __("Error on save video 1"); - die(json_encode($obj)); -} -if(!$video2->save()){ - $obj->msg = __("Error on save video 2"); - die(json_encode($obj)); -} -$video1->setVideoHigestResolution(0); -$video2->setVideoHigestResolution(0); -$global['mysqli']->commit(); -$obj->error = false; -die(json_encode($obj)); +msg = ''; +$obj->error = true; + +if (($advancedCustom->disableVideoSwap) || ($advancedCustom->makeSwapVideosOnlyForAdmin && !Permissions::canModerateVideos())) { + $obj->msg = __("Swap Disabled"); + die(json_encode($obj)); +} + +if (!User::canUpload()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +if (empty($_POST['videos_id_1']) || empty($_POST['videos_id_2'])) { + $obj->msg = __("Mou MUST select 2 videos to swap"); + die(json_encode($obj)); +} + +$video1 = new Video("", "", $_POST['videos_id_1']); +if (!$video1->userCanManageVideo()) { + $obj->msg = __("You can not Manage This Video 1"); + die(json_encode($obj)); +} + +$video2 = new Video("", "", $_POST['videos_id_2']); +if (!$video2->userCanManageVideo()) { + $obj->msg = __("You can not Manage This Video 2"); + die(json_encode($obj)); +} + +$video1Filename = $video1->getFilename(); +$video1Sites_id = $video1->getSites_id(); +$video1Duration = $video1->getDuration(); + +$video2Filename = $video2->getFilename(); +$video2Sites_id = $video2->getSites_id(); +$video2Duration = $video2->getDuration(); + +$video1->setFilename($video2Filename, true); +$video1->setSites_id($video2Sites_id); +$video1->setDuration($video2Duration); + +$video2->setFilename($video1Filename, true); +$video2->setSites_id($video1Sites_id); +$video2->setDuration($video1Duration); + +$global['mysqli']->autocommit(false); +if (!$video1->save()) { + $obj->msg = __("Error on save video 1"); + die(json_encode($obj)); +} +if (!$video2->save()) { + $obj->msg = __("Error on save video 2"); + die(json_encode($obj)); +} +$video1->setVideoHigestResolution(0); +$video2->setVideoHigestResolution(0); +$global['mysqli']->commit(); +$obj->error = false; +die(json_encode($obj)); diff --git a/objects/videoUpdateUsage.json.php b/objects/videoUpdateUsage.json.php index a2a5dc133e..7c2475754e 100644 --- a/objects/videoUpdateUsage.json.php +++ b/objects/videoUpdateUsage.json.php @@ -1,27 +1,27 @@ -msg = ""; -$obj->error = true; - - -if (!Permissions::canModerateVideos()) { - $obj->msg = __("Permission denied"); - die(json_encode($obj)); -} - -$videos = Video::getAllVideosLight("", false, true, false); - -foreach ($videos as $value) { - Video::updateFilesize($value['id']); -} - -$obj->error = false; -die(json_encode($obj)); +msg = ''; +$obj->error = true; + + +if (!Permissions::canModerateVideos()) { + $obj->msg = __("Permission denied"); + die(json_encode($obj)); +} + +$videos = Video::getAllVideosLight("", false, true, false); + +foreach ($videos as $value) { + Video::updateFilesize($value['id']); +} + +$obj->error = false; +die(json_encode($obj)); diff --git a/objects/video_statistic.php b/objects/video_statistic.php index ec026f4c4d..f9fc47d8de 100644 --- a/objects/video_statistic.php +++ b/objects/video_statistic.php @@ -1,599 +1,628 @@ -You need to update your system"; - * return false; - * } - */ - if (empty($videos_id)) { - die(__("You need a video to generate statistics")); - } - - $userId = empty($_SESSION["user"]["id"]) ? "NULL" : $_SESSION["user"]["id"]; - - $lastVideoTime = 0; - if (empty($currentTime)) { - $lastStatistic = self::getLastStatistics($videos_id, $userId); - if (empty($currentTime) && !empty($lastStatistic)) { - $lastVideoTime = intval($lastStatistic['lastVideoTime']); - } - } else { - $lastVideoTime = intval($currentTime); - } - - $sql = "INSERT INTO videos_statistics " - . "(`when`,ip, users_id, videos_id, lastVideoTime, created, modified, session_id) values " - . "(now(),?," . $userId . ",?,{$lastVideoTime},now(),now(),'" . session_id() . "')"; - $insert_row = sqlDAL::writeSql($sql, "si", array(getRealIpAddr(), $videos_id)); - - if (!empty($global['mysqli']->insert_id)) { - return $global['mysqli']->insert_id; - } else { - die($sql . ' Save Video Statistics Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - } - - public static function updateStatistic($videos_id, $users_id, $lastVideoTime, $seconds_watching_video = 0) { - $lastStatistic = self::getLastStatistics($videos_id, $users_id); - if (empty($lastStatistic)) { - $vs = new VideoStatistic(0); - $vs->setUsers_id($users_id); - $vs->setVideos_id($videos_id); - $vs->setWhen(date("Y-m-d h:i:s")); - } else { - $vs = new VideoStatistic($lastStatistic['id']); - } - $vs->setLastVideoTime($lastVideoTime); - - if (!empty($seconds_watching_video) && $seconds_watching_video > 0) { - $totalVideoWatched = $vs->getSeconds_watching_video() + $seconds_watching_video; - _error_log("updateStatistic: add more [$seconds_watching_video] to video [$videos_id] " . get_browser_name()); - $vs->setSeconds_watching_video($totalVideoWatched); - $v = new Video('', '', $videos_id); - $v->addSecondsWatching($seconds_watching_video); - - //$totalVideoSeconds = timeToSeconds($hms); - //Video::addViewPercent(); - } - - $id = $vs->save(); - /* - if(!empty($id)){ - Video::clearCache($videos_id); - } - */ - return $id; - } - - public function save() { - global $global; - if (empty($this->videos_id)) { - return false; - } - $this->setSession_id(session_id()); - if (empty($this->session_id) && empty($this->users_id)) { - return false; - } - if (empty($this->users_id)) { - $this->setUsers_id('null'); - } - - $this->lastVideoTime = intval(@$this->lastVideoTime); - - $this->seconds_watching_video = intval($this->seconds_watching_video); - - $this->json = $global['mysqli']->real_escape_string($this->json); - - return parent::save(); - } - - public static function getLastStatistics($videos_id, $users_id = 0) { - if (!empty($users_id)) { - $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND users_id = ? ORDER BY id DESC LIMIT 1 "; - $res = sqlDAL::readSql($sql, 'ii', array($videos_id, $users_id), true); - } else { - $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND session_id = ? ORDER BY id DESC LIMIT 1 "; - $res = sqlDAL::readSql($sql, 'is', array($videos_id, session_id()), true); - } - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($result)) { - return $result; - } - return false; - } - - public static function getLastVideoTimeFromVideo($videos_id, $users_id) { - $row = self::getLastStatistics($videos_id, $users_id); - if (empty($row)) { - return 0; - } - return intval($row['lastVideoTime']); - } - - public static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startDate = "", $endDate = "") { - global $global; - if ($uniqueUsers) { - $ast = "distinct(users_id)"; - } else { - $ast = "*"; - } - $sql = "SELECT count({$ast}) as total FROM videos_statistics WHERE 1=1 "; - $formats = ""; - $values = array(); - if (!empty($videos_id)) { - $sql .= " AND videos_id = ? "; - $formats .= "i"; - $values[] = $videos_id; - } - if (!empty($startDate)) { - $sql .= " AND `when` >= ? "; - $formats .= "s"; - $values[] = $startDate; - } - - if (!empty($endDate)) { - $sql .= " AND `when` <= ? "; - $formats .= "s"; - $values[] = $endDate; - } - $res = sqlDAL::readSql($sql, $formats, $values); - $result = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - if (!empty($result)) { - //echo "
".$row['total']." --- ".$sql, "
"; - return $result['total']; - } - return 0; - } - - public static function getTotalLastDaysAsync($video_id, $numberOfDays) { - global $global, $advancedCustom; - $md5 = ("{$video_id}_{$numberOfDays}"); - $path = getCacheDir() . "getTotalLastDaysAsync/"; - make_path($path); - $cacheFileName = "{$path}{$md5}"; - if (!file_exists($cacheFileName)) { - if (file_exists($cacheFileName . ".lock")) { - return array(); - } - $total = static::getTotalLastDays($video_id, $numberOfDays); - file_put_contents($cacheFileName, json_encode($total)); - return $total; - } - $return = _json_decode(file_get_contents($cacheFileName)); - if (time() - filemtime($cacheFileName) > 60) { - // file older than 1 min - $command = ("php '{$global['systemRootPath']}objects/getTotalLastDaysAsync.php' '$video_id' '$numberOfDays' '$cacheFileName'"); - _error_log("getTotalLastDaysAsync: {$command}"); - exec($command . " > /dev/null 2>/dev/null &"); - } - return $return; - } - - public static function getTotalLastDays($video_id, $numberOfDays, $returnArray = array()) { - if ($numberOfDays < 0) { - return $returnArray; - } - $date = date("Y-m-d", strtotime("-{$numberOfDays} days")); - $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . " 00:00:00", $date . " 23:59:59"); - $numberOfDays--; - return static::getTotalLastDays($video_id, $numberOfDays, $returnArray); - } - - public static function getTotalToday($video_id, $hour = 0, $returnArray = array()) { - if ($hour >= 24) { - return $returnArray; - } - $date = date("Y-m-d {$hour}", time()); - //echo $date;exit; - $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . ":00:00", $date . ":59:59"); - $hour++; - return static::getTotalToday($video_id, $hour, $returnArray); - } - - public static function getTotalTodayAsync($video_id) { - global $global, $advancedCustom; - $cacheFileName = getCacheDir() . "getTotalTodayAsync_{$video_id}"; - if (!file_exists($cacheFileName)) { - if (file_exists($cacheFileName . ".lock")) { - return array(); - } - $total = static::getTotalToday($video_id); - file_put_contents($cacheFileName, json_encode($total)); - return $total; - } - $return = _json_decode(file_get_contents($cacheFileName)); - if (time() - filemtime($cacheFileName) > 60) { - // file older than 1 min - $command = ("php '{$global['systemRootPath']}objects/getTotalTodayAsync.php' '$video_id' '$cacheFileName'"); - _error_log("getTotalTodayAsync: {$command}"); - exec($command . " > /dev/null 2>/dev/null &"); - } - return $return; - } - - public function getWhen() { - return $this->when; - } - - public function getIp() { - return $this->ip; - } - - public function getUsers_id() { - return $this->users_id; - } - - public function getVideos_id() { - return $this->videos_id; - } - - public function getLastVideoTime() { - return $this->lastVideoTime; - } - - public function setWhen($when) { - $this->when = $when; - } - - public function setIp($ip) { - $this->ip = $ip; - } - - public function setUsers_id($users_id) { - $this->users_id = intval($users_id); - if (empty($this->users_id)) { - $this->users_id = 'null'; - } - } - - public function setVideos_id($videos_id) { - $this->videos_id = intval($videos_id); - } - - public function setLastVideoTime($lastVideoTime) { - $this->lastVideoTime = intval($lastVideoTime); - } - - public function getSession_id() { - return $this->session_id; - } - - public function setSession_id($session_id) { - $this->session_id = $session_id; - } - - public static function getChannelsWithMoreViews($daysLimit = 30) { - global $global; - $cacheName3 = "getChannelsWithMoreViews{$daysLimit}" . DIRECTORY_SEPARATOR . md5(json_encode(array($_GET, $_POST))); - $cache = ObjectYPT::getCache($cacheName3, 3600); // 1 hour cache - if (!empty($cache)) { - _error_log('getChannelsWithMoreViews cache found ' . $cacheName3); - return object_to_array($cache); - } else { - _error_log('getChannelsWithMoreViews no cache found ' . $cacheName3); - } - - // get unique videos ids from the requested timeframe - $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE DATE(`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; - $channels = array(); - $channelsPerUser = array(); - $cacheName2 = "getChannelsWithMoreViews" . DIRECTORY_SEPARATOR . md5($sql); - $cache2 = ObjectYPT::getCache($cacheName2, 3600); // 1 hour cache - if (!empty($cache2)) { - $channelsPerUser = object_to_array($cache2); - } - - if (empty($channelsPerUser)) { - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - // get the channel owner from each of those videos - foreach ($fullData as $row) { - $users_id = Video::getOwner($row['videos_id']); - if (empty($channelsPerUser[$users_id])) { - $channelsPerUser[$users_id] = array(); - } - $channelsPerUser[$users_id][] = $row['videos_id']; - } - } - $response = ObjectYPT::setCache($cacheName2, $channelsPerUser); - } - - if (!empty($channelsPerUser)) { - foreach ($channelsPerUser as $key => $value) { - // count how many views each one has - $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id IN (" . implode(",", $value) . ") AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; - $res2 = sqlDAL::readSql($sql2); - $result2 = sqlDAL::fetchAssoc($res2); - sqlDAL::close($res2); - if (!empty($result2)) { - $channels[$key]['users_id'] = $key; - $channels[$key]['total'] = intval($result2['total']); - } - } - - // return more first - usort($channels, function ($a, $b) { - return $a['total'] - $b['total']; - }); - } - $response = ObjectYPT::setCache($cacheName3, $channels); - _error_log('getChannelsWithMoreViews cache saved [' . json_encode($response) . '] ' . $cacheName3); - return $channels; - } - - public static function getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly, $daysLimit = 30) { - global $global; - // get unique videos ids from the requested timeframe - $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics s " - . " LEFT JOIN videos v ON v.id = videos_id " - . " WHERE DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; - - if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { - $sql .= " AND v.users_id = '" . User::getId() . "'"; - } elseif (!empty($showOnlyLoggedUserVideos)) { - $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; - } - - if (!empty($_GET['channelName'])) { - $user = User::getChannelOwner($_GET['channelName']); - $sql .= " AND v.users_id = '{$user['id']}' "; - } - 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}'"; - } - $sql .= AVideoPlugin::getVideoWhereClause(); - - if ($suggestedOnly) { - $sql .= " AND v.isSuggested = 1 "; - } - - $sql .= static::getSqlLimit(); - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $channels = array(); - $videos = array(); - if ($res != false) { - foreach ($fullData as $key => $value) { - // count how many views each one has - $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id = {$value['videos_id']} AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; - - $res2 = sqlDAL::readSql($sql2); - $result2 = sqlDAL::fetchAssoc($res2); - sqlDAL::close($res2); - if (!empty($result2)) { - $video = Video::getVideo($value['videos_id'], $status, false, false, $suggestedOnly, $showUnlisted, false, $showOnlyLoggedUserVideos); - if (empty($video)) { - continue; - } - unset($video['title']); - unset($video['description']); - unset($video['descriptionHTML']); - $video['total'] = $result2['total']; - $videos[] = $video; - } - } - } - // return more first - usort($videos, function ($a, $b) { - return $a['total'] - $b['total']; - }); - return $videos; - } - - public static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) { - $channels = self::getChannelsWithMoreViews($daysLimit); - $users_id = array(); - foreach ($channels as $value) { - $users_id[] = $value['users_id']; - } - return $users_id; - } - - public static function getChannelsTotalViews($users_id, $daysLimit = 30) { - global $global; - $cacheName = "getChannelsTotalViews($users_id, $daysLimit)"; - $cache = ObjectYPT::getCache($cacheName, 3600); // 1 hour cache - if (!empty($cache)) { - return intval($cache); - } - $users_id = intval($users_id); - // count how many views each one has - $sql2 = "SELECT count(s.id) as total FROM videos_statistics s " - . " LEFT JOIN videos v ON v.id = videos_id WHERE v.users_id = $users_id " - . " AND DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; - $res2 = sqlDAL::readSql($sql2); - $result2 = sqlDAL::fetchAssoc($res2); - sqlDAL::close($res2); - $result = 0; - if (!empty($result2)) { - $result = intval($result2['total']); - } - ObjectYPT::setCache($cacheName, $result); - return $result; - } - - public static function getTotalStatisticsRecords() { - global $global; - $sql2 = "SELECT count(s.id) as total FROM videos_statistics s "; - $res2 = sqlDAL::readSql($sql2); - $result2 = sqlDAL::fetchAssoc($res2); - sqlDAL::close($res2); - $result = 0; - if (!empty($result2)) { - return intval($result2['total']); - } - ObjectYPT::setCache($cacheName, $result); - return 0; - } - - public static function deleteOldStatistics($days) { - global $global; - $days = intval($days); - if (!empty($days)) { - $sql = "DELETE FROM " . static::getTableName() . " "; - $sql .= " WHERE created < DATE_SUB(NOW(), INTERVAL ? DAY) "; - $global['lastQuery'] = $sql; - //_error_log("Delete Query: ".$sql); - return sqlDAL::writeSql($sql, "i", array($days)); - } - _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); - return false; - } - - function getSeconds_watching_video() { - return intval($this->seconds_watching_video); - } - - function setSeconds_watching_video($seconds_watching_video) { - $this->seconds_watching_video = intval($seconds_watching_video); - } - - function getJson() { - return $this->json; - } - - function setJson($json) { - if(!is_string($json)){ - $json = _json_encode($json); - } - $this->json = $json; - } - - public static function getAllFromVideos_id($videos_id) { - global $global; - if (!static::isTableInstalled()) { - return false; - } - - $videos_id = intval($videos_id); - - if (empty($videos_id)) { - return false; - } - - $sql = "SELECT u.*, vs.* FROM " . static::getTableName() . " vs LEFT JOIN users u ON vs.users_id = u.id WHERE videos_id=$videos_id "; - - $sql .= self::getSqlFromPost(); - //var_dump($_POST['searchPhrase'], $_GET['search']['value'], $sql);exit; - $res = sqlDAL::readSql($sql); - $fullData = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - $rows = array(); - if ($res != false) { - - $isPluginEnabled = AVideoPlugin::isEnabledByName('User_Location'); - - foreach ($fullData as $row) { - $row['users'] = User::getNameIdentificationById($row['users_id']); - $row['when_human'] = humanTimingAgo($row['when']); - $row['seconds_watching_video_human'] = seconds2human($row['seconds_watching_video']); - if ($isPluginEnabled) { - - $json = _json_decode($row['json']); - if (empty($json)) { - $json = new stdClass(); - } - if (empty($json->location)) { - $json->location = User_Location::getLocationFromIP($row['ip']); - $vs = new VideoStatistic($row['id']); - $vs->setJson($json); - $vs->save(); - } - $json->location = object_to_array($json->location); - $row['location'] = $json->location; - if(empty($json->location['country_name']) || $json->location['country_name'] === '-'){ - $row['location_name'] = $row['ip']; - }else{ - $row['location_name'] = "{$json->location['country_name']}, {$json->location['city_name']}, {$json->location['region_name']}"; - } - - } else { - $row['location_name'] = $row['location'] = ''; - } - $rows[] = $row; - } - } else { - die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); - } - return $rows; - } - - public static function getTotalFromVideos_id($videos_id) { - global $global; - if (!static::isTableInstalled()) { - return false; - } - - $videos_id = intval($videos_id); - - if (empty($videos_id)) { - return false; - } - - $sql = "SELECT count(vs.id) as total FROM " . static::getTableName() . " vs LEFT JOIN users u ON vs.users_id = u.id WHERE videos_id=$videos_id "; - - $sql .= self::getSqlSearchFromPost(); - - //echo $sql;//exit; - $res = sqlDAL::readSql($sql); - $result = sqlDAL::fetchAssoc($res); - if (!empty($result)) { - return intval($result['total']); - } - return 0; - } - - - -} +You need to update your system"; + * return false; + * } + */ + if (empty($videos_id)) { + die(__("You need a video to generate statistics")); + } + + $userId = empty($_SESSION["user"]["id"]) ? "NULL" : $_SESSION["user"]["id"]; + + $lastVideoTime = 0; + if (empty($currentTime)) { + $lastStatistic = self::getLastStatistics($videos_id, $userId); + if (empty($currentTime) && !empty($lastStatistic)) { + $lastVideoTime = intval($lastStatistic['lastVideoTime']); + } + } else { + $lastVideoTime = intval($currentTime); + } + + $sql = "INSERT INTO videos_statistics " + . "(`when`,ip, users_id, videos_id, lastVideoTime, created, modified, session_id) values " + . "(now(),?," . $userId . ",?,{$lastVideoTime},now(),now(),'" . session_id() . "')"; + $insert_row = sqlDAL::writeSql($sql, "si", [getRealIpAddr(), $videos_id]); + + if (!empty($global['mysqli']->insert_id)) { + return $global['mysqli']->insert_id; + } else { + die($sql . ' Save Video Statistics Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + } + + public static function updateStatistic($videos_id, $users_id, $lastVideoTime, $seconds_watching_video = 0) + { + $lastStatistic = self::getLastStatistics($videos_id, $users_id); + if (empty($lastStatistic)) { + $vs = new VideoStatistic(0); + $vs->setUsers_id($users_id); + $vs->setVideos_id($videos_id); + $vs->setWhen(date("Y-m-d h:i:s")); + } else { + $vs = new VideoStatistic($lastStatistic['id']); + } + $vs->setLastVideoTime($lastVideoTime); + + if (!empty($seconds_watching_video) && $seconds_watching_video > 0) { + $totalVideoWatched = $vs->getSeconds_watching_video() + $seconds_watching_video; + _error_log("updateStatistic: add more [$seconds_watching_video] to video [$videos_id] " . get_browser_name()); + $vs->setSeconds_watching_video($totalVideoWatched); + $v = new Video('', '', $videos_id); + $v->addSecondsWatching($seconds_watching_video); + + //$totalVideoSeconds = timeToSeconds($hms); + //Video::addViewPercent(); + } + + $id = $vs->save(); + /* + if(!empty($id)){ + Video::clearCache($videos_id); + } + */ + return $id; + } + + public function save() + { + global $global; + if (empty($this->videos_id)) { + return false; + } + $this->setSession_id(session_id()); + if (empty($this->session_id) && empty($this->users_id)) { + return false; + } + if (empty($this->users_id)) { + $this->setUsers_id('null'); + } + + $this->lastVideoTime = intval(@$this->lastVideoTime); + + $this->seconds_watching_video = intval($this->seconds_watching_video); + + $this->json = $global['mysqli']->real_escape_string($this->json); + + return parent::save(); + } + + public static function getLastStatistics($videos_id, $users_id = 0) + { + if (!empty($users_id)) { + $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND users_id = ? ORDER BY id DESC LIMIT 1 "; + $res = sqlDAL::readSql($sql, 'ii', [$videos_id, $users_id], true); + } else { + $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND session_id = ? ORDER BY id DESC LIMIT 1 "; + $res = sqlDAL::readSql($sql, 'is', [$videos_id, session_id()], true); + } + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($result)) { + return $result; + } + return false; + } + + public static function getLastVideoTimeFromVideo($videos_id, $users_id) + { + $row = self::getLastStatistics($videos_id, $users_id); + if (empty($row)) { + return 0; + } + return intval($row['lastVideoTime']); + } + + public static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startDate = "", $endDate = "") + { + global $global; + if ($uniqueUsers) { + $ast = "distinct(users_id)"; + } else { + $ast = "*"; + } + $sql = "SELECT count({$ast}) as total FROM videos_statistics WHERE 1=1 "; + $formats = ''; + $values = []; + if (!empty($videos_id)) { + $sql .= " AND videos_id = ? "; + $formats .= "i"; + $values[] = $videos_id; + } + if (!empty($startDate)) { + $sql .= " AND `when` >= ? "; + $formats .= "s"; + $values[] = $startDate; + } + + if (!empty($endDate)) { + $sql .= " AND `when` <= ? "; + $formats .= "s"; + $values[] = $endDate; + } + $res = sqlDAL::readSql($sql, $formats, $values); + $result = sqlDAL::fetchAssoc($res); + sqlDAL::close($res); + if (!empty($result)) { + //echo "
".$row['total']." --- ".$sql, "
"; + return $result['total']; + } + return 0; + } + + public static function getTotalLastDaysAsync($video_id, $numberOfDays) + { + global $global, $advancedCustom; + $md5 = ("{$video_id}_{$numberOfDays}"); + $path = getCacheDir() . "getTotalLastDaysAsync/"; + make_path($path); + $cacheFileName = "{$path}{$md5}"; + if (!file_exists($cacheFileName)) { + if (file_exists($cacheFileName . ".lock")) { + return []; + } + $total = static::getTotalLastDays($video_id, $numberOfDays); + file_put_contents($cacheFileName, json_encode($total)); + return $total; + } + $return = _json_decode(file_get_contents($cacheFileName)); + if (time() - filemtime($cacheFileName) > 60) { + // file older than 1 min + $command = ("php '{$global['systemRootPath']}objects/getTotalLastDaysAsync.php' '$video_id' '$numberOfDays' '$cacheFileName'"); + _error_log("getTotalLastDaysAsync: {$command}"); + exec($command . " > /dev/null 2>/dev/null &"); + } + return $return; + } + + public static function getTotalLastDays($video_id, $numberOfDays, $returnArray = []) + { + if ($numberOfDays < 0) { + return $returnArray; + } + $date = date("Y-m-d", strtotime("-{$numberOfDays} days")); + $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . " 00:00:00", $date . " 23:59:59"); + $numberOfDays--; + return static::getTotalLastDays($video_id, $numberOfDays, $returnArray); + } + + public static function getTotalToday($video_id, $hour = 0, $returnArray = []) + { + if ($hour >= 24) { + return $returnArray; + } + $date = date("Y-m-d {$hour}", time()); + //echo $date;exit; + $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . ":00:00", $date . ":59:59"); + $hour++; + return static::getTotalToday($video_id, $hour, $returnArray); + } + + public static function getTotalTodayAsync($video_id) + { + global $global, $advancedCustom; + $cacheFileName = getCacheDir() . "getTotalTodayAsync_{$video_id}"; + if (!file_exists($cacheFileName)) { + if (file_exists($cacheFileName . ".lock")) { + return []; + } + $total = static::getTotalToday($video_id); + file_put_contents($cacheFileName, json_encode($total)); + return $total; + } + $return = _json_decode(file_get_contents($cacheFileName)); + if (time() - filemtime($cacheFileName) > 60) { + // file older than 1 min + $command = ("php '{$global['systemRootPath']}objects/getTotalTodayAsync.php' '$video_id' '$cacheFileName'"); + _error_log("getTotalTodayAsync: {$command}"); + exec($command . " > /dev/null 2>/dev/null &"); + } + return $return; + } + + public function getWhen() + { + return $this->when; + } + + public function getIp() + { + return $this->ip; + } + + public function getUsers_id() + { + return $this->users_id; + } + + public function getVideos_id() + { + return $this->videos_id; + } + + public function getLastVideoTime() + { + return $this->lastVideoTime; + } + + public function setWhen($when) + { + $this->when = $when; + } + + public function setIp($ip) + { + $this->ip = $ip; + } + + public function setUsers_id($users_id) + { + $this->users_id = intval($users_id); + if (empty($this->users_id)) { + $this->users_id = 'null'; + } + } + + public function setVideos_id($videos_id) + { + $this->videos_id = intval($videos_id); + } + + public function setLastVideoTime($lastVideoTime) + { + $this->lastVideoTime = intval($lastVideoTime); + } + + public function getSession_id() + { + return $this->session_id; + } + + public function setSession_id($session_id) + { + $this->session_id = $session_id; + } + + public static function getChannelsWithMoreViews($daysLimit = 30) + { + global $global; + $cacheName3 = "getChannelsWithMoreViews{$daysLimit}" . DIRECTORY_SEPARATOR . md5(json_encode([$_GET, $_POST])); + $cache = ObjectYPT::getCache($cacheName3, 3600); // 1 hour cache + if (!empty($cache)) { + _error_log('getChannelsWithMoreViews cache found ' . $cacheName3); + return object_to_array($cache); + } else { + _error_log('getChannelsWithMoreViews no cache found ' . $cacheName3); + } + + // get unique videos ids from the requested timeframe + $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE DATE(`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; + $channels = []; + $channelsPerUser = []; + $cacheName2 = "getChannelsWithMoreViews" . DIRECTORY_SEPARATOR . md5($sql); + $cache2 = ObjectYPT::getCache($cacheName2, 3600); // 1 hour cache + if (!empty($cache2)) { + $channelsPerUser = object_to_array($cache2); + } + + if (empty($channelsPerUser)) { + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + if ($res != false) { + // get the channel owner from each of those videos + foreach ($fullData as $row) { + $users_id = Video::getOwner($row['videos_id']); + if (empty($channelsPerUser[$users_id])) { + $channelsPerUser[$users_id] = []; + } + $channelsPerUser[$users_id][] = $row['videos_id']; + } + } + $response = ObjectYPT::setCache($cacheName2, $channelsPerUser); + } + + if (!empty($channelsPerUser)) { + foreach ($channelsPerUser as $key => $value) { + // count how many views each one has + $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id IN (" . implode(",", $value) . ") AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; + $res2 = sqlDAL::readSql($sql2); + $result2 = sqlDAL::fetchAssoc($res2); + sqlDAL::close($res2); + if (!empty($result2)) { + $channels[$key]['users_id'] = $key; + $channels[$key]['total'] = intval($result2['total']); + } + } + + // return more first + usort($channels, function ($a, $b) { + return $a['total'] - $b['total']; + }); + } + $response = ObjectYPT::setCache($cacheName3, $channels); + _error_log('getChannelsWithMoreViews cache saved [' . json_encode($response) . '] ' . $cacheName3); + return $channels; + } + + public static function getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly, $daysLimit = 30) + { + global $global; + // get unique videos ids from the requested timeframe + $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics s " + . " LEFT JOIN videos v ON v.id = videos_id " + . " WHERE DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; + + if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { + $sql .= " AND v.users_id = '" . User::getId() . "'"; + } elseif (!empty($showOnlyLoggedUserVideos)) { + $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; + } + + if (!empty($_GET['channelName'])) { + $user = User::getChannelOwner($_GET['channelName']); + $sql .= " AND v.users_id = '{$user['id']}' "; + } + 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}'"; + } + $sql .= AVideoPlugin::getVideoWhereClause(); + + if ($suggestedOnly) { + $sql .= " AND v.isSuggested = 1 "; + } + + $sql .= static::getSqlLimit(); + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $channels = []; + $videos = []; + if ($res != false) { + foreach ($fullData as $key => $value) { + // count how many views each one has + $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id = {$value['videos_id']} AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; + + $res2 = sqlDAL::readSql($sql2); + $result2 = sqlDAL::fetchAssoc($res2); + sqlDAL::close($res2); + if (!empty($result2)) { + $video = Video::getVideo($value['videos_id'], $status, false, false, $suggestedOnly, $showUnlisted, false, $showOnlyLoggedUserVideos); + if (empty($video)) { + continue; + } + unset($video['title']); + unset($video['description']); + unset($video['descriptionHTML']); + $video['total'] = $result2['total']; + $videos[] = $video; + } + } + } + // return more first + usort($videos, function ($a, $b) { + return $a['total'] - $b['total']; + }); + return $videos; + } + + public static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) + { + $channels = self::getChannelsWithMoreViews($daysLimit); + $users_id = []; + foreach ($channels as $value) { + $users_id[] = $value['users_id']; + } + return $users_id; + } + + public static function getChannelsTotalViews($users_id, $daysLimit = 30) + { + global $global; + $cacheName = "getChannelsTotalViews($users_id, $daysLimit)"; + $cache = ObjectYPT::getCache($cacheName, 3600); // 1 hour cache + if (!empty($cache)) { + return intval($cache); + } + $users_id = intval($users_id); + // count how many views each one has + $sql2 = "SELECT count(s.id) as total FROM videos_statistics s " + . " LEFT JOIN videos v ON v.id = videos_id WHERE v.users_id = $users_id " + . " AND DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; + $res2 = sqlDAL::readSql($sql2); + $result2 = sqlDAL::fetchAssoc($res2); + sqlDAL::close($res2); + $result = 0; + if (!empty($result2)) { + $result = intval($result2['total']); + } + ObjectYPT::setCache($cacheName, $result); + return $result; + } + + public static function getTotalStatisticsRecords() + { + global $global; + $sql2 = "SELECT count(s.id) as total FROM videos_statistics s "; + $res2 = sqlDAL::readSql($sql2); + $result2 = sqlDAL::fetchAssoc($res2); + sqlDAL::close($res2); + $result = 0; + if (!empty($result2)) { + return intval($result2['total']); + } + ObjectYPT::setCache($cacheName, $result); + return 0; + } + + public static function deleteOldStatistics($days) + { + global $global; + $days = intval($days); + if (!empty($days)) { + $sql = "DELETE FROM " . static::getTableName() . " "; + $sql .= " WHERE created < DATE_SUB(NOW(), INTERVAL ? DAY) "; + $global['lastQuery'] = $sql; + //_error_log("Delete Query: ".$sql); + return sqlDAL::writeSql($sql, "i", [$days]); + } + _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); + return false; + } + + public function getSeconds_watching_video() + { + return intval($this->seconds_watching_video); + } + + public function setSeconds_watching_video($seconds_watching_video) + { + $this->seconds_watching_video = intval($seconds_watching_video); + } + + public function getJson() + { + return $this->json; + } + + public function setJson($json) + { + if (!is_string($json)) { + $json = _json_encode($json); + } + $this->json = $json; + } + + public static function getAllFromVideos_id($videos_id) + { + global $global; + if (!static::isTableInstalled()) { + return false; + } + + $videos_id = intval($videos_id); + + if (empty($videos_id)) { + return false; + } + + $sql = "SELECT u.*, vs.* FROM " . static::getTableName() . " vs LEFT JOIN users u ON vs.users_id = u.id WHERE videos_id=$videos_id "; + + $sql .= self::getSqlFromPost(); + //var_dump($_POST['searchPhrase'], $_GET['search']['value'], $sql);exit; + $res = sqlDAL::readSql($sql); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = []; + if ($res != false) { + $isPluginEnabled = AVideoPlugin::isEnabledByName('User_Location'); + + foreach ($fullData as $row) { + $row['users'] = User::getNameIdentificationById($row['users_id']); + $row['when_human'] = humanTimingAgo($row['when']); + $row['seconds_watching_video_human'] = seconds2human($row['seconds_watching_video']); + if ($isPluginEnabled) { + $json = _json_decode($row['json']); + if (empty($json)) { + $json = new stdClass(); + } + if (empty($json->location)) { + $json->location = User_Location::getLocationFromIP($row['ip']); + $vs = new VideoStatistic($row['id']); + $vs->setJson($json); + $vs->save(); + } + $json->location = object_to_array($json->location); + $row['location'] = $json->location; + if (empty($json->location['country_name']) || $json->location['country_name'] === '-') { + $row['location_name'] = $row['ip']; + } else { + $row['location_name'] = "{$json->location['country_name']}, {$json->location['city_name']}, {$json->location['region_name']}"; + } + } else { + $row['location_name'] = $row['location'] = ''; + } + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + public static function getTotalFromVideos_id($videos_id) + { + global $global; + if (!static::isTableInstalled()) { + return false; + } + + $videos_id = intval($videos_id); + + if (empty($videos_id)) { + return false; + } + + $sql = "SELECT count(vs.id) as total FROM " . static::getTableName() . " vs LEFT JOIN users u ON vs.users_id = u.id WHERE videos_id=$videos_id "; + + $sql .= self::getSqlSearchFromPost(); + + //echo $sql;//exit; + $res = sqlDAL::readSql($sql); + $result = sqlDAL::fetchAssoc($res); + if (!empty($result)) { + return intval($result['total']); + } + return 0; + } +} diff --git a/objects/video_statistic_getTotalLastDays.php b/objects/video_statistic_getTotalLastDays.php index 6dc27ee575..b7527ae441 100644 --- a/objects/video_statistic_getTotalLastDays.php +++ b/objects/video_statistic_getTotalLastDays.php @@ -1,18 +1,17 @@ - $value) { - /* - $video = new Video('', '', $value['id']); - $video->setStatus(Video::$statusActive); - Video::clearCache($value['id']);continue; - */ - unset($value['password'], $value['recoverPass']); - $name = empty($value['name']) ? $value['user'] : $value['name']; - $videos[$key]['creator'] = '
User Photo
' . $name . '' . User::getEmailVerifiedIcon($value['users_id']) . ' ' . humanTiming(strtotime($value['videoCreation'])) . '
'; - $videos[$key]['next_video'] = array(); - $videos[$key]['description'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['description']); - $videos[$key]['title'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['title']); - $videos[$key]['clean_title'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['clean_title']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $videos[$key]['typeLabels'] = Video::getVideoTypeLabels($videos[$key]['filename']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $videos[$key]['maxResolution'] = Video::getHigestResolution($videos[$key]['filename']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - if (!empty($videos[$key]['next_videos_id'])) { - unset($_POST['searchPhrase']); - $videos[$key]['next_video'] = Video::getVideo($videos[$key]['next_videos_id']); - } -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - if ($videos[$key]['type'] == 'article') { - $videos[$key]['videosURL'] = getVideosURLArticle($videos[$key]['filename']); - } elseif ($videos[$key]['type'] == 'image') { - $videos[$key]['videosURL'] = getVideosURLIMAGE($videos[$key]['filename']); - } elseif ($videos[$key]['type'] == 'zip') { - $videos[$key]['videosURL'] = getVideosURLZIP($videos[$key]['filename']); - } elseif ($videos[$key]['type'] == 'pdf') { - $videos[$key]['videosURL'] = getVideosURLPDF($videos[$key]['filename']); - } elseif ($videos[$key]['type'] == 'audio') { -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $videos[$key]['videosURL'] = getVideosURLAudio($videos[$key]['filename']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - Video::checkIfIsBroken($value['id']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - } else { -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - $videos[$key]['videosURL'] = getVideosURL($videos[$key]['filename']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - Video::checkIfIsBroken($value['id']); -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); - } - unset($videos[$key]['password'], $videos[$key]['recoverPass']); -} - -TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); -$obj = new stdClass(); -$obj->users_id = User::getId(); -$obj->current = getCurrentPage(); -$obj->rowCount = getRowCount(); -$obj->total = $total; -$obj->rows = $videos; -$obj->status = $status; -$obj->process_duration = microtime(true)-$start; - -die(json_encode($obj)); -exit; + $value) { + /* + $video = new Video('', '', $value['id']); + $video->setStatus(Video::$statusActive); + Video::clearCache($value['id']);continue; + */ + unset($value['password'], $value['recoverPass']); + $name = empty($value['name']) ? $value['user'] : $value['name']; + $videos[$key]['creator'] = '
User Photo
' . $name . '' . User::getEmailVerifiedIcon($value['users_id']) . ' ' . humanTiming(strtotime($value['videoCreation'])) . '
'; + $videos[$key]['next_video'] = []; + $videos[$key]['description'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['description']); + $videos[$key]['title'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['title']); + $videos[$key]['clean_title'] = preg_replace('/[\x00-\x1F\x7F]/u', '', $videos[$key]['clean_title']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $videos[$key]['typeLabels'] = Video::getVideoTypeLabels($videos[$key]['filename']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $videos[$key]['maxResolution'] = Video::getHigestResolution($videos[$key]['filename']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + if (!empty($videos[$key]['next_videos_id'])) { + unset($_POST['searchPhrase']); + $videos[$key]['next_video'] = Video::getVideo($videos[$key]['next_videos_id']); + } + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + if ($videos[$key]['type'] == 'article') { + $videos[$key]['videosURL'] = getVideosURLArticle($videos[$key]['filename']); + } elseif ($videos[$key]['type'] == 'image') { + $videos[$key]['videosURL'] = getVideosURLIMAGE($videos[$key]['filename']); + } elseif ($videos[$key]['type'] == 'zip') { + $videos[$key]['videosURL'] = getVideosURLZIP($videos[$key]['filename']); + } elseif ($videos[$key]['type'] == 'pdf') { + $videos[$key]['videosURL'] = getVideosURLPDF($videos[$key]['filename']); + } elseif ($videos[$key]['type'] == 'audio') { + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $videos[$key]['videosURL'] = getVideosURLAudio($videos[$key]['filename']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + Video::checkIfIsBroken($value['id']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + } else { + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + $videos[$key]['videosURL'] = getVideosURL($videos[$key]['filename']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + Video::checkIfIsBroken($value['id']); + TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); + } + unset($videos[$key]['password'], $videos[$key]['recoverPass']); +} + +TimeLogEnd($timeLogName, __LINE__, $TimeLogLimit); +$obj = new stdClass(); +$obj->users_id = User::getId(); +$obj->current = getCurrentPage(); +$obj->rowCount = getRowCount(); +$obj->total = $total; +$obj->rows = $videos; +$obj->status = $status; +$obj->process_duration = microtime(true)-$start; + +die(json_encode($obj)); +exit; diff --git a/objects/videos.txt.php b/objects/videos.txt.php index d48c29153d..29b4f3c6c7 100644 --- a/objects/videos.txt.php +++ b/objects/videos.txt.php @@ -1,7 +1,7 @@ $value) { - if(empty($_GET['type'])){ + if (empty($_GET['type'])) { echo Video::getPermaLink($videos[$key]['id']); - }else{ + } else { echo Video::getURLFriendlyFromCleanTitle($videos[$key]['clean_title']); } echo PHP_EOL; diff --git a/objects/videosAndroid.json.php b/objects/videosAndroid.json.php index f99696fd61..e4cb1ead8c 100644 --- a/objects/videosAndroid.json.php +++ b/objects/videosAndroid.json.php @@ -1,86 +1,85 @@ -login(false, true); -} - -$objMob = AVideoPlugin::getObjectData("MobileManager"); -if(!empty($random)){ - $video = Video::getVideo("", "viewableNotUnlisted", true, false, true); - if (empty($video)) { - $video = Video::getVideo("", "viewableNotUnlisted", true, true); - } - $videos = array($video); - $total = 1; -}else if ($objMob->netflixStyle) { - $videos = Video::getAllVideos("viewableNotUnlisted", false, true); - $total = Video::getTotalVideos("viewableNotUnlisted", false, true); -} else { - $videos = Video::getAllVideos("viewable"); - $total = Video::getTotalVideos("viewable"); -} - -foreach ($videos as $key => $value) { - unset($videos[$key]['password'], $videos[$key]['recoverPass']); - $images = Video::getImageFromFilename($videos[$key]['filename'], $videos[$key]['type']); - $videos[$key]['images'] = $images; - $videos[$key]['Poster'] = !empty($objMob->portraitImage) ? $images->posterPortrait : $images->poster; - $videos[$key]['Thumbnail'] = !empty($objMob->portraitImage) ? $images->posterPortraitThumbs : $images->thumbsJpg; - $videos[$key]['imageClass'] = !empty($objMob->portraitImage) ? "portrait" : "landscape"; - $videos[$key]['VideoUrl'] = getVideosURL($videos[$key]['filename']); - $videos[$key]['createdHumanTiming'] = humanTiming(strtotime($videos[$key]['created'])); - $videos[$key]['pageUrl'] = "{$global['webSiteRootURL']}video/" . $videos[$key]['clean_title']; - $videos[$key]['embedUrl'] = "{$global['webSiteRootURL']}videoEmbeded/" . $videos[$key]['clean_title']; - unset($_POST['sort'], $_POST['current'], $_POST['searchPhrase']); - $_REQUEST['rowCount'] = 10; - $_POST['sort']['created'] = "desc"; - $videos[$key]['comments'] = Comment::getAllComments($videos[$key]['id']); - $videos[$key]['commentsTotal'] = Comment::getTotalComments($videos[$key]['id']); - foreach ($videos[$key]['comments'] as $key2 => $value2) { - $user = new User($value2['users_id']); - $videos[$key]['comments'][$key2]['userPhotoURL'] = User::getPhoto($videos[$key]['comments'][$key2]['users_id']); - $videos[$key]['comments'][$key2]['userName'] = $user->getNameIdentificationBd(); - } - $videos[$key]['subscribers'] = Subscribe::getTotalSubscribes($videos[$key]['users_id']); - - $videos[$key]['firstVideo'] = ""; - foreach ($videos[$key]['VideoUrl'] as $value2) { - if ($value2["type"] === 'video') { - $videos[$key]['firstVideo'] = $value2["url"]; - break; - } - } - $videos[$key]['UserPhoto'] = User::getPhoto($videos[$key]['users_id']); -} - -$obj = new stdClass(); -$obj->current = $_POST['current']; -$obj->rowCount = $_POST['rowCount']; -$obj->total = $total; -$obj->videos = $videos; -echo json_encode($obj); -//AVideoPlugin::getEnd(); +login(false, true); +} + +$objMob = AVideoPlugin::getObjectData("MobileManager"); +if (!empty($random)) { + $video = Video::getVideo("", "viewableNotUnlisted", true, false, true); + if (empty($video)) { + $video = Video::getVideo("", "viewableNotUnlisted", true, true); + } + $videos = [$video]; + $total = 1; +} elseif ($objMob->netflixStyle) { + $videos = Video::getAllVideos("viewableNotUnlisted", false, true); + $total = Video::getTotalVideos("viewableNotUnlisted", false, true); +} else { + $videos = Video::getAllVideos("viewable"); + $total = Video::getTotalVideos("viewable"); +} + +foreach ($videos as $key => $value) { + unset($videos[$key]['password'], $videos[$key]['recoverPass']); + $images = Video::getImageFromFilename($videos[$key]['filename'], $videos[$key]['type']); + $videos[$key]['images'] = $images; + $videos[$key]['Poster'] = !empty($objMob->portraitImage) ? $images->posterPortrait : $images->poster; + $videos[$key]['Thumbnail'] = !empty($objMob->portraitImage) ? $images->posterPortraitThumbs : $images->thumbsJpg; + $videos[$key]['imageClass'] = !empty($objMob->portraitImage) ? "portrait" : "landscape"; + $videos[$key]['VideoUrl'] = getVideosURL($videos[$key]['filename']); + $videos[$key]['createdHumanTiming'] = humanTiming(strtotime($videos[$key]['created'])); + $videos[$key]['pageUrl'] = "{$global['webSiteRootURL']}video/" . $videos[$key]['clean_title']; + $videos[$key]['embedUrl'] = "{$global['webSiteRootURL']}videoEmbeded/" . $videos[$key]['clean_title']; + unset($_POST['sort'], $_POST['current'], $_POST['searchPhrase']); + $_REQUEST['rowCount'] = 10; + $_POST['sort']['created'] = "desc"; + $videos[$key]['comments'] = Comment::getAllComments($videos[$key]['id']); + $videos[$key]['commentsTotal'] = Comment::getTotalComments($videos[$key]['id']); + foreach ($videos[$key]['comments'] as $key2 => $value2) { + $user = new User($value2['users_id']); + $videos[$key]['comments'][$key2]['userPhotoURL'] = User::getPhoto($videos[$key]['comments'][$key2]['users_id']); + $videos[$key]['comments'][$key2]['userName'] = $user->getNameIdentificationBd(); + } + $videos[$key]['subscribers'] = Subscribe::getTotalSubscribes($videos[$key]['users_id']); + + $videos[$key]['firstVideo'] = ''; + foreach ($videos[$key]['VideoUrl'] as $value2) { + if ($value2["type"] === 'video') { + $videos[$key]['firstVideo'] = $value2["url"]; + break; + } + } + $videos[$key]['UserPhoto'] = User::getPhoto($videos[$key]['users_id']); +} + +$obj = new stdClass(); +$obj->current = $_POST['current']; +$obj->rowCount = $_POST['rowCount']; +$obj->total = $total; +$obj->videos = $videos; +echo json_encode($obj); +//AVideoPlugin::getEnd(); diff --git a/objects/youtubeUpload.json.php b/objects/youtubeUpload.json.php index 17310a1814..3010a657ad 100644 --- a/objects/youtubeUpload.json.php +++ b/objects/youtubeUpload.json.php @@ -1,144 +1,144 @@ -success = false; -require_once $global['systemRootPath'] . 'objects/functions.php'; -header('Content-Type: application/json'); - -$obj = AVideoPlugin::getObjectData("LoginGoogle"); -$OAUTH2_CLIENT_ID = $obj->id; -$OAUTH2_CLIENT_SECRET = $obj->key; -/* - * You can acquire an OAuth 2.0 client ID and client secret from the - * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> - * For more information about using OAuth 2.0 to access Google APIs, please see: - * - * Please ensure that you have enabled the YouTube Data API for your project. - */ -$client = new Google_Client(); -$client->setClientId($OAUTH2_CLIENT_ID); -$client->setClientSecret($OAUTH2_CLIENT_SECRET); -$client->setScopes('https://www.googleapis.com/auth/youtube'); -//$redirectUri = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],FILTER_SANITIZE_URL); -$redirectUri = "{$global['webSiteRootURL']}objects/youtubeUpload.json.php"; -$redirect = "{$global['webSiteRootURL']}mvideos"; -$client->setRedirectUri($redirectUri); -// Define an object that will be used to make all API requests. -$youtube = new Google_Service_YouTube($client); -// Check if an auth token exists for the required scopes -$tokenSessionKey = 'token-' . $client->prepareScopes(); -if (isset($_GET['code'])) { - if (strval($_SESSION['state']) !== strval($_GET['state'])) { - die('The session state did not match.'); - } - $client->authenticate($_GET['code']); - $_SESSION[$tokenSessionKey] = $client->getAccessToken(); - header('Location: ' . $redirect); -} -if (!is_array($_POST['id'])) { - $_POST['id'] = array($_POST['id']); -} -foreach ($_POST['id'] as $value) { - $v = new Video("", "", $value); - if (!$v->userCanManageVideo()) { - $obj->msg = __("You can not Manage This Video"); - die(json_encode($obj)); - } - if (isset($_SESSION[$tokenSessionKey])) { - $client->setAccessToken($_SESSION[$tokenSessionKey]); - } - // Check to ensure that the access token was successfully acquired. - if ($client->getAccessToken()) { - try { - // REPLACE this value with the path to the file you are uploading. - $videoPath = $v->getExistingVideoFile(); - // Create a snippet with title, description, tags and category ID - // Create an asset resource and set its snippet metadata and type. - // This example sets the video's title, description, keyword tags, and - // video category. - $snippet = new Google_Service_YouTube_VideoSnippet(); - $snippet->setTitle($v->getTitle()); - $snippet->setDescription($v->getDescription()); - $snippet->setTags(array("AVideo", $config->getWebSiteTitle())); - // Numeric video category. See - // https://developers.google.com/youtube/v3/docs/videoCategories/list - // $snippet->setCategoryId("22"); - // Set the video's status to "public". Valid statuses are "public", - // "private" and "unlisted". - $status = new Google_Service_YouTube_VideoStatus(); - $status->privacyStatus = "public"; - // Associate the snippet and status objects with a new video resource. - $video = new Google_Service_YouTube_Video(); - $video->setSnippet($snippet); - $video->setStatus($status); - // Specify the size of each chunk of data, in bytes. Set a higher value for - // reliable connection as fewer chunks lead to faster uploads. Set a lower - // value for better recovery on less reliable connections. - $chunkSizeBytes = 1 * 1024 * 1024; - // Setting the defer flag to true tells the client to return a request which can be called - // with ->execute(); instead of making the API call immediately. - $client->setDefer(true); - // Create a request for the API's videos.insert method to create and upload the video. - $insertRequest = $youtube->videos->insert("status,snippet", $video); - // Create a MediaFileUpload object for resumable uploads. - - _error_log("youtubeUpload: videoPath:: ". json_encode($videoPath)); - _error_log("youtubeUpload: title:: ".$v->getTitle()); - _error_log("youtubeUpload: videoPath:: {$videoPath}"); - - $media = new Google_Http_MediaFileUpload( - $client, - $insertRequest, - 'video/*', - null, - true, - $chunkSizeBytes - ); - $media->setFileSize(filesize($videoPath)); - // Read the media file and upload it chunk by chunk. - $status = false; - $handle = fopen($videoPath, "rb"); - while (!$status && !feof($handle)) { - $chunk = fread($handle, $chunkSizeBytes); - $status = $media->nextChunk($chunk); - } - fclose($handle); - // If you want to make other calls after the file upload, set setDefer back to false - $client->setDefer(false); - $obj->success = true; - $obj->title = $status['snippet']['title']; - $obj->id = $status['id']; - $obj->status = $status; - $obj->msg = sprintf(__("Your video %s was uploaded to your YouTube Account
"), $obj->id, $obj->title); - $v->setYoutubeId($obj->id); - $v->save(); - } catch (Google_Service_Exception $e) { - $obj->msg = sprintf(__("A service error occurred [1]: %s"), $e->getMessage()); - } catch (Google_Exception $e) { - $obj->msg = sprintf(__("An client error occurred [2]: %s"), $e->getMessage()); - } - $_SESSION[$tokenSessionKey] = $client->getAccessToken(); - } elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') { - $obj->msg = "

Client Credentials Required

-

- You need to set \$OAUTH2_CLIENT_ID and - \$OAUTH2_CLIENT_ID before proceeding. -

"; - } else { - // If the user hasn't authorized the app, initiate the OAuth flow - $state = mt_rand(); - $client->setState($state); - $_SESSION['state'] = $state; - $authUrl = $client->createAuthUrl(); - $obj->msg = "

Authorization Required

You need to authorize access before proceeding.

"; - } -} - -echo json_encode($obj); +success = false; +require_once $global['systemRootPath'] . 'objects/functions.php'; +header('Content-Type: application/json'); + +$obj = AVideoPlugin::getObjectData("LoginGoogle"); +$OAUTH2_CLIENT_ID = $obj->id; +$OAUTH2_CLIENT_SECRET = $obj->key; +/* + * You can acquire an OAuth 2.0 client ID and client secret from the + * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> + * For more information about using OAuth 2.0 to access Google APIs, please see: + * + * Please ensure that you have enabled the YouTube Data API for your project. + */ +$client = new Google_Client(); +$client->setClientId($OAUTH2_CLIENT_ID); +$client->setClientSecret($OAUTH2_CLIENT_SECRET); +$client->setScopes('https://www.googleapis.com/auth/youtube'); +//$redirectUri = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],FILTER_SANITIZE_URL); +$redirectUri = "{$global['webSiteRootURL']}objects/youtubeUpload.json.php"; +$redirect = "{$global['webSiteRootURL']}mvideos"; +$client->setRedirectUri($redirectUri); +// Define an object that will be used to make all API requests. +$youtube = new Google_Service_YouTube($client); +// Check if an auth token exists for the required scopes +$tokenSessionKey = 'token-' . $client->prepareScopes(); +if (isset($_GET['code'])) { + if (strval($_SESSION['state']) !== strval($_GET['state'])) { + die('The session state did not match.'); + } + $client->authenticate($_GET['code']); + $_SESSION[$tokenSessionKey] = $client->getAccessToken(); + header('Location: ' . $redirect); +} +if (!is_array($_POST['id'])) { + $_POST['id'] = [$_POST['id']]; +} +foreach ($_POST['id'] as $value) { + $v = new Video("", "", $value); + if (!$v->userCanManageVideo()) { + $obj->msg = __("You can not Manage This Video"); + die(json_encode($obj)); + } + if (isset($_SESSION[$tokenSessionKey])) { + $client->setAccessToken($_SESSION[$tokenSessionKey]); + } + // Check to ensure that the access token was successfully acquired. + if ($client->getAccessToken()) { + try { + // REPLACE this value with the path to the file you are uploading. + $videoPath = $v->getExistingVideoFile(); + // Create a snippet with title, description, tags and category ID + // Create an asset resource and set its snippet metadata and type. + // This example sets the video's title, description, keyword tags, and + // video category. + $snippet = new Google_Service_YouTube_VideoSnippet(); + $snippet->setTitle($v->getTitle()); + $snippet->setDescription($v->getDescription()); + $snippet->setTags(["AVideo", $config->getWebSiteTitle()]); + // Numeric video category. See + // https://developers.google.com/youtube/v3/docs/videoCategories/list + // $snippet->setCategoryId("22"); + // Set the video's status to "public". Valid statuses are "public", + // "private" and "unlisted". + $status = new Google_Service_YouTube_VideoStatus(); + $status->privacyStatus = "public"; + // Associate the snippet and status objects with a new video resource. + $video = new Google_Service_YouTube_Video(); + $video->setSnippet($snippet); + $video->setStatus($status); + // Specify the size of each chunk of data, in bytes. Set a higher value for + // reliable connection as fewer chunks lead to faster uploads. Set a lower + // value for better recovery on less reliable connections. + $chunkSizeBytes = 1 * 1024 * 1024; + // Setting the defer flag to true tells the client to return a request which can be called + // with ->execute(); instead of making the API call immediately. + $client->setDefer(true); + // Create a request for the API's videos.insert method to create and upload the video. + $insertRequest = $youtube->videos->insert("status,snippet", $video); + // Create a MediaFileUpload object for resumable uploads. + + _error_log("youtubeUpload: videoPath:: ". json_encode($videoPath)); + _error_log("youtubeUpload: title:: ".$v->getTitle()); + _error_log("youtubeUpload: videoPath:: {$videoPath}"); + + $media = new Google_Http_MediaFileUpload( + $client, + $insertRequest, + 'video/*', + null, + true, + $chunkSizeBytes + ); + $media->setFileSize(filesize($videoPath)); + // Read the media file and upload it chunk by chunk. + $status = false; + $handle = fopen($videoPath, "rb"); + while (!$status && !feof($handle)) { + $chunk = fread($handle, $chunkSizeBytes); + $status = $media->nextChunk($chunk); + } + fclose($handle); + // If you want to make other calls after the file upload, set setDefer back to false + $client->setDefer(false); + $obj->success = true; + $obj->title = $status['snippet']['title']; + $obj->id = $status['id']; + $obj->status = $status; + $obj->msg = sprintf(__("Your video %s was uploaded to your YouTube Account
"), $obj->id, $obj->title); + $v->setYoutubeId($obj->id); + $v->save(); + } catch (Google_Service_Exception $e) { + $obj->msg = sprintf(__("A service error occurred [1]: %s"), $e->getMessage()); + } catch (Google_Exception $e) { + $obj->msg = sprintf(__("An client error occurred [2]: %s"), $e->getMessage()); + } + $_SESSION[$tokenSessionKey] = $client->getAccessToken(); + } elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') { + $obj->msg = "

Client Credentials Required

+

+ You need to set \$OAUTH2_CLIENT_ID and + \$OAUTH2_CLIENT_ID before proceeding. +

"; + } else { + // If the user hasn't authorized the app, initiate the OAuth flow + $state = mt_rand(); + $client->setState($state); + $_SESSION['state'] = $state; + $authUrl = $client->createAuthUrl(); + $obj->msg = "

Authorization Required

You need to authorize access before proceeding.

"; + } +} + +echo json_encode($obj); diff --git a/view/about.php b/view/about.php index 074087dd12..6fc88b55e1 100644 --- a/view/about.php +++ b/view/about.php @@ -1,79 +1,79 @@ - - - - - <?php echo __("About") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - -

-
-
- getAbout(); - } - if (empty($custom)) { - ?> -

-
-

-
-
-
- getVersion()); ?> - - - - - - - -
- - : () - - - - - - - -
-
- -
- - - - - + + + + + <?php echo __("About") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + +
+
+
+ getAbout(); + } + if (empty($custom)) { + ?> +

+
+

+
+
+
+ getVersion()); ?> + + + + + + + +
+ + : () + + + + + + + +
+
+ +
+ + + + + diff --git a/view/channel.php b/view/channel.php index 887fe927c1..09b1d1de12 100644 --- a/view/channel.php +++ b/view/channel.php @@ -1,57 +1,57 @@ -getStatus() === 'i') { - forbiddenPage(__("This user is inactive")); -} -$isMyChannel = $user_id == User::getId(); - -$channelPassword = User::getProfilePassword($user_id); -if(!empty($channelPassword)){ - forbiddenPage('This channel is password protected',false, $channelPassword); -} -AVideoPlugin::getChannel($user_id, $user); -$channelFluidLayout = true; -// verify the width to match with the old profile bg image -$bgImagePath = $global['systemRootPath'] . $user->getBackgroundURL(); -$bgSize = getimagesize($bgImagePath); -if ($bgSize[0] < 2048) { - $channelFluidLayout = false; -} -$metaDescription = " Channel - {$_GET['channelName']}"; -?> - - - - <?php echo @$_GET['channelName'] . $config->getPageTitleSeparator() . __("Channel") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - -
"> - -
- - - +getStatus() === 'i') { + forbiddenPage(__("This user is inactive")); +} +$isMyChannel = $user_id == User::getId(); + +$channelPassword = User::getProfilePassword($user_id); +if (!empty($channelPassword)) { + forbiddenPage('This channel is password protected', false, $channelPassword); +} +AVideoPlugin::getChannel($user_id, $user); +$channelFluidLayout = true; +// verify the width to match with the old profile bg image +$bgImagePath = $global['systemRootPath'] . $user->getBackgroundURL(); +$bgSize = getimagesize($bgImagePath); +if ($bgSize[0] < 2048) { + $channelFluidLayout = false; +} +$metaDescription = " Channel - {$_GET['channelName']}"; +?> + + + + <?php echo @$_GET['channelName'] . $config->getPageTitleSeparator() . __("Channel") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + +
"> + +
+ + + diff --git a/view/channelBody.php b/view/channelBody.php index 23a261b12e..54b84b278f 100644 --- a/view/channelBody.php +++ b/view/channelBody.php @@ -1,321 +1,308 @@ -getBdId() != $user_id) { - header("Location: {$global['webSiteRootURL']}channels"); - exit; -} - -$_GET['channelName'] = $user->getChannelName(); -$timeLog = __FILE__ . " - channelName: {$_GET['channelName']}"; -TimeLogStart($timeLog); -$_POST['sort']['created'] = "DESC"; - -if (empty($_GET['current'])) { - $_POST['current'] = 1; -} else { - $_POST['current'] = $_GET['current']; -} -$current = $_POST['current']; -$rowCount = 25; -$_REQUEST['rowCount'] = $rowCount; - -$uploadedVideos = Video::getAllVideos("a", $user_id, !isToHidePrivateVideos()); -$uploadedTotalVideos = Video::getTotalVideos("a", $user_id, !isToHidePrivateVideos()); -TimeLogEnd($timeLog, __LINE__); -$totalPages = ceil($uploadedTotalVideos / $rowCount); - -unset($_POST['sort']); -unset($_POST['rowCount']); -unset($_POST['current']); - -$get = array('channelName' => $_GET['channelName']); -$palyListsObj = AVideoPlugin::getObjectDataIfEnabled('PlayLists'); -TimeLogEnd($timeLog, __LINE__); -$obj = AVideoPlugin::getObjectData("YouPHPFlix2"); -?> - - - -
-
-
- -
-
- +getBdId() != $user_id) { + header("Location: {$global['webSiteRootURL']}channels"); + exit; +} + +$_GET['channelName'] = $user->getChannelName(); +$timeLog = __FILE__ . " - channelName: {$_GET['channelName']}"; +TimeLogStart($timeLog); +$_POST['sort']['created'] = "DESC"; + +if (empty($_GET['current'])) { + $_POST['current'] = 1; +} else { + $_POST['current'] = $_GET['current']; +} +$current = $_POST['current']; +$rowCount = 25; +$_REQUEST['rowCount'] = $rowCount; + +$uploadedVideos = Video::getAllVideos("a", $user_id, !isToHidePrivateVideos()); +$uploadedTotalVideos = Video::getTotalVideos("a", $user_id, !isToHidePrivateVideos()); +TimeLogEnd($timeLog, __LINE__); +$totalPages = ceil($uploadedTotalVideos / $rowCount); + +unset($_POST['sort']); +unset($_POST['rowCount']); +unset($_POST['current']); + +$get = ['channelName' => $_GET['channelName']]; +$palyListsObj = AVideoPlugin::getObjectDataIfEnabled('PlayLists'); +TimeLogEnd($timeLog, __LINE__); +$obj = AVideoPlugin::getObjectData("YouPHPFlix2"); +?> + + + +
+
+
+ +
+
+ \ No newline at end of file diff --git a/view/channelHead.php b/view/channelHead.php index 3211d77696..bbc83e6592 100644 --- a/view/channelHead.php +++ b/view/channelHead.php @@ -1,32 +1,32 @@ - - - - - \ No newline at end of file diff --git a/view/channelPlaylist.php b/view/channelPlaylist.php index 73c0c5e1d5..2887203755 100644 --- a/view/channelPlaylist.php +++ b/view/channelPlaylist.php @@ -1,91 +1,91 @@ -
-

- -

-
-
- -
-
- \ No newline at end of file diff --git a/view/channelPlaylistItems.php b/view/channelPlaylistItems.php index 1dccbd4d60..679d4bc705 100644 --- a/view/channelPlaylistItems.php +++ b/view/channelPlaylistItems.php @@ -1,601 +1,573 @@ - -
- " . __('Sorry you do not have anything available') . "
"; - } - - die(""); - } - $playListsObj = AVideoPlugin::getObjectData("PlayLists"); - TimeLogEnd($timeLog2, __LINE__); - $channelName = @$_GET['channelName']; - unset($_GET['channelName']); - $startC = microtime(true); - TimeLogEnd($timeLog2, __LINE__); - - $countSuccess = 0; - $get = array(); - if (!empty($_GET['channelName'])) { - $get = array('channelName' => $_GET['channelName']); - } - $program = AVideoPlugin::loadPluginIfEnabled('PlayLists'); - foreach ($playlists as $key => $playlist) { - @$timesC[__LINE__] += microtime(true) - $startC; - $startC = microtime(true); - $_REQUEST['current'] = 1; - $_REQUEST['rowCount'] = 6; - $videosArrayId = PlayList::getVideosIdFromPlaylist($playlist['id']); - $_REQUEST['current'] = 1; - $_REQUEST['rowCount'] = 6; - @$timesC[__LINE__] += microtime(true) - $startC; - $startC = microtime(true); - $rowCount = $_POST['rowCount']; - $_REQUEST['rowCount'] = 6; - - //getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true) - if (empty($videosArrayId) && ($playlist['status'] == "favorite" || $playlist['status'] == "watch_later")) { - unset($playlists[$key]); - continue; - } else if (empty($videosArrayId)) { - $videosP = array(); - } else { - $videosP = Video::getAllVideos("viewable", false, true, $videosArrayId, false, true); - }//var_dump($videosArrayId, $videosP); exit; - - $totalDuration = 0; - foreach ($videosP as $value) { - $totalDuration += durationToSeconds($value['duration']); - } - - $_REQUEST['rowCount'] = $rowCount; - @$timesC[__LINE__] += microtime(true) - $startC; - $startC = microtime(true); - //_error_log("channelPlaylist videosP: ".json_encode($videosP)); - $videosP = PlayList::sortVideos($videosP, $videosArrayId); - @$timesC[__LINE__] += microtime(true) - $startC; - $startC = microtime(true); - //_error_log("channelPlaylist videosP2: ".json_encode($videosP)); - //_error_log("channelPlaylist videosArrayId: ".json_encode($videosArrayId)); - $playListButtons = AVideoPlugin::getPlayListButtons($playlist['id']); - @$timesC[__LINE__] += microtime(true) - $startC; - $startC = microtime(true); - $countSuccess++; - ?> - -
-
- - - () - - - - - -
- - - embedCodeTemplate); - echo ($code); - ?>'/> - - - - - - - - - - - - - -
-
- - - -
- thumbsGif; - $poster = $images->thumbsJpg; - $category = new Category($serie['categories_id']); - ?> -
-
-
- <?php echo $serie['title']; ?> -
-
- - - - -
- - getIconClass())) { - ?> - - - getName(); ?> - - label === __("Group")) { - ?> - text; ?> - -
- - - - - - - - - -
-

- -

-
-
-
- -
- thumbsGif; - $poster = $images->thumbsJpg; - $class = ""; - ?> -
- - <?php echo $value['title']; ?> - - -
-
-
- -
- - - - -
- - - -
- -
- - - -
-
- label === __("Group")) { - ?> - text; ?> - -
- doNotDisplayViews)) { - ?> -
- - - - -
- - -
- - -
-
- - -
- -
- - - -
- - -
- - - -
- -
-
- -
- - - - -
- - - - -

- + +

+ " . __('Sorry you do not have anything available') . "
"; + } + + die(""); + } + $playListsObj = AVideoPlugin::getObjectData("PlayLists"); + TimeLogEnd($timeLog2, __LINE__); + $channelName = @$_GET['channelName']; + unset($_GET['channelName']); + $startC = microtime(true); + TimeLogEnd($timeLog2, __LINE__); + + $countSuccess = 0; + $get = []; + if (!empty($_GET['channelName'])) { + $get = ['channelName' => $_GET['channelName']]; + } + $program = AVideoPlugin::loadPluginIfEnabled('PlayLists'); + foreach ($playlists as $key => $playlist) { + @$timesC[__LINE__] += microtime(true) - $startC; + $startC = microtime(true); + $_REQUEST['current'] = 1; + $_REQUEST['rowCount'] = 6; + $videosArrayId = PlayList::getVideosIdFromPlaylist($playlist['id']); + $_REQUEST['current'] = 1; + $_REQUEST['rowCount'] = 6; + @$timesC[__LINE__] += microtime(true) - $startC; + $startC = microtime(true); + $rowCount = $_POST['rowCount']; + $_REQUEST['rowCount'] = 6; + + //getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true) + if (empty($videosArrayId) && ($playlist['status'] == "favorite" || $playlist['status'] == "watch_later")) { + unset($playlists[$key]); + continue; + } elseif (empty($videosArrayId)) { + $videosP = []; + } else { + $videosP = Video::getAllVideos("viewable", false, true, $videosArrayId, false, true); + }//var_dump($videosArrayId, $videosP); exit; + + $totalDuration = 0; + foreach ($videosP as $value) { + $totalDuration += durationToSeconds($value['duration']); + } + + $_REQUEST['rowCount'] = $rowCount; + @$timesC[__LINE__] += microtime(true) - $startC; + $startC = microtime(true); + //_error_log("channelPlaylist videosP: ".json_encode($videosP)); + $videosP = PlayList::sortVideos($videosP, $videosArrayId); + @$timesC[__LINE__] += microtime(true) - $startC; + $startC = microtime(true); + //_error_log("channelPlaylist videosP2: ".json_encode($videosP)); + //_error_log("channelPlaylist videosArrayId: ".json_encode($videosArrayId)); + $playListButtons = AVideoPlugin::getPlayListButtons($playlist['id']); + @$timesC[__LINE__] += microtime(true) - $startC; + $startC = microtime(true); + $countSuccess++; ?> + +
+
+ + + () + + + + + +
+ + + embedCodeTemplate); + echo($code); ?>'/> + + + + + + + + + + + + + +
+
+ + + +
+ thumbsGif; + $poster = $images->thumbsJpg; + $category = new Category($serie['categories_id']); ?> +
+
+
+ <?php echo $serie['title']; ?> +
+
+ + + + +
+ + getIconClass())) { + ?> + + + getName(); ?> + + label === __("Group")) { + ?> + text; ?> + +
+ + + + + + + + + +
+

+ +

+
+
+
+ +
+ thumbsGif; + $poster = $images->thumbsJpg; + $class = ''; ?> +
+ + <?php echo $value['title']; ?> + + +
+
+
+ +
+ + + + +
+ + + +
+ +
+ + + +
+
+ label === __("Group")) { + ?> + text; ?> + +
+ doNotDisplayViews)) { + ?> +
+ + + + +
+ + +
+ + +
+
+ + +
+ +
+ + + +
+ + +
+ + + +
+ +
+
+ +
+ + + + +
+ + + + +

+

\ No newline at end of file diff --git a/view/channelProgram.php b/view/channelProgram.php index e298fbff1e..fa162fa1c4 100644 --- a/view/channelProgram.php +++ b/view/channelProgram.php @@ -1,741 +1,720 @@ -getUsers_id(); -} -$user_id = $_GET['user_id']; - -$publicOnly = true; -$isMyChannel = false; -if (User::isLogged() && $user_id == User::getId()) { - $publicOnly = false; - $isMyChannel = true; -} - -$programs = PlayList::getAllFromUser($user_id, $publicOnly, false, @$_GET['program_id']); -if (empty($programs)) { - $programs = PlayList::getAllFromUser($user_id, $publicOnly); -} else { - $videosArrayId = PlayList::getVideosIdFromPlaylist($_GET['program_id']); - $videos_id = @$videosArrayId[0]; -} -$playListsObj = AVideoPlugin::getObjectData("PlayLists"); -?> - - - - <?php echo __("Program") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - - - - - - - - - - - - - +getUsers_id(); +} +$user_id = $_GET['user_id']; + +$publicOnly = true; +$isMyChannel = false; +if (User::isLogged() && $user_id == User::getId()) { + $publicOnly = false; + $isMyChannel = true; +} + +$programs = PlayList::getAllFromUser($user_id, $publicOnly, false, @$_GET['program_id']); +if (empty($programs)) { + $programs = PlayList::getAllFromUser($user_id, $publicOnly); +} else { + $videosArrayId = PlayList::getVideosIdFromPlaylist($_GET['program_id']); + $videos_id = @$videosArrayId[0]; +} +$playListsObj = AVideoPlugin::getObjectData("PlayLists"); +?> + + + + <?php echo __("Program") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/view/channels.php b/view/channels.php index b90b6c8c1f..cd07857232 100644 --- a/view/channels.php +++ b/view/channels.php @@ -1,160 +1,156 @@ - - - - - <?php echo __("Channels") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - -
-
-
-
-
-
- " value="" /> - - - -
-
-
-
-
-
    -
- $value['channelName']); - ?> -
-
- User Photo - - - - -
- - -
-
- - -
- -
-
-
- - - - + + + + + <?php echo __("Channels") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + +
+
+
+
+
+
+ " value="" /> + + + +
+
+
+
+
+
    +
+ $value['channelName']]; ?> +
+
+ User Photo + + + + +
+ + +
+
+ + +
+ +
+
+
+ + + + diff --git a/view/charts.php b/view/charts.php index e3b6d4a756..16f237458b 100644 --- a/view/charts.php +++ b/view/charts.php @@ -1,24 +1,24 @@ - - - - - <?php echo __("Dashboard") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - + + + + + <?php echo __("Dashboard") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + diff --git a/view/charts_body.php b/view/charts_body.php index de1812bb3f..a5a3603ab4 100644 --- a/view/charts_body.php +++ b/view/charts_body.php @@ -1,48 +1,48 @@ - -
- - -
-
- -
- - - - -
-
- - - + + \ No newline at end of file diff --git a/view/charts_head.php b/view/charts_head.php index 861988aff0..46cca7d969 100644 --- a/view/charts_head.php +++ b/view/charts_head.php @@ -1,76 +1,76 @@ -getAuthCanViewChart() == 0 && !User::canUpload()) { - forbiddenPage("Only video uploaders can see charts"); - } - if ($config->getAuthCanViewChart() == 1) { - // mode 1 means selected users see admin-charts. - if (empty($_SESSION['user']['canViewChart'])) { - forbiddenPage("Admin did not give you right to see the chart"); - } - } -} - -?> - - - \ No newline at end of file diff --git a/view/configurations.php b/view/configurations.php index 2b4b8480f6..e7e698403e 100644 --- a/view/configurations.php +++ b/view/configurations.php @@ -1,40 +1,40 @@ - - - - - <?php echo __("Configuration") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - -
- -
- - - - + + + + + <?php echo __("Configuration") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + +
+ +
+ + + + diff --git a/view/configurations_body.php b/view/configurations_body.php index 713cb42c82..1a39eb3125 100644 --- a/view/configurations_body.php +++ b/view/configurations_body.php @@ -1,861 +1,839 @@ - - -
-
-
- - -
-
-
-
-
-

-
- -

- - -

-
- - -
-
-
-
-
-
- " class="img-responsive"> - - Purchase the Customize Plugin - - Customize Colors - -
-
- -
- getTheme(); - foreach ($themes as $fileEx) { - if ($fileEx == $savedTheme) { - ?> - - -
-
-
-
- - " class="img-responsive img-radio"> - - -
-
-
- -
- -
-
- -
-
-
- - - $secondsTotal) { - - $percent = intval($secondsTotal / $secondsLimit * 100); - } else { - $percent = 100; - } - ?> and you have minutes of storage -
-
- % of your storage limit used -
-
- - -
- -
- - is Present -
- -
- - Your server is , you must install Apache -
- - - - -
- - PHP is present. -
- -
- - Your PHP version is . PHP 7.3 or newer is required. -
- - - -
- - Your videos directory is writable -
- -
- - Your videos directory must be writable -
- - The video directory does not exists, AVideo had no permition to create it, you must create it manualy! -
-
sudo mkdir 
- -
- Then you can set the permissions. -
-
sudo chmod -R 777 
-
-
- - - -
- - Your post_max_size is -
- -
- - Your post_max_size is , it must be at least 100M - -
- Edit the php.ini file -
-
sudo nano 
-
-
- - - -
- - Your upload_max_filesize is -
- -
- - Your upload_max_filesize is , it must be at least 100M - -
- Edit the php.ini file -
-
sudo nano 
-
-
- - -
-
- -
-
- -
-

-
-
- -
-
- - getLanguage(), 'inputLanguage'); - ?> -
-
-
- -
- -
-
- - " class="form-control" type="email" value="getContactEmail(); ?>" > -
- -
-
- -
- -
-
- - -
-
-
- -
- -
-
- - -
-
-
- -
- -
-
- - - -
-
-
- -
- -
-
- getAutoplay())) { - echo "checked"; - } - ?> > - -
-
-
- -
-
- -
-
-
-

-
- -
- -
-
- - " class="form-control" type="text" value="getWebSiteTitle(); ?>" > -
-
-
-
- -
- - -
- -
-
- -
-
- -
- -
- -
-
-
-
-
-
- -
-
-
-

-
- -
-
- - -
-
-
- -
- - -
- : https://encoder1.avideo.com/ or - -
-
-
- -
- -
- -
-
- - -
- -
-
- getDisable_analytics())) { - echo "checked"; - } - ?> aria-describedby="disable_analyticsHelp"> - -
- -
-
- -
- -
- -
- getDisable_youtubeupload())) { - echo "checked"; - } - ?> > - -
-
-
- -
- -
-
- getAllow_download())) { - echo "checked"; - } - ?> aria-describedby="allow_downloadHelp"> - -
- -
-
-
-
- -
-
- -
-

Email Configuration

-
- -
-

- - , - -

-
- - -
- -
-
- getSmtp())) { - echo "checked"; - } - ?> > - -
-
-
-
- -
-
- getSmtpAuth())) { - echo "checked"; - } - ?> > - -
-
-
- -
- -
- - -
-
- -
- -
- - -
-
- -
- -
- -
-
- -
- -
- -
-
- -
- -
- getSmtpPassword() . '"', __("SMTP Password")); - ?> -
-
-
- -
- -
-
- -
-
-
-
- - - -

- -
-
-
- -
- - - - - - - - - : https://analytics.google.com
- -
-
-
- -
- - -
-
-
-
- -
- -
- -
- - - + + +
+
+
+ + +
+
+
+
+
+

+
+ +

+ + +

+
+ + +
+
+
+
+
+
+ " class="img-responsive"> + + Purchase the Customize Plugin + + Customize Colors + +
+
+ +
+ getTheme(); + foreach ($themes as $fileEx) { + if ($fileEx == $savedTheme) { + ?> + + +
+
+
+
+ + " class="img-responsive img-radio"> + + +
+
+
+ +
+ +
+
+ +
+
+
+ + + $secondsTotal) { + $percent = intval($secondsTotal / $secondsLimit * 100); + } else { + $percent = 100; + } ?> and you have minutes of storage +
+
+ % of your storage limit used +
+
+ + +
+ +
+ + is Present +
+ +
+ + Your server is , you must install Apache +
+ + + + +
+ + PHP is present. +
+ +
+ + Your PHP version is . PHP 7.3 or newer is required. +
+ + + +
+ + Your videos directory is writable +
+ +
+ + Your videos directory must be writable +
+ + The video directory does not exists, AVideo had no permition to create it, you must create it manualy! +
+
sudo mkdir 
+ +
+ Then you can set the permissions. +
+
sudo chmod -R 777 
+
+
+ + + +
+ + Your post_max_size is +
+ +
+ + Your post_max_size is , it must be at least 100M + +
+ Edit the php.ini file +
+
sudo nano 
+
+
+ + + +
+ + Your upload_max_filesize is +
+ +
+ + Your upload_max_filesize is , it must be at least 100M + +
+ Edit the php.ini file +
+
sudo nano 
+
+
+ + +
+
+ +
+
+ +
+

+
+
+ +
+
+ + getLanguage(), 'inputLanguage'); ?> +
+
+
+ +
+ +
+
+ + " class="form-control" type="email" value="getContactEmail(); ?>" > +
+ +
+
+ +
+ +
+
+ + +
+
+
+ +
+ +
+
+ + +
+
+
+ +
+ +
+
+ + + +
+
+
+ +
+ +
+
+ getAutoplay())) { + echo "checked"; + } ?> > + +
+
+
+ +
+
+ +
+
+
+

+
+ +
+ +
+
+ + " class="form-control" type="text" value="getWebSiteTitle(); ?>" > +
+
+
+
+ +
+ + +
+ +
+
+ +
+
+ +
+ +
+ +
+
+
+
+
+
+ +
+
+
+

+
+ +
+
+ + +
+
+
+ +
+ + +
+ : https://encoder1.avideo.com/ or + +
+
+
+ +
+ +
+ +
+
+ + +
+ +
+
+ getDisable_analytics())) { + echo "checked"; + } ?> aria-describedby="disable_analyticsHelp"> + +
+ +
+
+ +
+ +
+ +
+ getDisable_youtubeupload())) { + echo "checked"; + } ?> > + +
+
+
+ +
+ +
+
+ getAllow_download())) { + echo "checked"; + } ?> aria-describedby="allow_downloadHelp"> + +
+ +
+
+
+
+ +
+
+ +
+

Email Configuration

+
+ +
+

+ + , + +

+
+ + +
+ +
+
+ getSmtp())) { + echo "checked"; + } ?> > + +
+
+
+
+ +
+
+ getSmtpAuth())) { + echo "checked"; + } ?> > + +
+
+
+ +
+ +
+ + +
+
+ +
+ +
+ + +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ getSmtpPassword() . '"', __("SMTP Password")); ?> +
+
+
+ +
+ +
+
+ +
+
+
+
+ + + +

+ +
+
+
+ +
+ + + + + + + + + : https://analytics.google.com
+ +
+
+
+ +
+ + +
+
+
+
+ +
+ +
+ +
+ + + diff --git a/view/configurations_head.php b/view/configurations_head.php index a989eaa3e4..9f7f191728 100644 --- a/view/configurations_head.php +++ b/view/configurations_head.php @@ -1,8 +1,8 @@ - - - \ No newline at end of file diff --git a/view/contact.php b/view/contact.php index 5856ffca60..ed57b54d51 100644 --- a/view/contact.php +++ b/view/contact.php @@ -1,163 +1,163 @@ - - - - - <?php echo __("Contact") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - -
-
-
- -
- -
- - - - - - -
- -
-
- - " class="form-control" value="" type="text" required="true"> -
-
-
- - - -
- -
-
- - " class="form-control" value="" type="email" required="true"> -
-
-
- - - -
"> - -
-
- - " class="form-control" type="text"> -
-
-
- - -
- -
-
- - -
-
-
- - -
- -
-
- - - " class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText"> -
-
-
- -
- -
- -
-
- -
-
-
-
-
- - - - - - - - + + + + + <?php echo __("Contact") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + +
+
+
+ +
+ +
+ + + + + + +
+ +
+
+ + " class="form-control" value="" type="text" required="true"> +
+
+
+ + + +
+ +
+
+ + " class="form-control" value="" type="email" required="true"> +
+
+
+ + + +
"> + +
+
+ + " class="form-control" type="text"> +
+
+
+ + +
+ +
+
+ + +
+
+
+ + +
+ +
+
+ + + " class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText"> +
+
+
+ +
+ +
+ +
+
+ +
+
+
+
+
+ + + + + + + + diff --git a/view/css/custom/index.php b/view/css/custom/index.php index c6bd3fe438..f8809e3c68 100644 --- a/view/css/custom/index.php +++ b/view/css/custom/index.php @@ -1,31 +1,31 @@ - + <?php echo __("About") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - + - +
- +
@@ -35,15 +35,15 @@ $metaDescription = "Themes Page";
- +
- + diff --git a/view/css/custom/theme.php b/view/css/custom/theme.php index e007cc6e60..2db1f48ceb 100644 --- a/view/css/custom/theme.php +++ b/view/css/custom/theme.php @@ -1,9 +1,9 @@ - + @@ -98,7 +98,7 @@ if(!empty($_REQUEST['theme'])){
- +
diff --git a/view/downloadChecker.php b/view/downloadChecker.php index 709bd3ece1..6113e24529 100644 --- a/view/downloadChecker.php +++ b/view/downloadChecker.php @@ -1,145 +1,143 @@ -'; - foreach ($help as $value) { - $helpTXT .= '
  • ' . $value . '
  • '; - } - $helpTXT .= ''; - } - if ($isChecked) { - return '
  • ' . $text . $helpTXT . '
  • '; - } else { - return '
  • ' . $text . $helpTXT . '
  • '; - } -} -?> -
    -
    - Site Download Configuration -
    -
    -
      - getAllow_download())) { - echo getChecked(__("Your Site Configurations is set to NOT Allow Download"), false, $help); - } else { - echo getChecked(__("Your Site Configurations is set to Allow Download"), true, $help); - } - if (User::isAdmin()) { - $help = array(); - $help[] = "Plugins menu / CustomizeUser / nonAdminCannotDownload"; - } - if ($obj->nonAdminCannotDownload) { - echo getChecked(__("Non admin users can download videos"), true, $help); - } else { - echo getChecked(__("Non admin users can NOT download videos"), false, $help); - } - }else{ - echo getChecked(__("This site configuration allow download"), true, $help); - - if ($obj->nonAdminCannotDownload) { - $help[] = "Plugins menu / CustomizeUser / nonAdminCannotDownload"; - echo getChecked(__("But only admin can download"), true, $help); - } - } - ?> -
    -
    -
    -getUsers_id(); - $user = new User($users_id); - ?> -
    -
    - User Download Configuration () -
    -
    -
      - getType(); - if(!in_array($type, $canDownload)){ - echo getChecked(__("You cannot download video type")." {$type}", false, $help); - } - if (User::isAdmin()) { - $help = array(); - $help[] = "Plugins menu / CustomizeUser / userCanAllowFilesDownload"; - }else{ - $help = array(); - } - if (!empty($obj->userCanAllowFilesDownload)) { - $help[] = "My Videos menu / Allow Download My Videos"; - if (!empty($user->getExternalOption('userCanAllowFilesDownload'))) { - if (!empty($obj->userCanAllowFilesDownloadSelectPerVideo)) { - echo getChecked(__("This user do allow download selected videos"), true, $help); - } else { - echo getChecked(__("This user do allow download all his files"), true, $help); - } - } else { - echo getChecked(__("This user do NOT allow download his files"), false, $help); - } - } else { - echo getChecked(__("The download is controlled by the system, there is nothing to check on the user"), true, $help); - } - ?> -
    -
    -
    - -
    -
    - Video Download Configuration (getTitle(); ?>) -
    -
    -
      - getId()); - if ($canDownloadVideoFromVideo) { - echo getChecked(__("This video can be downloaded"), true); - } else { - $category = new Category($video->getCategories_id()); - $help = array(); - $help[] = "Categories menu / Edit a category / Meta Data / Allow Download"; - if (is_object($category) && !$category->getAllow_download()) { - echo getChecked(__("This category do not allow download"), false, $help); - } else { - echo getChecked(__("This category allow download"), true, $help); - } - if (!empty($obj->userCanAllowFilesDownloadSelectPerVideo)) { - $help = array(); - $help[] = "My Videos menu / Edit a video / Allow Download This media"; - if (empty($video->getCan_download())) { - echo getChecked(__("User must allow each video individually, but this video is not marked for download"), false, $help); - } else { - echo getChecked(__("This video checked for download"), true, $help); - } - } else { - echo getChecked(__("The download permission is site wide, so there is nothing to check on the video"), true); - } - } - ?> -
    -
    -
    - - '; + foreach ($help as $value) { + $helpTXT .= '
  • ' . $value . '
  • '; + } + $helpTXT .= ''; + } + if ($isChecked) { + return '
  • ' . $text . $helpTXT . '
  • '; + } else { + return '
  • ' . $text . $helpTXT . '
  • '; + } +} +?> +
    +
    + Site Download Configuration +
    +
    +
      + getAllow_download())) { + echo getChecked(__("Your Site Configurations is set to NOT Allow Download"), false, $help); + } else { + echo getChecked(__("Your Site Configurations is set to Allow Download"), true, $help); + } + if (User::isAdmin()) { + $help = []; + $help[] = "Plugins menu / CustomizeUser / nonAdminCannotDownload"; + } + if ($obj->nonAdminCannotDownload) { + echo getChecked(__("Non admin users can download videos"), true, $help); + } else { + echo getChecked(__("Non admin users can NOT download videos"), false, $help); + } + } else { + echo getChecked(__("This site configuration allow download"), true, $help); + + if ($obj->nonAdminCannotDownload) { + $help[] = "Plugins menu / CustomizeUser / nonAdminCannotDownload"; + echo getChecked(__("But only admin can download"), true, $help); + } + } + ?> +
    +
    +
    +getUsers_id(); + $user = new User($users_id); ?> +
    +
    + User Download Configuration () +
    +
    +
      + getType(); + if (!in_array($type, $canDownload)) { + echo getChecked(__("You cannot download video type")." {$type}", false, $help); + } + if (User::isAdmin()) { + $help = []; + $help[] = "Plugins menu / CustomizeUser / userCanAllowFilesDownload"; + } else { + $help = []; + } + if (!empty($obj->userCanAllowFilesDownload)) { + $help[] = "My Videos menu / Allow Download My Videos"; + if (!empty($user->getExternalOption('userCanAllowFilesDownload'))) { + if (!empty($obj->userCanAllowFilesDownloadSelectPerVideo)) { + echo getChecked(__("This user do allow download selected videos"), true, $help); + } else { + echo getChecked(__("This user do allow download all his files"), true, $help); + } + } else { + echo getChecked(__("This user do NOT allow download his files"), false, $help); + } + } else { + echo getChecked(__("The download is controlled by the system, there is nothing to check on the user"), true, $help); + } ?> +
    +
    +
    + +
    +
    + Video Download Configuration (getTitle(); ?>) +
    +
    +
      + getId()); + if ($canDownloadVideoFromVideo) { + echo getChecked(__("This video can be downloaded"), true); + } else { + $category = new Category($video->getCategories_id()); + $help = []; + $help[] = "Categories menu / Edit a category / Meta Data / Allow Download"; + if (is_object($category) && !$category->getAllow_download()) { + echo getChecked(__("This category do not allow download"), false, $help); + } else { + echo getChecked(__("This category allow download"), true, $help); + } + if (!empty($obj->userCanAllowFilesDownloadSelectPerVideo)) { + $help = []; + $help[] = "My Videos menu / Edit a video / Allow Download This media"; + if (empty($video->getCan_download())) { + echo getChecked(__("User must allow each video individually, but this video is not marked for download"), false, $help); + } else { + echo getChecked(__("This video checked for download"), true, $help); + } + } else { + echo getChecked(__("The download permission is site wide, so there is nothing to check on the video"), true); + } + } ?> +
    +
    +
    + + \ No newline at end of file diff --git a/view/downloadExternalVideo.php b/view/downloadExternalVideo.php index 421b043c2b..51c196d4c3 100644 --- a/view/downloadExternalVideo.php +++ b/view/downloadExternalVideo.php @@ -1,197 +1,198 @@ - - - - - <?php echo __("User") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - -
    - -
    -

    -

    youtube-dl

    -
    - Youtube-dl

    - -
    sudo apt-get install python
    -
    - -
    sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl && sudo chmod a+rx /usr/local/bin/youtube-dl
    -
    - -
    sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl && sudo chmod a+rx /usr/local/bin/youtube-dl
    -
    - -
    -
    -
    -
    -
    - - -
    - -
    -
    - - " class="form-control" type="text" value="" required > -
    -
    -
    - - - - -
    - -
    - -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - -
    - -
    -
    - - -
    - - - - - + + + + + <?php echo __("User") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + +
    + +
    +

    +

    youtube-dl

    +
    + Youtube-dl

    + +
    sudo apt-get install python
    +
    + +
    sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl && sudo chmod a+rx /usr/local/bin/youtube-dl
    +
    + +
    sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl && sudo chmod a+rx /usr/local/bin/youtube-dl
    +
    + +
    +
    +
    +
    +
    + + +
    + +
    +
    + + " class="form-control" type="text" value="" required > +
    +
    +
    + + + + +
    + +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    + +
    + +
    +
    + + +
    + + + + + diff --git a/view/error.php b/view/error.php index 1a93db70ee..17dd4248ba 100644 --- a/view/error.php +++ b/view/error.php @@ -1,521 +1,521 @@ - - - - - - - - - - -
    -
    -
      -
    • k
    • - -
    • v
    • - -
    • n
    • - -
    • z
    • - -
    • i
    • - -
    • x
    • - -
    • m
    • - -
    • e
    • - -
    • t
    • - -
    • a
    • - -
    • x
    • - -
    • l
    • - -
    • 4
    • - -
    • 0
    • - -
    • 4
    • - -
    • y
    • - -
    • y
    • - -
    • w
    • - -
    • v
    • - -
    • b
    • - -
    • o
    • - -
    • q
    • - -
    • d
    • - -
    • y
    • - -
    • p
    • - -
    • a
    • - -
    • p
    • - -
    • a
    • - -
    • g
    • - -
    • e
    • - -
    • v
    • - -
    • j
    • - -
    • a
    • - -
    • n
    • - -
    • o
    • - -
    • t
    • - -
    • s
    • - -
    • c
    • - -
    • e
    • - -
    • w
    • - -
    • v
    • - -
    • x
    • - -
    • e
    • - -
    • p
    • - -
    • c
    • - -
    • f
    • - -
    • h
    • - -
    • q
    • - -
    • e
    • - -
    • f
    • - -
    • o
    • - -
    • u
    • - -
    • n
    • - -
    • d
    • - -
    • s
    • - -
    • w
    • - -
    • q
    • - -
    • v
    • - -
    • o
    • - -
    • s
    • - -
    • m
    • - -
    • v
    • - -
    • f
    • - -
    • u
    • -
    -
    - -
    -
    -

    - -

    - -

    - - - - -
    -
    - - + + + + + + + + + + +
    +
    +
      +
    • k
    • + +
    • v
    • + +
    • n
    • + +
    • z
    • + +
    • i
    • + +
    • x
    • + +
    • m
    • + +
    • e
    • + +
    • t
    • + +
    • a
    • + +
    • x
    • + +
    • l
    • + +
    • 4
    • + +
    • 0
    • + +
    • 4
    • + +
    • y
    • + +
    • y
    • + +
    • w
    • + +
    • v
    • + +
    • b
    • + +
    • o
    • + +
    • q
    • + +
    • d
    • + +
    • y
    • + +
    • p
    • + +
    • a
    • + +
    • p
    • + +
    • a
    • + +
    • g
    • + +
    • e
    • + +
    • v
    • + +
    • j
    • + +
    • a
    • + +
    • n
    • + +
    • o
    • + +
    • t
    • + +
    • s
    • + +
    • c
    • + +
    • e
    • + +
    • w
    • + +
    • v
    • + +
    • x
    • + +
    • e
    • + +
    • p
    • + +
    • c
    • + +
    • f
    • + +
    • h
    • + +
    • q
    • + +
    • e
    • + +
    • f
    • + +
    • o
    • + +
    • u
    • + +
    • n
    • + +
    • d
    • + +
    • s
    • + +
    • w
    • + +
    • q
    • + +
    • v
    • + +
    • o
    • + +
    • s
    • + +
    • m
    • + +
    • v
    • + +
    • f
    • + +
    • u
    • +
    +
    + +
    +
    +

    + +

    + +

    + + + + +
    +
    + + diff --git a/view/forbiddenPage.php b/view/forbiddenPage.php index 9eabca8fb1..a4327aabba 100644 --- a/view/forbiddenPage.php +++ b/view/forbiddenPage.php @@ -1,63 +1,60 @@ - - - - - <?php echo __("Forbidden") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - -
    - -
    -
    -
    - -
    -
    - -
    -
    - -
    - -
    - -
    -
    -
    - -
    - - - + + + + + <?php echo __("Forbidden") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    + +
    + +
    +
    +
    + +
    + + + diff --git a/view/googleAdView.php b/view/googleAdView.php index 5c1f999bec..780704e9cd 100644 --- a/view/googleAdView.php +++ b/view/googleAdView.php @@ -1,20 +1,20 @@ - - - - - - getAdsense(); - ?> - - + + + + + + getAdsense(); + ?> + + diff --git a/view/help.php b/view/help.php index 179a8a1e15..f3489a5864 100644 --- a/view/help.php +++ b/view/help.php @@ -1,114 +1,114 @@ - - - - - <?php echo __("Help") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - -
    -
    -
    -

    getWebSiteTitle(); ?>

    -

    -

      -
    • -
    -

    -

    - -

    -

    -

    -

    siteConfigurations'>, plugins'> "CustomiseAdvanced".

    -

    "". .

    -

    -
    -

    -

    -

    : cd ; git pull .

    -

    "update'>".

    -

    !

    -
    -

    -

    : github.com/DanielnetoDotCom/AVideo/archive/master.zip ().

    -

    -

    "update'>".

    -

    !

    -
    -

    -

    -

    :

    -

    -
    - -

    -

    -

    -

    :

    - - - - - - - - - -
    Embed a video link->Embedded'); ?>
    Embed a video link->Choose Direct audio-link (mp3 or ogg)'); ?>
    Embed a video->Choose Direct video-link (mp4)'); ?>
    -
    -

    -

    -

    , .

    -

    -
      -
    • -
    • -
    • -
    • -
    -

    -
    -

    -

    -> .

    -

    -

    .

    - - - - - -
    -
    -
    - - - - - + + + + + <?php echo __("Help") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + +
    +
    +
    +

    getWebSiteTitle(); ?>

    +

    +

      +
    • +
    +

    +

    + +

    +

    +

    +

    siteConfigurations'>, plugins'> "CustomiseAdvanced".

    +

    "". .

    +

    +
    +

    +

    +

    : cd ; git pull .

    +

    "update'>".

    +

    !

    +
    +

    +

    : github.com/DanielnetoDotCom/AVideo/archive/master.zip ().

    +

    +

    "update'>".

    +

    !

    +
    +

    +

    +

    :

    +

    +
    + +

    +

    +

    +

    :

    + + + + + + + + + +
    Embed a video link->Embedded'); ?>
    Embed a video link->Choose Direct audio-link (mp3 or ogg)'); ?>
    Embed a video->Choose Direct video-link (mp4)'); ?>
    +
    +

    +

    +

    , .

    +

    +
      +
    • +
    • +
    • +
    • +
    +

    +
    +

    +

    -> .

    +

    +

    .

    + + + + + +
    +
    +
    + + + + + diff --git a/view/hls.php b/view/hls.php index e9aff91246..4fcbfa6cc5 100644 --- a/view/hls.php +++ b/view/hls.php @@ -1,103 +1,100 @@ -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']) || User::canWatchVideoWithAds($video['id']) || isCDN()) { - - if (!empty($_GET['download'])) { - downloadHLS($_GET['file']); - } else if (!empty($_GET['playHLSasMP4'])) { - playHLSasMP4($_GET['file']); - } else { - if(@filesize($_GET['file'])>20){ - $filename = $_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; +isTokenValid($_GET['token'], $fname, $_GET['videoDirectory']); + } +} elseif (!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']) || User::canWatchVideoWithAds($video['id']) || isCDN()) { + if (!empty($_GET['download'])) { + downloadHLS($_GET['file']); + } elseif (!empty($_GET['playHLSasMP4'])) { + playHLSasMP4($_GET['file']); + } else { + if (@filesize($_GET['file'])>20) { + $filename = $_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); + } elseif (!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/iframe.php b/view/iframe.php index 9a58582656..f98cd2d42c 100644 --- a/view/iframe.php +++ b/view/iframe.php @@ -1,84 +1,83 @@ -onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && User::isVerified()) || (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && !$advancedCustomUser->onlyVerifiedEmailCanUpload) || !isset($advancedCustomUser->onlyVerifiedEmailCanUpload)) { - if (!empty($config->getEncoderURL())) { - $iframeURL = $config->getEncoderURL()."?noNavbar=1&".getCredentialsURL(); - }else{ - if(empty($iframeURL)){ - forbiddenPage("Your encoder is empty"); - } - } - }else{ - if(empty($iframeURL)){ - forbiddenPage("You cannot upload 1"); - } - } - break; - case "network": - $titleTag = __("Network"); - if ((isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && User::isVerified()) || (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && !$advancedCustomUser->onlyVerifiedEmailCanUpload) || !isset($advancedCustomUser->onlyVerifiedEmailCanUpload)) { - if (!empty($advancedCustom->encoderNetwork) && empty($advancedCustom->doNotShowEncoderNetwork)) { - $iframeURL = $advancedCustom->encoderNetwork."?".getCredentialsURL(); - }else{ - if(empty($iframeURL)){ - forbiddenPage("Network is disabled"); - } - } - }else{ - if(empty($iframeURL)){ - forbiddenPage("You cannot upload 1"); - } - } - break; - case "log": - $titleTag = __("Log"); - $iframeURL = $global['webSiteRootURL']."view/logs.php"; - break; - -} -if(empty($iframeURL)){ - forbiddenPage("Invalid Type {$_GET['type']}"); -} - - -?> - - - - <?php echo $titleTag . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - - - +onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && User::isVerified()) || (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && !$advancedCustomUser->onlyVerifiedEmailCanUpload) || !isset($advancedCustomUser->onlyVerifiedEmailCanUpload)) { + if (!empty($config->getEncoderURL())) { + $iframeURL = $config->getEncoderURL()."?noNavbar=1&".getCredentialsURL(); + } else { + if (empty($iframeURL)) { + forbiddenPage("Your encoder is empty"); + } + } + } else { + if (empty($iframeURL)) { + forbiddenPage("You cannot upload 1"); + } + } + break; + case "network": + $titleTag = __("Network"); + if ((isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && User::isVerified()) || (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && !$advancedCustomUser->onlyVerifiedEmailCanUpload) || !isset($advancedCustomUser->onlyVerifiedEmailCanUpload)) { + if (!empty($advancedCustom->encoderNetwork) && empty($advancedCustom->doNotShowEncoderNetwork)) { + $iframeURL = $advancedCustom->encoderNetwork."?".getCredentialsURL(); + } else { + if (empty($iframeURL)) { + forbiddenPage("Network is disabled"); + } + } + } else { + if (empty($iframeURL)) { + forbiddenPage("You cannot upload 1"); + } + } + break; + case "log": + $titleTag = __("Log"); + $iframeURL = $global['webSiteRootURL']."view/logs.php"; + break; + +} +if (empty($iframeURL)) { + forbiddenPage("Invalid Type {$_GET['type']}"); +} + + +?> + + + + <?php echo $titleTag . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + + + diff --git a/view/img/image404.php b/view/img/image404.php index cd7f11f3c7..03ca91f28e 100644 --- a/view/img/image404.php +++ b/view/img/image404.php @@ -1,47 +1,48 @@ -doNotShowImportMP4Button)) { - return false; -} -?> - - - - <?php echo __("Import") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - -
    - -
    -
    Import Local Videos
    -
    -
    - - Here you can direct import multiple videos stored on your hard drive.
    - If there is a file (html or htm or txt) we will import it's content as a description, and the first - characteres will be the file title. (choose 0 to use the file name as the title) -
    -
    -
    - -
    -
    -
    -
    - - - - - - - - - - -
    -
    - -
    - -
    -
      -
    - - - -
    -
    - -
    - - - - - +doNotShowImportMP4Button)) { + return false; +} +?> + + + + <?php echo __("Import") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + +
    + +
    +
    Import Local Videos
    +
    +
    + + Here you can direct import multiple videos stored on your hard drive.
    + If there is a file (html or htm or txt) we will import it's content as a description, and the first + characteres will be the file title. (choose 0 to use the file name as the title) +
    +
    +
    + +
    +
    +
    +
    + + + + + + + + + + +
    +
    + +
    + +
    +
      +
    + + + +
    +
    + +
    + + + + + diff --git a/view/include/article.php b/view/include/article.php index ee43da9ede..0604a7195d 100644 --- a/view/include/article.php +++ b/view/include/article.php @@ -1,7 +1,7 @@ - +
    @@ -18,12 +18,12 @@ $sources = getVideosURLPDF($video['filename']);

    - +

    -
    - +
    - + \ No newline at end of file diff --git a/view/include/categoryTop.php b/view/include/categoryTop.php index 5d1b9cc8ac..06ed618dfd 100644 --- a/view/include/categoryTop.php +++ b/view/include/categoryTop.php @@ -1,20 +1,20 @@ -showCategoryTopImages)){ - return false; -} -if (!empty($_GET['catName'])) { - $currentCat = Category::getCategoryByName($_GET['catName']); - $categories_id = $currentCat['id']; - if(!Category::isAssetsValids($categories_id)){ - return false; - } -}else{ - return false; -} - -$photo = Category::getCategoryPhotoPath($categories_id); -$background = Category::getCategoryBackgroundPath($categories_id); -?> +showCategoryTopImages)) { + return false; +} +if (!empty($_GET['catName'])) { + $currentCat = Category::getCategoryByName($_GET['catName']); + $categories_id = $currentCat['id']; + if (!Category::isAssetsValids($categories_id)) { + return false; + } +} else { + return false; +} + +$photo = Category::getCategoryPhotoPath($categories_id); +$background = Category::getCategoryBackgroundPath($categories_id); +?>
    diff --git a/view/include/embed.php b/view/include/embed.php index f504b3c9ca..9f9b3473f8 100644 --- a/view/include/embed.php +++ b/view/include/embed.php @@ -1,12 +1,12 @@ - + - + - + diff --git a/view/include/footer.php b/view/include/footer.php index afab3041f5..71c370207d 100644 --- a/view/include/footer.php +++ b/view/include/footer.php @@ -1,48 +1,48 @@ -" . __('You have a new version to install') . "', showHideTransition: 'plain', icon: 'error', hideAfter: 20000 -});"; - //$footerjs .= 'var filesToUpdate='.json_encode($fileUpdates).';'; -} -if (empty($advancedCustom)) { - $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); -} -?> +});"; + //$footerjs .= 'var filesToUpdate='.json_encode($fileUpdates).';'; +} +if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); +} +?>
    - getFooter(); - } - if (empty($custom)) { - ?> + getFooter(); + } + if (empty($custom)) { + ?>
    • - Powered by AVideo ® Platform vgetVersion(); ?> + Powered by AVideo ® Platform vgetVersion(); ?>
    - +
    @@ -55,50 +55,50 @@ showAlertMessage(); new WOW().init(); --> - - + +
    - +
    -"; -} -if (!empty($advancedCustom->footerHTMLCode->value)) { - echo $advancedCustom->footerHTMLCode->value; -} - -if (isFirstPage()) { - echo ''; -} -?> +"; + } +if (!empty($advancedCustom->footerHTMLCode->value)) { + echo $advancedCustom->footerHTMLCode->value; +} + +if (isFirstPage()) { + echo ''; +} +?> \ No newline at end of file diff --git a/view/include/head.php b/view/include/head.php index 45be255749..cf4523ca25 100644 --- a/view/include/head.php +++ b/view/include/head.php @@ -1,60 +1,60 @@ -getId()); -} -$custom = array(); - -$customizePluginDescription = ''; -if (file_exists($extraPluginFile) && AVideoPlugin::isEnabledByName("Customize")) { - require_once $extraPluginFile; - $ec = new ExtraConfig(); - $customizePluginDescription = $ec->getDescription(); - $custom[] = $customizePluginDescription; -} - -if (!empty($poster)) { - $subTitle = str_replace(array('"', "\n", "\r"), array("", "", ""), strip_tags($video['description'])); - $custom = array(); - $custom[] = $subTitle; - if (!empty($video["category"])) { - $custom[] = $video["category"]; - } -} - -if (!empty($_GET['catName'])) { - $category = Category::getCategoryByName($_GET['catName']); - $description = str_replace(array('"', "\n", "\r"), array("", "", ""), strip_tags($category['description'])); - $custom = array(); - $custom[] = $description; - $custom[] = $category['name']; -} - -foreach ($custom as $key => $value) { - if (empty($value)) { - unset($custom[$key]); - } -} - -if (!empty($metaDescription)) { - $metaDescription = implode(" - ", $custom) . " - {$metaDescription}"; -} else { - $metaDescription = implode(" - ", $custom); -} -// for SEO to not rise an error of duplicated title or description of same pages with and without last slash -$metaDescription .= getSEOComplement(array("addAutoPrefix" => false)); -$theme = getCurrentTheme(); - -if (empty($config)) { - $config = new Configuration(); -} -?> +getId()); +} +$custom = []; + +$customizePluginDescription = ''; +if (file_exists($extraPluginFile) && AVideoPlugin::isEnabledByName("Customize")) { + require_once $extraPluginFile; + $ec = new ExtraConfig(); + $customizePluginDescription = $ec->getDescription(); + $custom[] = $customizePluginDescription; +} + +if (!empty($poster)) { + $subTitle = str_replace(['"', "\n", "\r"], ["", "", ""], strip_tags($video['description'])); + $custom = []; + $custom[] = $subTitle; + if (!empty($video["category"])) { + $custom[] = $video["category"]; + } +} + +if (!empty($_GET['catName'])) { + $category = Category::getCategoryByName($_GET['catName']); + $description = str_replace(['"', "\n", "\r"], ["", "", ""], strip_tags($category['description'])); + $custom = []; + $custom[] = $description; + $custom[] = $category['name']; +} + +foreach ($custom as $key => $value) { + if (empty($value)) { + unset($custom[$key]); + } +} + +if (!empty($metaDescription)) { + $metaDescription = implode(" - ", $custom) . " - {$metaDescription}"; +} else { + $metaDescription = implode(" - ", $custom); +} +// for SEO to not rise an error of duplicated title or description of same pages with and without last slash +$metaDescription .= getSEOComplement(["addAutoPrefix" => false]); +$theme = getCurrentTheme(); + +if (empty($config)) { + $config = new Configuration(); +} +?> @@ -70,64 +70,64 @@ if (empty($config)) { "> "> "> -"> --> -disableAnimations)){ -?> +disableAnimations)) { + ?> - + - + -showCustomCSS) && file_exists($filename)) { - echo ''; -} else { - if ($theme !== "default") { - echo ""; - } - if (empty($customizePlugin->showCustomCSS)) { - echo ""; - } - if (!file_exists($filename)) { - echo ""; - } - if (!empty($global['userBootstrapLatest'])) { - echo ""; - } - echo ''; -} -$cssFiles = array(); -$cssFiles[] = "view/css/main.css"; -$cssFiles = array_merge($cssFiles, AVideoPlugin::getCSSFiles()); -echo combineFilesHTML($cssFiles, "css"); -if (isRTL()) { - ?> +showCustomCSS) && file_exists($filename)) { + echo ''; +} else { + if ($theme !== "default") { + echo ""; + } + if (empty($customizePlugin->showCustomCSS)) { + echo ""; + } + if (!file_exists($filename)) { + echo ""; + } + if (!empty($global['userBootstrapLatest'])) { + echo ""; + } + echo ''; +} +$cssFiles = []; +$cssFiles[] = "view/css/main.css"; +$cssFiles = array_merge($cssFiles, AVideoPlugin::getCSSFiles()); +echo combineFilesHTML($cssFiles, "css"); +if (isRTL()) { + ?> - + -getDisable_analytics()) { - ?> +getDisable_analytics()) { + ?> - getHead(); -echo $head; -if (!empty($video)) { - if (!empty($video['users_id'])) { - $userAnalytics = new User($video['users_id']); - echo $userAnalytics->getAnalytics(); - unset($userAnalytics); - } -} -ogSite(); + getHead(); +echo $head; +if (!empty($video)) { + if (!empty($video['users_id'])) { + $userAnalytics = new User($video['users_id']); + echo $userAnalytics->getAnalytics(); + unset($userAnalytics); + } +} +ogSite(); ?> \ No newline at end of file diff --git a/view/include/image.php b/view/include/image.php index ea3f78f1e6..61256164c2 100644 --- a/view/include/image.php +++ b/view/include/image.php @@ -1,6 +1,6 @@ -
    @@ -16,8 +16,8 @@ $sources = getVideosURLIMAGE($video['filename']);
    - " class="img img-responsive" style="max-height: 600px;" >
    - signInOnRight)) { - if (User::isLogged()) { - if (!$advancedCustomUser->disableSignOutButton) { - ?> + signInOnRight)) { + if (User::isLogged()) { + if (!$advancedCustomUser->disableSignOutButton) { + ?>
  • - + - + - +
  • - +
  • - +
  • - + @@ -615,21 +598,20 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • @@ -798,29 +774,29 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • -
  • @@ -1108,10 +1079,10 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • + '; + } + if (Permissions::canAdminUserGroups()) { + $menus[] = '?>
  • @@ -1119,10 +1090,10 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • + '; + } + if (Permissions::canClearCache()) { + $menus[] = '?>
  • @@ -1134,78 +1105,74 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • + '; + } + if (Permissions::canSeeLogs()) { + $menus[] = ' ?>
  • + '; + } + if (Permissions::canGenerateSiteMap()) { + $menus[] = '?>
  • + '; + } + if (count($menus)) { + ?>

    - + - + - doNotShowLeftMenuAudioAndVideoButtons)) { - ?> + doNotShowLeftMenuAudioAndVideoButtons)) { + ?>

  • - + - removeBrowserChannelLinkFromMenu)) { - ?> + removeBrowserChannelLinkFromMenu)) { + ?>

  • @@ -1216,13 +1183,12 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • - +
  • - +

  • @@ -1230,145 +1196,142 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp
  • - CategoryLabel); ?> + CategoryLabel); ?>

  • - "; - foreach ($subcats as $subcat) { - if ($subcat['parentId'] != $catId) { - continue; - } - if (empty($subcat['total'])) { - continue; - } - if (is_array($parsed_cats) && in_array($subcat['id'], $parsed_cats)) { - continue; - } - //$parsed_cats[] = $subcat['id']; - echo ''; - } - echo ""; - } - } - - } - if (empty($advancedCustom->doNotDisplayCategoryLeftMenu)) { - $post = $_POST; - $get = $_GET; - unset($_GET); - unset($_POST); - $_GET['current'] = $_POST['current'] = 1; - $_GET['parentsOnly'] = 1; - $categories = Category::getAllCategories(); - foreach ($categories as $value) { - if ($value['parentId']) { - continue; - } - if ($advancedCustom->ShowAllVideosOnCategory) { - $total = $value['fullTotal']; - } else { - $total = $value['total']; - } - if (empty($total)) { - continue; - } - if (in_array($value['id'], $parsed_cats)) { - continue; - } - //$parsed_cats[] = $value['id']; - echo ''; - } - $_POST = $post; - $_GET = $get; - } - - $_REQUEST['rowCount'] = $_rowCount; - ?> + "; + foreach ($subcats as $subcat) { + if ($subcat['parentId'] != $catId) { + continue; + } + if (empty($subcat['total'])) { + continue; + } + if (is_array($parsed_cats) && in_array($subcat['id'], $parsed_cats)) { + continue; + } + //$parsed_cats[] = $subcat['id']; + echo ''; + } + echo ""; + } + } + } + if (empty($advancedCustom->doNotDisplayCategoryLeftMenu)) { + $post = $_POST; + $get = $_GET; + unset($_GET); + unset($_POST); + $_GET['current'] = $_POST['current'] = 1; + $_GET['parentsOnly'] = 1; + $categories = Category::getAllCategories(); + foreach ($categories as $value) { + if ($value['parentId']) { + continue; + } + if ($advancedCustom->ShowAllVideosOnCategory) { + $total = $value['fullTotal']; + } else { + $total = $value['total']; + } + if (empty($total)) { + continue; + } + if (in_array($value['id'], $parsed_cats)) { + continue; + } + //$parsed_cats[] = $value['id']; + echo ''; + } + $_POST = $post; + $_GET = $get; + } + + $_REQUEST['rowCount'] = $_rowCount; ?>

  • - disableInstallPWAButton)) { - ?> + disableInstallPWAButton)) { + ?> - disablePlayLink)) { - ?> + disablePlayLink)) { + ?> - disableHelpLeftMenu)) { - ?> + disableHelpLeftMenu)) { + ?>
  • - +
  • - disableAboutLeftMenu)) { - ?> + disableAboutLeftMenu)) { + ?>
  • - +
  • - disableContactLeftMenu)) { - ?> + disableContactLeftMenu)) { + ?>
  • - +
  • - +
    @@ -1463,13 +1426,12 @@ if (!User::isLogged() && !empty($advancedCustomUser->userMustBeLoggedIn) && !emp }); } - underMenuBarHTMLCode->value)) { - echo $advancedCustom->underMenuBarHTMLCode->value; - } -} else if ($thisScriptFile["basename"] !== 'user.php' && empty($advancedCustom->disableNavbar)) { - -} -echo '', AVideoPlugin::navBarAfter(), ''; -unset($_GET['parentsOnly']); -?> + underMenuBarHTMLCode->value)) { + echo $advancedCustom->underMenuBarHTMLCode->value; + } + } elseif ($thisScriptFile["basename"] !== 'user.php' && empty($advancedCustom->disableNavbar)) { + } +echo '', AVideoPlugin::navBarAfter(), ''; +unset($_GET['parentsOnly']); +?> diff --git a/view/include/navbarEncoder.php b/view/include/navbarEncoder.php index c32d983e07..2f5a0bdfc5 100644 --- a/view/include/navbarEncoder.php +++ b/view/include/navbarEncoder.php @@ -1,7 +1,7 @@ -openEncoderInIFrame) || !isSameDomainAsMyAVideo($config->getEncoderURL())) { - if (!empty($advancedCustom->encoderNetwork) && empty($advancedCustom->doNotShowEncoderNetwork)) { - ?> +openEncoderInIFrame) || !isSameDomainAsMyAVideo($config->getEncoderURL())) { + if (!empty($advancedCustom->encoderNetwork) && empty($advancedCustom->doNotShowEncoderNetwork)) { + ?>
  • @@ -10,14 +10,14 @@ if (empty($advancedCustom->openEncoderInIFrame) || !isSameDomainAsMyAVideo($conf
    " data-placement="left" > - encoderNetworkLabel) ? __("Encoder Network") : __($advancedCustom->encoderNetworkLabel); ?> + encoderNetworkLabel) ? __("Encoder Network") : __($advancedCustom->encoderNetworkLabel); ?>
  • - doNotShowEncoderButton)) { - if (!empty($config->getEncoderURL())) { - ?> + doNotShowEncoderButton)) { + if (!empty($config->getEncoderURL())) { + ?>
  • @@ -27,45 +27,44 @@ if (empty($advancedCustom->openEncoderInIFrame) || !isSameDomainAsMyAVideo($conf " data-placement="left" class="faa-parent animated-hover" > - encoderButtonLabel) ? __("Encode video and audio") : __($advancedCustom->encoderButtonLabel); ?> + encoderButtonLabel) ? __("Encode video and audio") : __($advancedCustom->encoderButtonLabel); ?>
  • - +
  • - encoderNetwork) && empty($advancedCustom->doNotShowEncoderNetwork)) { - ?> + encoderNetwork) && empty($advancedCustom->doNotShowEncoderNetwork)) { + ?>
  • " data-placement="left" > - encoderNetworkLabel) ? __("Encoder Network") : __($advancedCustom->encoderNetworkLabel); ?> + encoderNetworkLabel) ? __("Encoder Network") : __($advancedCustom->encoderNetworkLabel); ?>
  • - doNotShowEncoderButton)) { - if (!empty($config->getEncoderURL())) { - ?> + doNotShowEncoderButton)) { + if (!empty($config->getEncoderURL())) { + ?>
  • " data-placement="left" > - encoderButtonLabel) ? __("Encode video and audio") : __($advancedCustom->encoderButtonLabel); ?> + encoderButtonLabel) ? __("Encode video and audio") : __($advancedCustom->encoderButtonLabel); ?>
  • - +
  • - \ No newline at end of file diff --git a/view/include/offlinePage.php b/view/include/offlinePage.php index 293d22b29f..3e359af07d 100644 --- a/view/include/offlinePage.php +++ b/view/include/offlinePage.php @@ -1,12 +1,12 @@ - + -<? echo __("Site Maintenance"); ?> +<?php echo __("Site Maintenance"); ?> - - - -
    - - -
    -
    - 1 {$value['name']}"); - continue; - } - if ($advancedCustom->ShowAllVideosOnCategory) { - $total = $value['fullTotal']; - } else { - $total = $value['total']; - } - if (empty($total)) { - //var_dump("
    2 {$value['name']}"); - continue; - } - - if(!empty($value['fullTotal_videos'])){ - $video = Category::getLatestVideoFromCategory($value['id'], true, true); - $images = Video::getImageFromID($video['id']); - $image = $images->poster; - }else - if(!empty($value['fullTotal_lives'])){ - $live = Category::getLatestLiveFromCategory($value['id'], true, true); - $image = Live::getImage($live['users_id'], $live['live_servers_id']); - }else - if(!empty($value['fullTotal_livelinks'])){ - $liveLinks = Category::getLatestLiveLinksFromCategory($value['id'], true, true); - $image = LiveLinks::getImage($liveLinks['id']); - } - - $totalVideosOnChilds = Category::getTotalFromChildCategory($value['id']); - $childs = Category::getChildCategories($value['id']); - $photo = Category::getCategoryPhotoPath($value['id']); - $photoBg = Category::getCategoryBackgroundPath($value['id']); - $link = $global['webSiteRootURL'] . 'cat/' . $value['clean_name']; - $imageNotFound = preg_match('/notfound/i', $image); - $photoNotFound = empty($photo) || preg_match('/notfound/i', $photo['url']); - $icon = ' ' ; - if (!$imageNotFound) { - ?> - - - - - -
    -
    -
    - -
    - -
    - -
    -
    -
    -
    - -
    -
    - - - - - + + + + + + + + +
    + + +
    +
    + 1 {$value['name']}"); + continue; + } + if ($advancedCustom->ShowAllVideosOnCategory) { + $total = $value['fullTotal']; + } else { + $total = $value['total']; + } + if (empty($total)) { + //var_dump("
    2 {$value['name']}"); + continue; + } + + if (!empty($value['fullTotal_videos'])) { + $video = Category::getLatestVideoFromCategory($value['id'], true, true); + $images = Video::getImageFromID($video['id']); + $image = $images->poster; + } elseif (!empty($value['fullTotal_lives'])) { + $live = Category::getLatestLiveFromCategory($value['id'], true, true); + $image = Live::getImage($live['users_id'], $live['live_servers_id']); + } elseif (!empty($value['fullTotal_livelinks'])) { + $liveLinks = Category::getLatestLiveLinksFromCategory($value['id'], true, true); + $image = LiveLinks::getImage($liveLinks['id']); + } + + $totalVideosOnChilds = Category::getTotalFromChildCategory($value['id']); + $childs = Category::getChildCategories($value['id']); + $photo = Category::getCategoryPhotoPath($value['id']); + $photoBg = Category::getCategoryBackgroundPath($value['id']); + $link = $global['webSiteRootURL'] . 'cat/' . $value['clean_name']; + $imageNotFound = preg_match('/notfound/i', $image); + $photoNotFound = empty($photo) || preg_match('/notfound/i', $photo['url']); + $icon = ' ' ; + if (!$imageNotFound) { + ?> + + + + + +
    +
    +
    + +
    + +
    + +
    +
    +
    +
    + +
    +
    + + + + +error = true; -$obj->msg = ""; -$obj->filename = $global['systemRootPath'].'videos'.DIRECTORY_SEPARATOR.'avideo.log_'.date('Ymd-His').'.zip'; - -if (!Permissions::canSeeLogs()) { - $obj->msg = __("You cannot see the logs"); - die(json_encode($obj)); -} - -if (!empty($global['disableAdvancedConfigurations'])) { - $obj->msg = __("This page is disabled"); - die(json_encode($obj)); -} - -$zip = new ZipArchive; -if ($zip->open($obj->filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) { - $zip->addFile($global['logfile'], 'avideo.log'); - $zip->close(); - file_put_contents($global['logfile'], ''); - $obj->error = false; - die(json_encode($obj)); -} else { - $obj->msg = __("Error on create file"); - die(json_encode($obj)); -} - -?> \ No newline at end of file +error = true; +$obj->msg = ''; +$obj->filename = $global['systemRootPath'].'videos'.DIRECTORY_SEPARATOR.'avideo.log_'.date('Ymd-His').'.zip'; + +if (!Permissions::canSeeLogs()) { + $obj->msg = __("You cannot see the logs"); + die(json_encode($obj)); +} + +if (!empty($global['disableAdvancedConfigurations'])) { + $obj->msg = __("This page is disabled"); + die(json_encode($obj)); +} + +$zip = new ZipArchive(); +if ($zip->open($obj->filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) { + $zip->addFile($global['logfile'], 'avideo.log'); + $zip->close(); + file_put_contents($global['logfile'], ''); + $obj->error = false; + die(json_encode($obj)); +} else { + $obj->msg = __("Error on create file"); + die(json_encode($obj)); +} diff --git a/view/logs.php b/view/logs.php index f65578d430..5b4b51d430 100644 --- a/view/logs.php +++ b/view/logs.php @@ -1,355 +1,350 @@ - - - -
    ...
    -
    "; -$collapsibleClose = "
    "; - -$outputText = ""; -$outputTextErrors = array(); -$outputTextWarnings = array(); -$linesAdded = 0; -$isCollapsed = true; - -function e($text) { - if (empty($text)) { - return false; - } - global $printedarray, $global, $mysqlPass, - $outputText, $outputTextErrors, $outputTextWarnings, - $collapsibleOpen, $collapsibleClose, $linesAdded, $isCollapsed; - - $uniqid = ""; - $class = ""; - $collapsible = true; - $uniqid = uniqid(); - if ( - preg_match("/(AVideoLog::SECURITY)/", $text, $matches) || - preg_match("/(Prepare failed)/i", $text, $matches) || - preg_match("/(AVideoLog::ERROR)/", $text, $matches) || - preg_match("/(fatal)/i", $text, $matches)) { - $outputTextErrors[] = array($uniqid, $text, $matches[1]); - $class = "terminal-alert terminal-alert-error "; - $style = "background-color: #A00; color:#FFF;font-weight: bold;"; - $collapsible = false; - } else - if (preg_match("/(PHP Warning)/i", $text, $matches)) { - $class = "terminal-alert terminal-alert-primary"; - $outputTextWarnings[] = array($uniqid, $text, $matches[1]); - $collapsible = false; - } else if (preg_match("/PHP Notice/", $text)) { - $class = "logNotice"; - } else if (preg_match("/(AVideoLog::WARNING)/", $text, $matches) || preg_match("/AVideoLog::DEBUG/", $text)) { - $class = "logDebug"; - } - - if ($collapsible) { - $log = preg_replace("/^[^\]]+/", "", $text); - if (!empty($log)) { - if (in_array($log, $printedarray)) { - $class = "logIgnore"; - } - $printedarray[] = $log; - } - } - - $removeLinesWithWords = array('password', 'recoverPass', 'pass'); - foreach ($removeLinesWithWords as $value) { - if (preg_match("/{$value}/i", $text)) { - $text = preg_replace("/[^ ]/", "*", $text) . " - {$value}"; - break; - } - } - - $text = preg_replace("/[^ ]+@[^ ]+/i", "myemail@mydomain.com", $text); - - $text = htmlentities($text); - if ($collapsible && !$isCollapsed) { - $outputText .= $collapsibleOpen; - $isCollapsed = true; - } - if (!$collapsible && $isCollapsed) { - if ($linesAdded === 0) { - $outputText = ""; - } else { - $outputText .= $collapsibleClose; - } - $isCollapsed = false; - } - if (!$collapsible && !$isCollapsed) { - - } - $linesAdded++; - $outputText .= "
    " - . "#{$linesAdded} {$text}" - . "
    " . PHP_EOL; - return true; -} - -if (empty($global['logfile'])) { - die("Log variable does not exists"); -} - -if (!file_exists($global['logfile'])) { - die("you may have problems on the write permission for the log file"); -} - -$lines = tail($global['logfile'], 5000, true, true); -$lines = array_reverse($lines); -foreach ($lines as $key => $line) { - if (empty($line[0])) { - unset($line[$key]); - } else { - break; - } -} -$outputText .= $collapsibleOpen; -foreach ($lines as $line) { - e($line[0]); -} -$outputText .= $collapsibleClose; -?> - - - - <?php echo __("Logs") . " " . date("Y-M-d H:i:s") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - -
    -
    - -
    - If you have a problem with your installation, feel free to share this log information on GitHub. - In this log, we hide all the sensitive information from your log, but it still very helpful for finding issues. - -
    -
    -
    - -
    -
    -
    - - #{$count} - {$value[2]}"; ?> - -
    -
    -
    - -
    -
    -
    - - -
    -
    -
    - #{$count} - {$value[2]}"; - } - ?> -
    -
    -
    - -
    -
    - - - -
    -
    -                
    -            
    -
    - - - - + + + +
    ...
    +
    "; +$collapsibleClose = "
    "; + +$outputText = ''; +$outputTextErrors = []; +$outputTextWarnings = []; +$linesAdded = 0; +$isCollapsed = true; + +function e($text) +{ + if (empty($text)) { + return false; + } + global $printedarray, $global, $mysqlPass, + $outputText, $outputTextErrors, $outputTextWarnings, + $collapsibleOpen, $collapsibleClose, $linesAdded, $isCollapsed; + + $uniqid = ''; + $class = ''; + $collapsible = true; + $uniqid = uniqid(); + if ( + preg_match("/(AVideoLog::SECURITY)/", $text, $matches) || + preg_match("/(Prepare failed)/i", $text, $matches) || + preg_match("/(AVideoLog::ERROR)/", $text, $matches) || + preg_match("/(fatal)/i", $text, $matches)) { + $outputTextErrors[] = [$uniqid, $text, $matches[1]]; + $class = "terminal-alert terminal-alert-error "; + $style = "background-color: #A00; color:#FFF;font-weight: bold;"; + $collapsible = false; + } elseif (preg_match("/(PHP Warning)/i", $text, $matches)) { + $class = "terminal-alert terminal-alert-primary"; + $outputTextWarnings[] = [$uniqid, $text, $matches[1]]; + $collapsible = false; + } elseif (preg_match("/PHP Notice/", $text)) { + $class = "logNotice"; + } elseif (preg_match("/(AVideoLog::WARNING)/", $text, $matches) || preg_match("/AVideoLog::DEBUG/", $text)) { + $class = "logDebug"; + } + + if ($collapsible) { + $log = preg_replace("/^[^\]]+/", "", $text); + if (!empty($log)) { + if (in_array($log, $printedarray)) { + $class = "logIgnore"; + } + $printedarray[] = $log; + } + } + + $removeLinesWithWords = ['password', 'recoverPass', 'pass']; + foreach ($removeLinesWithWords as $value) { + if (preg_match("/{$value}/i", $text)) { + $text = preg_replace("/[^ ]/", "*", $text) . " - {$value}"; + break; + } + } + + $text = preg_replace("/[^ ]+@[^ ]+/i", "myemail@mydomain.com", $text); + + $text = htmlentities($text); + if ($collapsible && !$isCollapsed) { + $outputText .= $collapsibleOpen; + $isCollapsed = true; + } + if (!$collapsible && $isCollapsed) { + if ($linesAdded === 0) { + $outputText = ''; + } else { + $outputText .= $collapsibleClose; + } + $isCollapsed = false; + } + if (!$collapsible && !$isCollapsed) { + } + $linesAdded++; + $outputText .= "
    " + . "#{$linesAdded} {$text}" + . "
    " . PHP_EOL; + return true; +} + +if (empty($global['logfile'])) { + die("Log variable does not exists"); +} + +if (!file_exists($global['logfile'])) { + die("you may have problems on the write permission for the log file"); +} + +$lines = tail($global['logfile'], 5000, true, true); +$lines = array_reverse($lines); +foreach ($lines as $key => $line) { + if (empty($line[0])) { + unset($line[$key]); + } else { + break; + } +} +$outputText .= $collapsibleOpen; +foreach ($lines as $line) { + e($line[0]); +} +$outputText .= $collapsibleClose; +?> + + + + <?php echo __("Logs") . " " . date("Y-M-d H:i:s") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + +
    +
    + +
    + If you have a problem with your installation, feel free to share this log information on GitHub. + In this log, we hide all the sensitive information from your log, but it still very helpful for finding issues. + +
    +
    +
    + +
    +
    +
    + + #{$count} - {$value[2]}"; ?> + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    + #{$count} - {$value[2]}"; + } ?> +
    +
    +
    + +
    +
    + + + +
    +
    +                
    +            
    +
    + + + + \ No newline at end of file diff --git a/view/maintanance.html b/view/maintanance.html index 0c6ac119d1..9d7742a92c 100644 --- a/view/maintanance.html +++ b/view/maintanance.html @@ -1,73 +1,73 @@ - - - - Under Maintanance - - - - - -
    - - - - - - - - - - -

    Under Maintanance

    -

    Sorry for the inconvenience.

    -
    - - + + + + Under Maintanance + + + + + +
    + + + + + + + + + + +

    Under Maintanance

    +

    Sorry for the inconvenience.

    +
    + + diff --git a/view/managerCategories.php b/view/managerCategories.php index 8bda675133..66d2486f9d 100644 --- a/view/managerCategories.php +++ b/view/managerCategories.php @@ -1,30 +1,30 @@ - - - - - <?php echo __("Categories") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - + + + + + <?php echo __("Categories") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + diff --git a/view/managerCategories_body.php b/view/managerCategories_body.php index ce901c96af..cc4e97bc24 100644 --- a/view/managerCategories_body.php +++ b/view/managerCategories_body.php @@ -1,414 +1,414 @@ -
    -
    -
    -
    - - -
    -
    - - - - - - - - - - - - - - - - - -
    -
    -
    - -
    - \ No newline at end of file diff --git a/view/managerCategories_head.php b/view/managerCategories_head.php index 507dea0ccd..77417e564b 100644 --- a/view/managerCategories_head.php +++ b/view/managerCategories_head.php @@ -1,3 +1,2 @@ - \ No newline at end of file + - - - - <?php echo __("Comments") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - -
    -
    -
    - -
    -
    -
    - - - + + + + + <?php echo __("Comments") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + +
    +
    +
    + +
    +
    +
    + + + diff --git a/view/managerPlugins.php b/view/managerPlugins.php index 497fab1b36..29f25b6392 100644 --- a/view/managerPlugins.php +++ b/view/managerPlugins.php @@ -1,28 +1,28 @@ - - - - - <?php echo __("Plugins") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - + + + + + <?php echo __("Plugins") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + diff --git a/view/managerPlugins_body.php b/view/managerPlugins_body.php index 746bd0a410..0f5522228f 100644 --- a/view/managerPlugins_body.php +++ b/view/managerPlugins_body.php @@ -1,627 +1,627 @@ - - -
    -
    -
    - -
    -
    -
    - - -
    - -
    -
    -
    - - - - + + +
    +
    +
    + +
    +
    +
    + + +
    + +
    +
    +
    + + + + diff --git a/view/managerPlugins_head.php b/view/managerPlugins_head.php index d5895ca563..dfc643766f 100644 --- a/view/managerPlugins_head.php +++ b/view/managerPlugins_head.php @@ -1,135 +1,135 @@ - - - - - - - + + + + + + + diff --git a/view/managerSubscribes.php b/view/managerSubscribes.php index 2d4cef72e8..62f1d6b6f9 100644 --- a/view/managerSubscribes.php +++ b/view/managerSubscribes.php @@ -1,141 +1,141 @@ - - - - - <?php echo __("Subscribes") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - -
    -
    -
    - -
    -
    - - - -
    - -
    -
    - - - - - - + + + + + <?php echo __("Subscribes") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + +
    +
    +
    + +
    +
    + + + +
    + +
    +
    + + + + + + diff --git a/view/managerUsers.php b/view/managerUsers.php index 3da7c2bde5..d88a41720e 100644 --- a/view/managerUsers.php +++ b/view/managerUsers.php @@ -1,34 +1,34 @@ - - - - - <?php echo __("Users") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - -
    - -
    - - - + + + + + <?php echo __("Users") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + +
    + +
    + + + diff --git a/view/managerUsersGroups.php b/view/managerUsersGroups.php index d2bd8aeb3e..e098b21dc3 100644 --- a/view/managerUsersGroups.php +++ b/view/managerUsersGroups.php @@ -1,35 +1,35 @@ - - - - - <?php echo __("UserGroups") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - -
    - -
    - - - + + + + + <?php echo __("UserGroups") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + +
    + +
    + + + diff --git a/view/managerUsersGroups_body.php b/view/managerUsersGroups_body.php index 12c0ad55ff..7ac3aae2cc 100644 --- a/view/managerUsersGroups_body.php +++ b/view/managerUsersGroups_body.php @@ -1,219 +1,218 @@ -
    - -
    - - - - - - - - - -
    -
    -
    - - -
    - - +
    + +
    + + + + + + + + + +
    +
    +
    + + +
    + + diff --git a/view/managerUsersGroups_head.php b/view/managerUsersGroups_head.php index c9a640bd74..030837ad61 100644 --- a/view/managerUsersGroups_head.php +++ b/view/managerUsersGroups_head.php @@ -1,3 +1,2 @@ - \ No newline at end of file + -
    - -
    - -
    -
    -
    -
    - - - - - - - - - - - - -
    -
    -
    - - - - - - - - - - - - -
    -
    -
    - - - - - - - - - - - - -
    -
    - -
    -
    -
    - - -
    -
    - - - - - - - - - - - - -
    -
    - -
    -
    - - - - - - - - - - +
    +
    + +
    + +
    +
    +
    +
    + + + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + +
    +
    +
    + + + + + + + + + + + + +
    +
    + +
    +
    +
    + + +
    +
    + + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + + + + + + + diff --git a/view/managerUsers_head.php b/view/managerUsers_head.php index 36c86251f6..137e938a35 100644 --- a/view/managerUsers_head.php +++ b/view/managerUsers_head.php @@ -1,15 +1,15 @@ - - \ No newline at end of file diff --git a/view/managerVideos.php b/view/managerVideos.php index 65f6012188..c714ad761e 100644 --- a/view/managerVideos.php +++ b/view/managerVideos.php @@ -1,43 +1,42 @@ - - - - - <?php echo __("Audio and Video") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - - - + + + + + <?php echo __("Audio and Video") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + + + diff --git a/view/managerVideosLight.php b/view/managerVideosLight.php index d2f2ffc008..7eb007e6cf 100644 --- a/view/managerVideosLight.php +++ b/view/managerVideosLight.php @@ -1,72 +1,72 @@ -getTitle(); -$description = $video->getDescription(); -$categories_id = $video->getCategories_id(); -?> - - - - <?php echo __("Edit Video"); ?> - - - - - - - - +getTitle(); +$description = $video->getDescription(); +$categories_id = $video->getCategories_id(); +?> + + + + <?php echo __("Edit Video"); ?> + + + + + + + + diff --git a/view/managerVideosLight_image.php b/view/managerVideosLight_image.php index 43166e624b..e89acf7efc 100644 --- a/view/managerVideosLight_image.php +++ b/view/managerVideosLight_image.php @@ -1,66 +1,66 @@ - -posterPortraitPath; - $portreait = 1; -}else{ - $width = 1280; - $height = 720; - $path = empty($images->posterLandscapePath)?"{$global['systemRootPath']}view/img/notfound.jpg":$images->posterLandscapePath; - $portreait = 0; -} - -$image = str_replace(array($global['systemRootPath'], DIRECTORY_SEPARATOR), array($global['webSiteRootURL'], '/'), $path); - -$image = addQueryStringParameter($image, 'cache', filectime($path)); -//var_dump($image, $images);exit; -$croppie1 = getCroppie(__("Upload Poster"), "saveVideo", $width, $height, $viewportWidth); -echo $croppie1['html']; -?> -
    -
    - - -
    - \ No newline at end of file diff --git a/view/managerVideosLight_meta.php b/view/managerVideosLight_meta.php index 233ca5a5b5..fc281e56d9 100644 --- a/view/managerVideosLight_meta.php +++ b/view/managerVideosLight_meta.php @@ -1,54 +1,54 @@ - -
    -
    - - -
    -
    - - -
    -
    - - - disableHTMLDescription)) { - echo getTinyMCE("description"); - } - ?> -
    -
    -
    -
    - - -
    - \ No newline at end of file diff --git a/view/managerVideos_body.php b/view/managerVideos_body.php index 1985abb993..ae38150534 100644 --- a/view/managerVideos_body.php +++ b/view/managerVideos_body.php @@ -1,2299 +1,2291 @@ - - -
    - -
    -
    - -
    - - - - - - - - - - - - - - - - - - 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()) { ?> - - videosManegerBulkActionButtons) { - if (empty($advancedCustomUser->userCanNotChangeCategory) || Permissions::canAdminVideos()) { - ?> -
    - - -
    - -
    - - -
    - userCanNotChangeUserGroup) || Permissions::canAdminVideos()) { - ?> -
    - - -
    -
    - - -
    - disableVideoSwap) && (empty($advancedCustom->makeSwapVideosOnlyForAdmin) || Permissions::canAdminVideos())) { - ?> - - - - - - -
    - -
    -
    - - -
    -
    - - - - - - - - - - - - - - - - - - - - -
    - '); ?> - - '); ?> - - '); ?> - - '); ?> - - '); ?> - - '); ?> - - '); ?> -
    -
    -
    - - - - disableDownloadVideosList)) { - ?> - - getDisable_youtubeupload())) { - ?> -
    -

    -

    :

    -
      -
    1. - - " . __("Google ID and Key") . ""; ?> -
    2. -
    3. - - - " . __("YouTube Data API") . " v3"; ?> -
    4. -
    5. - : - objects/youtubeUpload.json.php -
    6. -
    7. - : - -
    8. -
    - -
    - -
    - - - - - - - - - - -disableHTMLDescription)) { - echo getTinyMCE("inputDescription"); -} -?> - + + +
    + +
    +
    + +
    + + + + + + + + + + + + + + + + + + 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()) { ?> + + videosManegerBulkActionButtons) { + if (empty($advancedCustomUser->userCanNotChangeCategory) || Permissions::canAdminVideos()) { + ?> +
    + + +
    + +
    + + +
    + userCanNotChangeUserGroup) || Permissions::canAdminVideos()) { + ?> +
    + + +
    +
    + + +
    + disableVideoSwap) && (empty($advancedCustom->makeSwapVideosOnlyForAdmin) || Permissions::canAdminVideos())) { + ?> + + + + + + +
    + +
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + +
    + '); ?> + + '); ?> + + '); ?> + + '); ?> + + '); ?> + + '); ?> + + '); ?> +
    +
    +
    + + + + disableDownloadVideosList)) { + ?> + + getDisable_youtubeupload())) { + ?> +
    +

    +

    :

    +
      +
    1. + + " . __("Google ID and Key") . ""; ?> +
    2. +
    3. + + + " . __("YouTube Data API") . " v3"; ?> +
    4. +
    5. + : + objects/youtubeUpload.json.php +
    6. +
    7. + : + +
    8. +
    + +
    + +
    + + + + + + + + + + +disableHTMLDescription)) { + echo getTinyMCE("inputDescription"); +} +?> + diff --git a/view/managerVideos_head.php b/view/managerVideos_head.php index 2d9f82c680..0b8cf5a40f 100644 --- a/view/managerVideos_head.php +++ b/view/managerVideos_head.php @@ -1,50 +1,50 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/view/manifest.json.php b/view/manifest.json.php index 5b9814bb94..259c73a9de 100644 --- a/view/manifest.json.php +++ b/view/manifest.json.php @@ -1,87 +1,87 @@ -pwa_display->value)){ - $obj->pwa_display->value = 'fullscreen'; -} - - -$pwa = new stdClass(); - -$pwa->short_name = $config->getWebSiteTitle(); -$pwa->name = $config->getWebSiteTitle(); -$pwa->description = $config->getWebSiteTitle(); - -$pwa->icons = pwaIconsArray(); - -//$pwa->start_url = $global['webSiteRootURL']; -$pwa->start_url = '/'; - -$pwa->background_color = $obj->pwa_background_color; -$pwa->theme_color = $obj->pwa_background_color; -$pwa->orientation = "any"; -$pwa->display_override = array($obj->pwa_display->value, 'fullscreen', 'standalone', 'minimal-ui', "window-control-overlay"); -$pwa->display = $obj->pwa_display->value; -$pwa->scope = $obj->pwa_scope; - -$pwa->related_applications = array(); -$pwa->related_applications[] = pwaRelated_applications('play', $obj->playStoreApp); -$pwa->related_applications[] = pwaRelated_applications('itunes', $obj->appleStoreApp); - - -$shortcut = new stdClass(); -$shortcut->name = $config->getWebSiteTitle(); -$shortcut->short_name = $config->getWebSiteTitle(); -$shortcut->description = $config->getWebSiteTitle(); -//$shortcut->url = $global['webSiteRootURL']; -$shortcut->url = '/'; -$shortcut->icons = pwaIconsArray(); - -$pwa->shortcuts = array($shortcut); - -echo _json_encode($pwa); - -function pwaRelated_applications($platform, $url) { - $obj = new stdClass(); - $obj->platform = $platform; - $obj->url = $url; - return $obj; -} - -function pwaIcon($src, $type, $sizes) { - $icon = new stdClass(); - $icon->src = $src; - $icon->type = $type; - $icon->sizes = $sizes; - return $icon; -} - -function pwaIconsArray() { - - $icon = array(); - - $favicon = Configuration::_getFavicon(true); - $faviconICO = Configuration::_getFavicon(false); - - $sizes = array(72, 96, 120, 128, 144, 152, 180, 192, 384, 512); - - foreach ($sizes as $value) { - $pwaIcon = "faviconPWA{$value}.png"; - if (!file_exists(getVideosDir() . $pwaIcon)) { - im_resizePNG($favicon['file'], getVideosDir() . $pwaIcon, $value, $value); - } - $icon[] = pwaIcon(getCDN() . 'videos/' . $pwaIcon, 'image/png', "{$value}x{$value}"); - } - //$icon[] = pwaIcon($favicon['url'], 'image/png', '180x180'); - //$icon[] = pwaIcon($faviconICO['url'], 'image/x-icon', '16x16,24x24,32x32,48x48,144x144'); - - return $icon; -} -?> \ No newline at end of file +pwa_display->value)) { + $obj->pwa_display->value = 'fullscreen'; +} + + +$pwa = new stdClass(); + +$pwa->short_name = $config->getWebSiteTitle(); +$pwa->name = $config->getWebSiteTitle(); +$pwa->description = $config->getWebSiteTitle(); + +$pwa->icons = pwaIconsArray(); + +//$pwa->start_url = $global['webSiteRootURL']; +$pwa->start_url = '/'; + +$pwa->background_color = $obj->pwa_background_color; +$pwa->theme_color = $obj->pwa_background_color; +$pwa->orientation = "any"; +$pwa->display_override = [$obj->pwa_display->value, 'fullscreen', 'standalone', 'minimal-ui', "window-control-overlay"]; +$pwa->display = $obj->pwa_display->value; +$pwa->scope = $obj->pwa_scope; + +$pwa->related_applications = []; +$pwa->related_applications[] = pwaRelated_applications('play', $obj->playStoreApp); +$pwa->related_applications[] = pwaRelated_applications('itunes', $obj->appleStoreApp); + + +$shortcut = new stdClass(); +$shortcut->name = $config->getWebSiteTitle(); +$shortcut->short_name = $config->getWebSiteTitle(); +$shortcut->description = $config->getWebSiteTitle(); +//$shortcut->url = $global['webSiteRootURL']; +$shortcut->url = '/'; +$shortcut->icons = pwaIconsArray(); + +$pwa->shortcuts = [$shortcut]; + +echo _json_encode($pwa); + +function pwaRelated_applications($platform, $url) +{ + $obj = new stdClass(); + $obj->platform = $platform; + $obj->url = $url; + return $obj; +} + +function pwaIcon($src, $type, $sizes) +{ + $icon = new stdClass(); + $icon->src = $src; + $icon->type = $type; + $icon->sizes = $sizes; + return $icon; +} + +function pwaIconsArray() +{ + $icon = []; + + $favicon = Configuration::_getFavicon(true); + $faviconICO = Configuration::_getFavicon(false); + + $sizes = [72, 96, 120, 128, 144, 152, 180, 192, 384, 512]; + + foreach ($sizes as $value) { + $pwaIcon = "faviconPWA{$value}.png"; + if (!file_exists(getVideosDir() . $pwaIcon)) { + im_resizePNG($favicon['file'], getVideosDir() . $pwaIcon, $value, $value); + } + $icon[] = pwaIcon(getCDN() . 'videos/' . $pwaIcon, 'image/png', "{$value}x{$value}"); + } + //$icon[] = pwaIcon($favicon['url'], 'image/png', '180x180'); + //$icon[] = pwaIcon($faviconICO['url'], 'image/x-icon', '16x16,24x24,32x32,48x48,144x144'); + + return $icon; +} diff --git a/view/mini-upload-form/index.php b/view/mini-upload-form/index.php index 1939bfd11f..279423f27b 100644 --- a/view/mini-upload-form/index.php +++ b/view/mini-upload-form/index.php @@ -1,24 +1,24 @@ - + <?php echo __("Upload your file") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - + @@ -30,16 +30,16 @@ if (!User::canUpload()) { - +
    " enctype="multipart/form-data">
    - + @@ -56,33 +56,32 @@ if (!User::canUpload()) {

    - +

    - encoder or use the public one"); ?> + encoder or use the public one"); ?>

    - +
    - +
    - + diff --git a/view/mini-upload-form/upload.php b/view/mini-upload-form/upload.php index f3ba564d29..904c2f2689 100644 --- a/view/mini-upload-form/upload.php +++ b/view/mini-upload-form/upload.php @@ -1,161 +1,156 @@ -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("", "", $videos_id); - $filename = $video->getFilename(); - 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 ($extension !== "jpg" && $video->getType() == "image") { - sleep(1); // to make sure the file will be available - $file = $video->getFilename(); - $jpgFrom = Video::getPathToFile("{$file}.{$extension}"); - $jpgTo = Video::getPathToFile("{$file}.jpg"); - try { - convertImage($jpgFrom, $jpgTo, 70); - } catch (Exception $exc) { - _error_log("We could not convert the image to JPG " . $exc->getMessage()); - } - } - - if (!empty($_FILES['upl']['tmp_name'])) { - $video->setAutoStatus(Video::$statusActive); - AVideoPlugin::onUploadIsDone($obj->videos_id); - AVideoPlugin::afterNewVideo($obj->videos_id); - } - die(json_encode($obj)); - } -} - -$obj->msg = "\$_FILES Error"; -$obj->FILES = $_FILES; -die(json_encode($obj)); +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']; + } elseif (!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("", "", $videos_id); + $filename = $video->getFilename(); + 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); + } elseif (($extension == "mp3") || ($extension == "ogg")) { + if (!empty($advancedCustom->disableMP3Upload)) { + $obj->msg = "MP3 Files are not Allowed"; + die(json_encode($obj)); + } + $video->setType("audio", true); + } elseif (($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 ($extension !== "jpg" && $video->getType() == "image") { + sleep(1); // to make sure the file will be available + $file = $video->getFilename(); + $jpgFrom = Video::getPathToFile("{$file}.{$extension}"); + $jpgTo = Video::getPathToFile("{$file}.jpg"); + try { + convertImage($jpgFrom, $jpgTo, 70); + } catch (Exception $exc) { + _error_log("We could not convert the image to JPG " . $exc->getMessage()); + } + } + + if (!empty($_FILES['upl']['tmp_name'])) { + $video->setAutoStatus(Video::$statusActive); + AVideoPlugin::onUploadIsDone($obj->videos_id); + AVideoPlugin::afterNewVideo($obj->videos_id); + } + die(json_encode($obj)); + } +} + +$obj->msg = "\$_FILES Error"; +$obj->FILES = $_FILES; +die(json_encode($obj)); diff --git a/view/modePlayLink.php b/view/modePlayLink.php index 8ad57d7b61..21fb443ef5 100644 --- a/view/modePlayLink.php +++ b/view/modePlayLink.php @@ -1,105 +1,105 @@ - - - - - - - - -
    - - -
    -
    -
    -
    -
    - -
    -
    - " value="" id="playFormInput" /> - - - -
    -
    - -
    -
    -
    -
    -
    - - - - + + + + + + + + +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + " value="" id="playFormInput" /> + + + +
    +
    +
    +
    +
    +
    +
    +
    + + + + diff --git a/view/modeYoutube.php b/view/modeYoutube.php index 79814b1ca3..8b1027943e 100644 --- a/view/modeYoutube.php +++ b/view/modeYoutube.php @@ -1,402 +1,401 @@ -thumbnails; - $poster = $evideo->thumbnails; - $imgw = 1280; - $imgh = 720; - $autoPlaySources = array(); - $autoPlayURL = ''; - $autoPlayPoster = ''; - $autoPlayThumbsSprit = ''; -} else { - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - require_once $global['systemRootPath'] . 'objects/user.php'; - require_once $global['systemRootPath'] . 'objects/category.php'; - require_once $global['systemRootPath'] . 'objects/subscribe.php'; - require_once $global['systemRootPath'] . 'objects/functions.php'; - - $img = "" . getCDN() . "view/img/notfound.jpg"; - $poster = "" . getCDN() . "view/img/notfound.jpg"; - $imgw = 1280; - $imgh = 720; - - if (!empty($_GET['type'])) { - if ($_GET['type'] == 'audio') { - $_SESSION['type'] = 'audio'; - } else - if ($_GET['type'] == 'video') { - $_SESSION['type'] = 'video'; - } else - if ($_GET['type'] == 'pdf') { - $_SESSION['type'] = 'pdf'; - } else { - $_SESSION['type'] = ""; - unset($_SESSION['type']); - } - } else { - unset($_SESSION['type']); - } - session_write_close(); - - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - if (!empty($_GET['playlist_id'])) { - $isSerie = 1; - if (preg_match("/^[0-9]+$/", $_GET['playlist_id'])) { - $playlist_id = $_GET['playlist_id']; - } else if (User::isLogged()) { - if ($_GET['playlist_id'] == "favorite") { - $playlist_id = PlayList::getFavoriteIdFromUser(User::getId()); - } else { - $playlist_id = PlayList::getWatchLaterIdFromUser(User::getId()); - } - } - - if (!empty($_GET['playlist_index'])) { - $playlist_index = $_GET['playlist_index']; - } - - $videosArrayId = PlayList::getVideosIdFromPlaylist($playlist_id); - if (empty($videosArrayId)) { - videoNotFound(__('Playlist is empty or does not exist')); - } - $videosPlayList = Video::getAllVideos("viewable", false, false, $videosArrayId, false, true); - $videosPlayList = PlayList::sortVideos($videosPlayList, $videosArrayId); - - $videoSerie = Video::getVideoFromSeriePlayListsId($playlist_id); - //var_dump($videoSerie, $videosArrayId);exit; - unset($_GET['playlist_id']); - $isPlayListTrailer = false; - - $playListObject = AVideoPlugin::getObjectData("PlayLists"); - - if (!empty($videoSerie)) { - $videoSerie = Video::getVideo($videoSerie["id"], "", true); - if (!empty($playListObject->showTrailerInThePlayList) && !empty($videoSerie["trailer1"]) && filter_var($videoSerie["trailer1"], FILTER_VALIDATE_URL) !== FALSE) { - $videoSerie["type"] = "embed"; - $videoSerie["videoLink"] = $videoSerie["trailer1"]; - array_unshift($videosPlayList, $videoSerie); - array_unshift($videosArrayId, $videoSerie['id']); - $isPlayListTrailer = true; - } - } - if (empty($playlist_index) && $isPlayListTrailer && !empty($videoSerie)) { - $video = $videoSerie; - } else { - $vid = new Video("", "", $videosPlayList[$playlist_index]['id']); - $_GET['videoName'] = $vid->getClean_title(); - $video = Video::getVideo($videosPlayList[$playlist_index]['id'], "viewable", false, false, false, true); - } - - if (!empty($videosPlayList[$playlist_index + 1])) { - $autoPlayVideo = Video::getVideo($videosPlayList[$playlist_index + 1]['id'], "viewableNotUnlisted", false, false, false, true); - $autoPlayVideo['url'] = $global['webSiteRootURL'] . "playlist/{$playlist_id}/" . ($playlist_index + 1); - } else if (!empty($videosPlayList[0])) { - $autoPlayVideo = Video::getVideo($videosPlayList[0]['id'], "viewableNotUnlisted", false, false, false, true); - $autoPlayVideo['url'] = $global['webSiteRootURL'] . "playlist/{$playlist_id}/0"; - } - - if ($serie = PlayLists::isPlayListASerie($playlist_id)) { - setVideos_id($serie['id']); - } else if (!empty($videosPlayList[$playlist_index])) { - setVideos_id($videosPlayList[$playlist_index]['id']); - } - } else { - $catLink = ""; - if (!empty($_GET['catName'])) { - $catLink = "cat/{$_GET['catName']}/"; - } - - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); -// add this because if you change the video category the video was not loading anymore - $catName = @$_GET['catName']; - - if (empty($_GET['clean_title']) && (isset($advancedCustom->forceCategory) && $advancedCustom->forceCategory === false)) { - $_GET['catName'] = ""; - } - - if (empty($video) && !empty($_REQUEST['v'])) { - $video = Video::getVideo($_REQUEST['v'], "viewable", false, false, false, true); - //var_dump('Line: '.__LINE__, $_REQUEST['v'], $video);exit; - } - - if (empty($video)) { - $video = Video::getVideo("", "viewable", false, false, true, true); - } - - if (empty($video)) { - $video = Video::getVideo("", "viewable", false, false, false, true); - } - if (empty($video)) { - $video = AVideoPlugin::getVideo(); - } - - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - if (!empty($_GET['v']) && (empty($video) || $video['id'] != $_GET['v'])) { - $video = false; - } - if (!empty($video['id'])) { - // allow users to count a view again in case it is refreshed - Video::unsetAddView($video['id']); - - // add this because if you change the video category the video was not loading anymore - $_GET['catName'] = $catName; - - $_GET['isMediaPlaySite'] = $video['id']; - $obj = new Video("", "", $video['id']); - } - - $get = array('channelName' => @$_GET['channelName'], 'catName' => @$_GET['catName']); - - $modeYouTubeTimeLog['Code part 1.1'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - if (!empty($video['next_videos_id'])) { - $modeYouTubeTimeLog['Code part 1.2'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - $autoPlayVideo = Video::getVideo($video['next_videos_id']); - } else { - $modeYouTubeTimeLog['Code part 1.3'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - $modeYouTubeTimeLog['Code part 1.5'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - if (!empty($video['id'])) { - $autoPlayVideo = Video::getRandom($video['id']); - } - //} - } - - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - $modeYouTubeTimeLog['Code part 1.6'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - if (!empty($autoPlayVideo)) { - $autoPlayVideo['creator'] = Video::getCreatorHTML($autoPlayVideo['users_id']); - $autoPlayVideo['tags'] = Video::getTags($autoPlayVideo['id'], '
    ' . humanTiming(strtotime($autoPlayVideo['videoCreation'])) . ''); - $autoPlayVideo['url'] = Video::getLink($autoPlayVideo['id'], $autoPlayVideo['clean_title'], false, $get); - } - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - } - $modeYouTubeTimeLog['Code part 2'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - if (!empty($video)) { - $name = User::getNameIdentificationById($video['users_id']); - $name = "{$name} " . User::getEmailVerifiedIcon($video['users_id']) . ""; - $subscribe = Subscribe::getButton($video['users_id']); - $video['creator'] = Video::getCreatorHTML($video['users_id'], '
    ' . humanTiming(strtotime($video['videoCreation'])) . ''); - - $obj = new Video("", "", $video['id']); - } - - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - if (!empty($video) && $video['type'] == "video") { - $poster = "{$global['webSiteRootURL']}videos/{$video['filename']}.jpg"; - } else { - $poster = "" . getCDN() . "view/img/audio_wave.jpg"; - } - - if (!empty($video)) { - $source = Video::getSourceFile($video['filename']); - if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { - $img = $source['url']; - $data = getimgsize($source['path']); - $imgw = $data[0]; - $imgh = $data[1]; - } else if ($video['type'] == "audio") { - $img = "" . getCDN() . "view/img/audio_wave.jpg"; - } - $type = 'video'; - if ($video['type'] === 'pdf') { - $type = 'pdf'; - } else if ($video['type'] === 'zip') { - $type = 'zip'; - } else if ($video['type'] === 'article') { - $type = 'article'; - } - $images = Video::getImageFromFilename($video['filename'], $type); - $poster = isMobile() ? $images->thumbsJpg : $images->poster; - 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($source['path']); - $imgw = $data[0]; - $imgh = $data[1]; - } else { - $img = isMobile() ? $images->thumbsJpg : $images->poster; - } - } else { - $poster = "" . getCDN() . "view/img/notfound.jpg"; - } - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - $objSecure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); - $modeYouTubeTimeLog['Code part 3'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - if (!empty($autoPlayVideo) && !empty($autoPlayVideo['filename'])) { - $autoPlaySources = getSources($autoPlayVideo['filename'], true); - $autoPlayURL = $autoPlayVideo['url']; - $autoPlayPoster = "{$global['webSiteRootURL']}videos/{$autoPlayVideo['filename']}.jpg"; - $autoPlayThumbsSprit = "{$global['webSiteRootURL']}videos/{$autoPlayVideo['filename']}_thumbsSprit.jpg"; - } else { - $autoPlaySources = array(); - $autoPlayURL = ''; - $autoPlayPoster = ''; - $autoPlayThumbsSprit = ""; - } - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - - if (empty($_GET['videoName']) && !empty($video)) { - $_GET['videoName'] = $video['clean_title']; - } - if (!empty($_GET['videoName'])) { - $v = Video::getVideoFromCleanTitle($_GET['videoName']); - } - if (empty($v) && empty($videosPlayList[$playlist_index]['id'])) { - videoNotFound(""); - } else { - $modeYouTubeTimeLog['Code part 4'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - AVideoPlugin::getModeYouTube($v['id']); - $modeYouTubeTimeLog['Code part 5'] = microtime(true) - $modeYouTubeTime; - $modeYouTubeTime = microtime(true); - } - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); -} - - -TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); -// video not found -if (empty($video)) { - videoNotFound('The video is not available'); -} -$metaDescription = " {$video['id']}"; - -// make sure the title tag does not have more then 70 chars -$titleTag = $video['title']; -$titleTag = (strlen($titleTag) > 50) ? (substr($titleTag, 0, 48) . " …") : $titleTag; -$titleTag .= getSEOComplement(array("allowedTypes" => array("audio", "video", "pdf"))) . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); -$titleTag = (strlen($titleTag) > 70) ? (substr($titleTag, 0, 68) . " …") : $titleTag; - -if (!empty($video['users_id']) && User::hasBlockedUser($video['users_id'])) { - $video['type'] = "blockedUser"; -} - -TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); -?> - - - - <?php echo $titleTag; ?> - - - - - - - showChannelBannerOnModeYoutube)) { - ?> -
    - -
    - -
    - -
    -
    -
    -
    -
    - ! videoNotFoundText->value) ? __("We have not found any videos or audios to show") : $advancedCustom->videoNotFoundText->value; ?>. -
    - -
    - disableYoutubePlayerIntegration || isMobile(); - - - TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); - if ((isset($_GET['isEmbedded'])) && ($disableYoutubeIntegration == false)) { - if ($_GET['isEmbedded'] == "y") { - ?> - - - - - - - - - - -thumbnails; + $poster = $evideo->thumbnails; + $imgw = 1280; + $imgh = 720; + $autoPlaySources = []; + $autoPlayURL = ''; + $autoPlayPoster = ''; + $autoPlayThumbsSprit = ''; +} else { + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + require_once $global['systemRootPath'] . 'objects/user.php'; + require_once $global['systemRootPath'] . 'objects/category.php'; + require_once $global['systemRootPath'] . 'objects/subscribe.php'; + require_once $global['systemRootPath'] . 'objects/functions.php'; + + $img = "" . getCDN() . "view/img/notfound.jpg"; + $poster = "" . getCDN() . "view/img/notfound.jpg"; + $imgw = 1280; + $imgh = 720; + + if (!empty($_GET['type'])) { + if ($_GET['type'] == 'audio') { + $_SESSION['type'] = 'audio'; + } elseif ($_GET['type'] == 'video') { + $_SESSION['type'] = 'video'; + } elseif ($_GET['type'] == 'pdf') { + $_SESSION['type'] = 'pdf'; + } else { + $_SESSION['type'] = ''; + unset($_SESSION['type']); + } + } else { + unset($_SESSION['type']); + } + session_write_close(); + + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + if (!empty($_GET['playlist_id'])) { + $isSerie = 1; + if (preg_match("/^[0-9]+$/", $_GET['playlist_id'])) { + $playlist_id = $_GET['playlist_id']; + } elseif (User::isLogged()) { + if ($_GET['playlist_id'] == "favorite") { + $playlist_id = PlayList::getFavoriteIdFromUser(User::getId()); + } else { + $playlist_id = PlayList::getWatchLaterIdFromUser(User::getId()); + } + } + + if (!empty($_GET['playlist_index'])) { + $playlist_index = $_GET['playlist_index']; + } + + $videosArrayId = PlayList::getVideosIdFromPlaylist($playlist_id); + if (empty($videosArrayId)) { + videoNotFound(__('Playlist is empty or does not exist')); + } + $videosPlayList = Video::getAllVideos("viewable", false, false, $videosArrayId, false, true); + $videosPlayList = PlayList::sortVideos($videosPlayList, $videosArrayId); + + $videoSerie = Video::getVideoFromSeriePlayListsId($playlist_id); + //var_dump($videoSerie, $videosArrayId);exit; + unset($_GET['playlist_id']); + $isPlayListTrailer = false; + + $playListObject = AVideoPlugin::getObjectData("PlayLists"); + + if (!empty($videoSerie)) { + $videoSerie = Video::getVideo($videoSerie["id"], "", true); + if (!empty($playListObject->showTrailerInThePlayList) && !empty($videoSerie["trailer1"]) && filter_var($videoSerie["trailer1"], FILTER_VALIDATE_URL) !== false) { + $videoSerie["type"] = "embed"; + $videoSerie["videoLink"] = $videoSerie["trailer1"]; + array_unshift($videosPlayList, $videoSerie); + array_unshift($videosArrayId, $videoSerie['id']); + $isPlayListTrailer = true; + } + } + if (empty($playlist_index) && $isPlayListTrailer && !empty($videoSerie)) { + $video = $videoSerie; + } else { + $vid = new Video("", "", $videosPlayList[$playlist_index]['id']); + $_GET['videoName'] = $vid->getClean_title(); + $video = Video::getVideo($videosPlayList[$playlist_index]['id'], "viewable", false, false, false, true); + } + + if (!empty($videosPlayList[$playlist_index + 1])) { + $autoPlayVideo = Video::getVideo($videosPlayList[$playlist_index + 1]['id'], "viewableNotUnlisted", false, false, false, true); + $autoPlayVideo['url'] = $global['webSiteRootURL'] . "playlist/{$playlist_id}/" . ($playlist_index + 1); + } elseif (!empty($videosPlayList[0])) { + $autoPlayVideo = Video::getVideo($videosPlayList[0]['id'], "viewableNotUnlisted", false, false, false, true); + $autoPlayVideo['url'] = $global['webSiteRootURL'] . "playlist/{$playlist_id}/0"; + } + + if ($serie = PlayLists::isPlayListASerie($playlist_id)) { + setVideos_id($serie['id']); + } elseif (!empty($videosPlayList[$playlist_index])) { + setVideos_id($videosPlayList[$playlist_index]['id']); + } + } else { + $catLink = ''; + if (!empty($_GET['catName'])) { + $catLink = "cat/{$_GET['catName']}/"; + } + + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + // add this because if you change the video category the video was not loading anymore + $catName = @$_GET['catName']; + + if (empty($_GET['clean_title']) && (isset($advancedCustom->forceCategory) && $advancedCustom->forceCategory === false)) { + $_GET['catName'] = ''; + } + + if (empty($video) && !empty($_REQUEST['v'])) { + $video = Video::getVideo($_REQUEST['v'], "viewable", false, false, false, true); + //var_dump('Line: '.__LINE__, $_REQUEST['v'], $video);exit; + } + + if (empty($video)) { + $video = Video::getVideo("", "viewable", false, false, true, true); + } + + if (empty($video)) { + $video = Video::getVideo("", "viewable", false, false, false, true); + } + if (empty($video)) { + $video = AVideoPlugin::getVideo(); + } + + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + if (!empty($_GET['v']) && (empty($video) || $video['id'] != $_GET['v'])) { + $video = false; + } + if (!empty($video['id'])) { + // allow users to count a view again in case it is refreshed + Video::unsetAddView($video['id']); + + // add this because if you change the video category the video was not loading anymore + $_GET['catName'] = $catName; + + $_GET['isMediaPlaySite'] = $video['id']; + $obj = new Video("", "", $video['id']); + } + + $get = ['channelName' => @$_GET['channelName'], 'catName' => @$_GET['catName']]; + + $modeYouTubeTimeLog['Code part 1.1'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + if (!empty($video['next_videos_id'])) { + $modeYouTubeTimeLog['Code part 1.2'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + $autoPlayVideo = Video::getVideo($video['next_videos_id']); + } else { + $modeYouTubeTimeLog['Code part 1.3'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + $modeYouTubeTimeLog['Code part 1.5'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + if (!empty($video['id'])) { + $autoPlayVideo = Video::getRandom($video['id']); + } + //} + } + + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + $modeYouTubeTimeLog['Code part 1.6'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + if (!empty($autoPlayVideo)) { + $autoPlayVideo['creator'] = Video::getCreatorHTML($autoPlayVideo['users_id']); + $autoPlayVideo['tags'] = Video::getTags($autoPlayVideo['id'], '
    ' . humanTiming(strtotime($autoPlayVideo['videoCreation'])) . ''); + $autoPlayVideo['url'] = Video::getLink($autoPlayVideo['id'], $autoPlayVideo['clean_title'], false, $get); + } + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + } + $modeYouTubeTimeLog['Code part 2'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + if (!empty($video)) { + $name = User::getNameIdentificationById($video['users_id']); + $name = "{$name} " . User::getEmailVerifiedIcon($video['users_id']) . ""; + $subscribe = Subscribe::getButton($video['users_id']); + $video['creator'] = Video::getCreatorHTML($video['users_id'], '
    ' . humanTiming(strtotime($video['videoCreation'])) . ''); + + $obj = new Video("", "", $video['id']); + } + + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + if (!empty($video) && $video['type'] == "video") { + $poster = "{$global['webSiteRootURL']}videos/{$video['filename']}.jpg"; + } else { + $poster = "" . getCDN() . "view/img/audio_wave.jpg"; + } + + if (!empty($video)) { + $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'; + } elseif ($video['type'] === 'zip') { + $type = 'zip'; + } elseif ($video['type'] === 'article') { + $type = 'article'; + } + $images = Video::getImageFromFilename($video['filename'], $type); + $poster = isMobile() ? $images->thumbsJpg : $images->poster; + 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($source['path']); + $imgw = $data[0]; + $imgh = $data[1]; + } else { + $img = isMobile() ? $images->thumbsJpg : $images->poster; + } + } else { + $poster = "" . getCDN() . "view/img/notfound.jpg"; + } + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + $objSecure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); + $modeYouTubeTimeLog['Code part 3'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + if (!empty($autoPlayVideo) && !empty($autoPlayVideo['filename'])) { + $autoPlaySources = getSources($autoPlayVideo['filename'], true); + $autoPlayURL = $autoPlayVideo['url']; + $autoPlayPoster = "{$global['webSiteRootURL']}videos/{$autoPlayVideo['filename']}.jpg"; + $autoPlayThumbsSprit = "{$global['webSiteRootURL']}videos/{$autoPlayVideo['filename']}_thumbsSprit.jpg"; + } else { + $autoPlaySources = []; + $autoPlayURL = ''; + $autoPlayPoster = ''; + $autoPlayThumbsSprit = ''; + } + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + + if (empty($_GET['videoName']) && !empty($video)) { + $_GET['videoName'] = $video['clean_title']; + } + if (!empty($_GET['videoName'])) { + $v = Video::getVideoFromCleanTitle($_GET['videoName']); + } + if (empty($v) && empty($videosPlayList[$playlist_index]['id'])) { + videoNotFound(""); + } else { + $modeYouTubeTimeLog['Code part 4'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + AVideoPlugin::getModeYouTube($v['id']); + $modeYouTubeTimeLog['Code part 5'] = microtime(true) - $modeYouTubeTime; + $modeYouTubeTime = microtime(true); + } + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); +} + + +TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); +// video not found +if (empty($video)) { + videoNotFound('The video is not available'); +} +$metaDescription = " {$video['id']}"; + +// make sure the title tag does not have more then 70 chars +$titleTag = $video['title']; +$titleTag = (strlen($titleTag) > 50) ? (substr($titleTag, 0, 48) . " …") : $titleTag; +$titleTag .= getSEOComplement(["allowedTypes" => ["audio", "video", "pdf"]]) . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); +$titleTag = (strlen($titleTag) > 70) ? (substr($titleTag, 0, 68) . " …") : $titleTag; + +if (!empty($video['users_id']) && User::hasBlockedUser($video['users_id'])) { + $video['type'] = "blockedUser"; +} + +TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); +?> + + + + <?php echo $titleTag; ?> + + + + + + + showChannelBannerOnModeYoutube)) { + ?> +
    + +
    + +
    + +
    +
    +
    +
    +
    + ! videoNotFoundText->value) ? __("We have not found any videos or audios to show") : $advancedCustom->videoNotFoundText->value; ?>. +
    + +
    + disableYoutubePlayerIntegration || isMobile(); + + + TimeLogEnd($timeLogNameMY, __LINE__, $TimeLogLimitMY); + if ((isset($_GET['isEmbedded'])) && ($disableYoutubeIntegration == false)) { + if ($_GET['isEmbedded'] == "y") { + ?> + + + + + + + + + + + \ No newline at end of file diff --git a/view/modeYoutubeBottom.php b/view/modeYoutubeBottom.php index eeb18e6bbe..70d63c6d75 100644 --- a/view/modeYoutubeBottom.php +++ b/view/modeYoutubeBottom.php @@ -1,334 +1,331 @@ -
    ' . humanTiming(strtotime($video['videoCreation'])) . ''); - $source = Video::getSourceFile($video['filename']); - if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { - $img = $source['url']; - $data = getimgsize($source['path']); - $imgw = $data[0]; - $imgh = $data[1]; - } else if ($video['type'] == "audio") { - $img = "" . getCDN() . "view/img/audio_wave.jpg"; - } - $type = 'video'; - if ($video['type'] === 'pdf') { - $type = 'pdf'; - } else if ($video['type'] === 'zip') { - $type = 'zip'; - } else if ($video['type'] === 'article') { - $type = 'article'; - } - $images = Video::getImageFromFilename($video['filename'], $type); - $poster = $images->poster; - 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($source['path']); - $imgw = $data[0]; - $imgh = $data[1]; - } -} -if (empty($video['created'])) { - return false; -} -if (User::hasBlockedUser($video['users_id'])) { - return false; -} -?> - - -
    -
    -
    - <?php echo str_replace('" class="img img-responsive rotate" height="130" itemprop="thumbnail" /> - - - - - - - - - " /> - -
    -
    -

    - -
    - "> - - - -
    - - - label === __("Group")) { - ?> - text; ?> - - -

    -
    - -
    - - doNotDisplayViews)) { - ?> - - - -
    -
    - -
    -
    - disableShareAndPlaylist)) { ?> - - - - - - $theLink) { - //$notAllowedKeys = array('m3u8'); - $notAllowedKeys = array(); - if (empty($advancedCustom->showImageDownloadOption)) { - $notAllowedKeys = array_merge($notAllowedKeys, array('jpg', 'gif', 'webp', 'pjpg')); - } - $keyFound = false; - foreach ($notAllowedKeys as $notAllowedKey) { - if (preg_match("/{$notAllowedKey}/", $key)) { - $keyFound = true; - break; - } - } - if ($keyFound) { - continue; - } - - $theLink['url'] = addQueryStringParameter($theLink['url'], "download", 1); - $theLink['url'] = addQueryStringParameter($theLink['url'], "title", $video['title'] . "_{$key}_." . ($video['type'] === 'audio' ? 'mp3' : 'mp4')); - - $parts = explode("_", $key); - $name = $key; - if (count($parts) > 1) { - $name = strtoupper($parts[0]); - if (is_numeric($parts[1])) { - $name .= "
    {$parts[1]}p
    " . getResolutionLabel($parts[1]); - } else { - $name .= "
    " . strtoupper($parts[1]) . "
    "; - } - } - - $filesToDownload[] = array('name' => $name, 'url' => $theLink['url']); - } - if (!empty($filesToDownload)) { - ?> - - - - - '; - } - } else { - echo ''; - } - ?> - - removeThumbsUpAndDown)) { - ?> - " id="dislikeBtn" data-toggle="tooltip" title="" > - - - " id="likeBtn" data-toggle="tooltip" title="" > - - - - - - -
    -
    - -
    - - - - - -
    -
    -
    -
    :
    - - -
    :
    -
    - -
    - -
    :
    -
    -
    -
    - -
    -
    - -
    - -
    -
    - -
    - -disableComments) && Video::showYoutubeModeOptions()) { - ?> -
    - -
    - +' . humanTiming(strtotime($video['videoCreation'])) . ''); + $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'; + } elseif ($video['type'] === 'zip') { + $type = 'zip'; + } elseif ($video['type'] === 'article') { + $type = 'article'; + } + $images = Video::getImageFromFilename($video['filename'], $type); + $poster = $images->poster; + 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($source['path']); + $imgw = $data[0]; + $imgh = $data[1]; + } +} +if (empty($video['created'])) { + return false; +} +if (User::hasBlockedUser($video['users_id'])) { + return false; +} +?> + + +
    +
    +
    + <?php echo str_replace('" class="img img-responsive rotate" height="130" itemprop="thumbnail" /> + + + + + + + + - " /> + +
    +
    +

    + +
    + "> + + + +
    + + + label === __("Group")) { + ?> + text; ?> + + +

    +
    + +
    + + doNotDisplayViews)) { + ?> + + + +
    +
    + +
    +
    + disableShareAndPlaylist)) { ?> + + + + + + $theLink) { + //$notAllowedKeys = array('m3u8'); + $notAllowedKeys = []; + if (empty($advancedCustom->showImageDownloadOption)) { + $notAllowedKeys = array_merge($notAllowedKeys, ['jpg', 'gif', 'webp', 'pjpg']); + } + $keyFound = false; + foreach ($notAllowedKeys as $notAllowedKey) { + if (preg_match("/{$notAllowedKey}/", $key)) { + $keyFound = true; + break; + } + } + if ($keyFound) { + continue; + } + + $theLink['url'] = addQueryStringParameter($theLink['url'], "download", 1); + $theLink['url'] = addQueryStringParameter($theLink['url'], "title", $video['title'] . "_{$key}_." . ($video['type'] === 'audio' ? 'mp3' : 'mp4')); + + $parts = explode("_", $key); + $name = $key; + if (count($parts) > 1) { + $name = strtoupper($parts[0]); + if (is_numeric($parts[1])) { + $name .= "
    {$parts[1]}p
    " . getResolutionLabel($parts[1]); + } else { + $name .= "
    " . strtoupper($parts[1]) . "
    "; + } + } + + $filesToDownload[] = ['name' => $name, 'url' => $theLink['url']]; + } + if (!empty($filesToDownload)) { + ?> + + + + + '; + } + } else { + echo ''; + } + ?> + + removeThumbsUpAndDown)) { + ?> + " id="dislikeBtn" data-toggle="tooltip" title="" > + + + " id="likeBtn" data-toggle="tooltip" title="" > + + + + + + +
    +
    + +
    + + + + + +
    +
    +
    +
    :
    + + +
    :
    +
    + +
    + +
    :
    +
    +
    +
    + +
    +
    + +
    + +
    +
    + +
    + +disableComments) && Video::showYoutubeModeOptions()) { + ?> +
    + +
    + diff --git a/view/modeYoutubeBottomRight.php b/view/modeYoutubeBottomRight.php index f981e7df2d..94a50779c1 100644 --- a/view/modeYoutubeBottomRight.php +++ b/view/modeYoutubeBottomRight.php @@ -1,96 +1,97 @@ - -
    - -
    - - - -
    - - - - - "> - -
    - > - -
    -
    -
    - -
    -
    - - - - - "> - -
    - > - -
    -
    -
    -
    - -
    -
    -
    - - -
    - -
    - - - - + +
    + + + + + "> + +
    + > + +
    +
    +
    + +
    +
    + + + + + "> + +
    + > + +
    +
    +
    +
    + +
    +
    +
    + + +
    + +
    + + + + \ No newline at end of file diff --git a/view/modeYoutubeBundle.php b/view/modeYoutubeBundle.php index 5aa61fcf6b..d62ab4af64 100644 --- a/view/modeYoutubeBundle.php +++ b/view/modeYoutubeBundle.php @@ -1,105 +1,92 @@ - -
    - -
    - -
    -
    -
    - -
    - -
    - - -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    - -
    - -
    - -
    -
    - -
    -
    -
    -
    -
    - -
    -
    -
    -
    - +
    + +
    + +
    +
    +
    + +
    + +
    + + +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    + +
    + +
    + +
    +
    + +
    +
    +
    +
    +
    + +
    +
    +
    +
    + \ No newline at end of file diff --git a/view/modeYoutubeTop.php b/view/modeYoutubeTop.php index 49ff73cda7..ce372ff9d9 100644 --- a/view/modeYoutubeTop.php +++ b/view/modeYoutubeTop.php @@ -1,36 +1,36 @@ -
    -
    -
    - - - -
    -
    -
    - -
    -
    -
    -
    - -
    -
    +
    +
    +
    + + + +
    +
    +
    + +
    +
    +
    +
    + +
    +
    \ No newline at end of file diff --git a/view/oembed.php b/view/oembed.php index fa54f70baf..d4f7f8c09e 100644 --- a/view/oembed.php +++ b/view/oembed.php @@ -1,100 +1,98 @@ -getWebSiteTitle()); -$description = html2plainText($video['description']); -$link = Video::getLinkToVideo($videos_id); -$embedURL = Video::getLinkToVideo($videos_id, $video['clean_title'], true); -$duration = Video::getItemDurationSeconds($video['duration']); -$code = str_replace("{embedURL}", $embedURL, $advancedCustom->embedCodeTemplate); - -if ($format === 'xml') { - header('Content-type: application/xml'); - ?> - - 1.0 - rich - - - <?php echo $title; ?> - - - - - - version = 1.0; - $obj->type = "rich"; - $obj->width = $imgw; - $obj->height = $imgh; - $obj->title = $title; - $obj->url = $link; - $obj->provider_name = $siteTitle; - $obj->provider_url = $global['webSiteRootURL']; - $obj->html = $code; - die(json_encode($obj)); - -} - - +getWebSiteTitle()); +$description = html2plainText($video['description']); +$link = Video::getLinkToVideo($videos_id); +$embedURL = Video::getLinkToVideo($videos_id, $video['clean_title'], true); +$duration = Video::getItemDurationSeconds($video['duration']); +$code = str_replace("{embedURL}", $embedURL, $advancedCustom->embedCodeTemplate); + +if ($format === 'xml') { + header('Content-type: application/xml'); ?> + + 1.0 + rich + + + <?php echo $title; ?> + + + + + + version = 1.0; + $obj->type = "rich"; + $obj->width = $imgw; + $obj->height = $imgh; + $obj->title = $title; + $obj->url = $link; + $obj->provider_name = $siteTitle; + $obj->provider_url = $global['webSiteRootURL']; + $obj->html = $code; + die(json_encode($obj)); + } + + ?> \ No newline at end of file diff --git a/view/og.php b/view/og.php index 78b938d14e..0c6597631b 100644 --- a/view/og.php +++ b/view/og.php @@ -1,18 +1,18 @@ - - - - - <?php echo $config->getWebSiteTitle(); ?> - - - - - + + + + + <?php echo $config->getWebSiteTitle(); ?> + + + + + diff --git a/view/report.json.php b/view/report.json.php index ea8b3bba9d..db86ae89e4 100644 --- a/view/report.json.php +++ b/view/report.json.php @@ -1,101 +1,101 @@ -error = true; -$obj->msg = ''; -$obj->configAuthCanViewChart = $config->getAuthCanViewChart(); -$obj->performance = new stdClass(); -$obj->performance->start = microtime(true); - -if(empty($_REQUEST['users_id'])){ - $obj->users_id = User::getId(); -}else{ - $obj->users_id = intval($_REQUEST['users_id']); -} - -if(empty($obj->users_id)){ - $obj->msg = 'You MUST Specify a user'; - die(_json_encode($obj)); -} - -$user = new User($obj->users_id); - -if(empty($user->getUser())){ - $obj->msg = 'Invalid user'; - die(_json_encode($obj)); -} - -$obj->users_id_statistics = $obj->users_id; -if(User::isAdmin() && !empty($_REQUEST['isAdminPanel'])){ - $obj->users_id_statistics = 0; // show all results - $obj->totalUsers = User::getTotalUsers(false, 'a'); -}else if(User::getId() !== $obj->users_id_statistics){ - $obj->msg = 'Invalid user'; - die(_json_encode($obj)); -} - -$cacheName = 'statisticsReport_'.$obj->users_id_statistics; - -$cache = ObjectYPT::getCache($cacheName, 300); // 5 min cache -if(!empty($cache)){ - if(empty($cache->performance)){ - $cache->performance = new stdClass(); - } - if(empty($cache->performance->cache)){ - $cache->performance->cache = new stdClass(); - } - $cache->performance->cache->time = time(); - $cache->performance->cache->date = date('Y-m-d H:i:s'); - $cache->performance->cache->cache_duration = microtime(true) - $obj->start; - $cache->performance->cache->human = humanTimingAgo($cache->performance->time, 2); - die(_json_encode($cache)); -} - -$obj->can_upload = $user->getCanUpload(); -$obj->can_view_charts = $user->getCanViewChart(); - -if (!$user->getIsAdmin() && empty($obj->can_view_charts)) { - if ($obj->configAuthCanViewChart == 0 && !$obj->can_upload) { - $obj->msg = 'Only uploaders have charts'; - die(_json_encode($obj)); - } - if ($obj->configAuthCanViewChart == 1) { - $obj->msg = 'This user is not selected to display charts'; - die(_json_encode($obj)); - } -} - -$obj->error = false; -$obj->totalVideos = VideosStatistics::getTotalVideos($obj->users_id_statistics); -$obj->totalSubscriptions = VideosStatistics::getTotalSubscriptions($obj->users_id_statistics); -$obj->totalComents = VideosStatistics::getTotalComments($obj->users_id_statistics); -$obj->totalVideosViews = VideosStatistics::getTotalVideosViews($obj->users_id_statistics); -$obj->totalDurationVideos = intval(VideosStatistics::getTotalDuration($obj->users_id_statistics) / 60); -$obj->totalLikes = VideosStatistics::getTotalLikes($obj->users_id_statistics); -$obj->totalDislikes = VideosStatistics::getTotalDislikes($obj->users_id_statistics); - -$obj->today = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 1, 10); -$obj->last7Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 7, 10); -$obj->last15Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 15, 10); -$obj->last30Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 30); -$obj->last90Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 90); - - -$obj->performance->end = microtime(true); -$obj->performance->time = time(); -$obj->performance->date = date('Y-m-d H:i:s'); -$obj->performance->duration = $obj->end - $obj->start; - - -ObjectYPT::setCache($cacheName, $obj); - -echo _json_encode($obj); +error = true; +$obj->msg = ''; +$obj->configAuthCanViewChart = $config->getAuthCanViewChart(); +$obj->performance = new stdClass(); +$obj->performance->start = microtime(true); + +if (empty($_REQUEST['users_id'])) { + $obj->users_id = User::getId(); +} else { + $obj->users_id = intval($_REQUEST['users_id']); +} + +if (empty($obj->users_id)) { + $obj->msg = 'You MUST Specify a user'; + die(_json_encode($obj)); +} + +$user = new User($obj->users_id); + +if (empty($user->getUser())) { + $obj->msg = 'Invalid user'; + die(_json_encode($obj)); +} + +$obj->users_id_statistics = $obj->users_id; +if (User::isAdmin() && !empty($_REQUEST['isAdminPanel'])) { + $obj->users_id_statistics = 0; // show all results + $obj->totalUsers = User::getTotalUsers(false, 'a'); +} elseif (User::getId() !== $obj->users_id_statistics) { + $obj->msg = 'Invalid user'; + die(_json_encode($obj)); +} + +$cacheName = 'statisticsReport_'.$obj->users_id_statistics; + +$cache = ObjectYPT::getCache($cacheName, 300); // 5 min cache +if (!empty($cache)) { + if (empty($cache->performance)) { + $cache->performance = new stdClass(); + } + if (empty($cache->performance->cache)) { + $cache->performance->cache = new stdClass(); + } + $cache->performance->cache->time = time(); + $cache->performance->cache->date = date('Y-m-d H:i:s'); + $cache->performance->cache->cache_duration = microtime(true) - $obj->start; + $cache->performance->cache->human = humanTimingAgo($cache->performance->time, 2); + die(_json_encode($cache)); +} + +$obj->can_upload = $user->getCanUpload(); +$obj->can_view_charts = $user->getCanViewChart(); + +if (!$user->getIsAdmin() && empty($obj->can_view_charts)) { + if ($obj->configAuthCanViewChart == 0 && !$obj->can_upload) { + $obj->msg = 'Only uploaders have charts'; + die(_json_encode($obj)); + } + if ($obj->configAuthCanViewChart == 1) { + $obj->msg = 'This user is not selected to display charts'; + die(_json_encode($obj)); + } +} + +$obj->error = false; +$obj->totalVideos = VideosStatistics::getTotalVideos($obj->users_id_statistics); +$obj->totalSubscriptions = VideosStatistics::getTotalSubscriptions($obj->users_id_statistics); +$obj->totalComents = VideosStatistics::getTotalComments($obj->users_id_statistics); +$obj->totalVideosViews = VideosStatistics::getTotalVideosViews($obj->users_id_statistics); +$obj->totalDurationVideos = intval(VideosStatistics::getTotalDuration($obj->users_id_statistics) / 60); +$obj->totalLikes = VideosStatistics::getTotalLikes($obj->users_id_statistics); +$obj->totalDislikes = VideosStatistics::getTotalDislikes($obj->users_id_statistics); + +$obj->today = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 1, 10); +$obj->last7Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 7, 10); +$obj->last15Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 15, 10); +$obj->last30Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 30); +$obj->last90Days = VideosStatistics::getMostViewedVideosFromLastDays($obj->users_id_statistics, 90); + + +$obj->performance->end = microtime(true); +$obj->performance->time = time(); +$obj->performance->date = date('Y-m-d H:i:s'); +$obj->performance->duration = $obj->end - $obj->start; + + +ObjectYPT::setCache($cacheName, $obj); + +echo _json_encode($obj); diff --git a/view/report0.php b/view/report0.php index 04a51c5ab0..c47033777c 100644 --- a/view/report0.php +++ b/view/report0.php @@ -1,365 +1,365 @@ -
    -
    - -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    - -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    - -
    -
    -
    0
    -
    -
    -
    -
    - - - -
    -
    -
    -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
    - \ No newline at end of file diff --git a/view/report0_total_views.php b/view/report0_total_views.php index d3f5a12faa..8b13789179 100644 --- a/view/report0_total_views.php +++ b/view/report0_total_views.php @@ -1 +1 @@ - + diff --git a/view/report1.json.php b/view/report1.json.php index 4cf1933534..f9b89103a9 100644 --- a/view/report1.json.php +++ b/view/report1.json.php @@ -1,52 +1,53 @@ -getAuthCanViewChart() == 0){ -// list all channels - if(User::isAdmin()){ - $users = Channel::getChannels(); - }else if(User::isLogged()){ - $users = array(array('id'=> User::getId())); - }else{ - $users = array(); - } -} else if($config->getAuthCanViewChart() == 1){ - if((!empty($_SESSION['user']['canViewChart']))||(User::isAdmin())) { - $users = Channel::getChannels(); - } -} - -$rows = array(); -foreach ($users as $key => $value) { - // list all videos on that channel - $videos = Video::getAllVideos("a", $value['id']); - $identification = User::getNameIdentificationById($value['id']); - $views = 0; - foreach ($videos as $key2 => $value2) { - $views+=VideoStatistic::getStatisticTotalViews($value2['id'], false, $from, $to); - } - if(empty($views)){ - continue;; - } - $item = array( - 'views'=>$views, - 'channel'=>"{$identification}" - - ); - $rows[] = $item; -} - -$obj = new stdClass(); - -$obj->data = $rows; - -echo json_encode($obj); +getAuthCanViewChart() == 0) { + // list all channels + if (User::isAdmin()) { + $users = Channel::getChannels(); + } elseif (User::isLogged()) { + $users = [['id'=> User::getId()]]; + } else { + $users = []; + } +} elseif ($config->getAuthCanViewChart() == 1) { + if ((!empty($_SESSION['user']['canViewChart']))||(User::isAdmin())) { + $users = Channel::getChannels(); + } +} + +$rows = []; +foreach ($users as $key => $value) { + // list all videos on that channel + $videos = Video::getAllVideos("a", $value['id']); + $identification = User::getNameIdentificationById($value['id']); + $views = 0; + foreach ($videos as $key2 => $value2) { + $views+=VideoStatistic::getStatisticTotalViews($value2['id'], false, $from, $to); + } + if (empty($views)) { + continue; + ; + } + $item = [ + 'views'=>$views, + 'channel'=>"{$identification}", + + ]; + $rows[] = $item; +} + +$obj = new stdClass(); + +$obj->data = $rows; + +echo json_encode($obj); diff --git a/view/report1.php b/view/report1.php index 8c59d7a58a..4ffa5bfce9 100644 --- a/view/report1.php +++ b/view/report1.php @@ -1,85 +1,85 @@ -
    -
    - -
    - -
    -
    -
    - -
    - -
    -
    -
    - -
    -
    - - - - - - - - - - - - - -
    - \ No newline at end of file diff --git a/view/report2.json.php b/view/report2.json.php index 97d36f9d85..5926fd1278 100644 --- a/view/report2.json.php +++ b/view/report2.json.php @@ -1,50 +1,50 @@ -getAuthCanViewChart() == 0){ - if(User::isAdmin()){ - $users = User::getAllUsers(); - }else if(User::isLogged()){ - $users = array(array('id'=> User::getId())); - }else{ - $users = array(); - } -} else if($config->getAuthCanViewChart() == 1){ - if((!empty($_SESSION['user']['canViewChart']))||(User::isAdmin())) { - $users = User::getAllUsers(true); - } -} - -$rows = array(); -foreach ($users as $key => $value) { - // list all videos on that channel - $identification = User::getNameIdentificationById($value['id']); - $thumbs = Comment::getTotalCommentsThumbsUpFromUser($value['id'], $from, $to); - if(empty($thumbs['thumbsUp']) && empty($thumbs['thumbsDown'])){ - continue; - } - $item = array( - 'thumbsUp'=>$thumbs['thumbsUp'], - 'thumbsDown'=>$thumbs['thumbsDown'], - 'user'=>"{$identification}" - - ); - $rows[] = $item; -} - -$obj = new stdClass(); - -$obj->data = $rows; - -echo json_encode($obj); +getAuthCanViewChart() == 0) { + if (User::isAdmin()) { + $users = User::getAllUsers(); + } elseif (User::isLogged()) { + $users = [['id'=> User::getId()]]; + } else { + $users = []; + } +} elseif ($config->getAuthCanViewChart() == 1) { + if ((!empty($_SESSION['user']['canViewChart']))||(User::isAdmin())) { + $users = User::getAllUsers(true); + } +} + +$rows = []; +foreach ($users as $key => $value) { + // list all videos on that channel + $identification = User::getNameIdentificationById($value['id']); + $thumbs = Comment::getTotalCommentsThumbsUpFromUser($value['id'], $from, $to); + if (empty($thumbs['thumbsUp']) && empty($thumbs['thumbsDown'])) { + continue; + } + $item = [ + 'thumbsUp'=>$thumbs['thumbsUp'], + 'thumbsDown'=>$thumbs['thumbsDown'], + 'user'=>"{$identification}", + + ]; + $rows[] = $item; +} + +$obj = new stdClass(); + +$obj->data = $rows; + +echo json_encode($obj); diff --git a/view/report2.php b/view/report2.php index 3380d3bfeb..c5ef01b2e7 100644 --- a/view/report2.php +++ b/view/report2.php @@ -1,87 +1,87 @@ -
    -
    - -
    - -
    -
    -
    - -
    - -
    -
    -
    - -
    -
    - - - - - - - - - - - - - - - -
    - \ No newline at end of file diff --git a/view/report3.json.php b/view/report3.json.php index 1376ae19ab..d660cec041 100644 --- a/view/report3.json.php +++ b/view/report3.json.php @@ -1,50 +1,50 @@ -getAuthCanViewChart() == 0){ -// list all channels - if(User::isAdmin()){ - $users = User::getAllUsers(); - }else if(User::isLogged()){ - $users = array(array('id'=> User::getId())); - }else{ - $users = array(); - } -} else if($config->getAuthCanViewChart() == 1){ - if((!empty($_SESSION['user']['canViewChart']))||(User::isAdmin())) { - $users = User::getAllUsers(true); - } -} -$rows = array(); -foreach ($users as $key => $value) { - // list all videos on that channel - $identification = User::getNameIdentificationById($value['id']); - //$thumbs = Video::getTotalVideosThumbsUpFromUser($value['id'], $from, $to); - $thumbs = Video::getTotalVideosThumbsUpFromUserFromVideos($value['id']); - if(empty($thumbs['thumbsUp']) && empty($thumbs['thumbsDown'])){ - continue; - } - $item = array( - 'thumbsUp'=>$thumbs['thumbsUp'], - 'thumbsDown'=>$thumbs['thumbsDown'], - 'channel'=>"{$identification}" - - ); - $rows[] = $item; -} - -$obj = new stdClass(); - -$obj->data = $rows; - -echo json_encode($obj); +getAuthCanViewChart() == 0) { + // list all channels + if (User::isAdmin()) { + $users = User::getAllUsers(); + } elseif (User::isLogged()) { + $users = [['id'=> User::getId()]]; + } else { + $users = []; + } +} elseif ($config->getAuthCanViewChart() == 1) { + if ((!empty($_SESSION['user']['canViewChart']))||(User::isAdmin())) { + $users = User::getAllUsers(true); + } +} +$rows = []; +foreach ($users as $key => $value) { + // list all videos on that channel + $identification = User::getNameIdentificationById($value['id']); + //$thumbs = Video::getTotalVideosThumbsUpFromUser($value['id'], $from, $to); + $thumbs = Video::getTotalVideosThumbsUpFromUserFromVideos($value['id']); + if (empty($thumbs['thumbsUp']) && empty($thumbs['thumbsDown'])) { + continue; + } + $item = [ + 'thumbsUp'=>$thumbs['thumbsUp'], + 'thumbsDown'=>$thumbs['thumbsDown'], + 'channel'=>"{$identification}", + + ]; + $rows[] = $item; +} + +$obj = new stdClass(); + +$obj->data = $rows; + +echo json_encode($obj); diff --git a/view/report3.php b/view/report3.php index 15ecfc4693..61ef4acc27 100644 --- a/view/report3.php +++ b/view/report3.php @@ -1,90 +1,90 @@ - - - - - - - - - - - - - - - - -
    - \ No newline at end of file diff --git a/view/robots.txt.php b/view/robots.txt.php index b9d3e24dbf..9479b720fd 100644 --- a/view/robots.txt.php +++ b/view/robots.txt.php @@ -1,12 +1,11 @@ - -Sitemap: sitemap.xml -User-Agent: * + +Sitemap: sitemap.xml +User-Agent: * robotsTXT->value; ?> \ No newline at end of file diff --git a/view/signUp.php b/view/signUp.php index 1067a712fd..ddf3313dc9 100644 --- a/view/signUp.php +++ b/view/signUp.php @@ -1,211 +1,212 @@ -disableNativeSignUp)) { - die(__("Sign Up Disabled")); -} - -$agreement = AVideoPlugin::loadPluginIfEnabled("SignUpAgreement"); - -$signInLink = "{$global['webSiteRootURL']}user?redirectUri=" . urlencode(isset($_GET['redirectUri']) ? $_GET['redirectUri'] : ""); -if (!empty($_GET['siteRedirectUri'])) { - $signInLink = $_GET['siteRedirectUri']; -} -?> - - - - <?php echo __("Sign Up") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    - messageToAppearAboveSignUpBox->value)) { - echo $advancedCustomUser->messageToAppearAboveSignUpBox->value; - } - ?> -
    -
    -
    -
    - -
    -
    - - " class="form-control" type="text" value="" required > -
    -
    -
    -
    - -
    -
    - - " class="form-control" type="forceLoginToBeTheEmail) ? "text" : "email"; ?>" value="" required > -
    -
    -
    - forceLoginToBeTheEmail)) { - ?> -
    - -
    -
    - - " class="form-control" type="email" value="" required > -
    -
    -
    - -
    - -
    - -
    -
    - -
    - -
    - -
    -
    -
    - getSignupCheckBox(); - } - ?> -
    - -
    - -
    -
    - - - " class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText"> -
    -
    -
    - - - -
    -
    - -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - +disableNativeSignUp)) { + die(__("Sign Up Disabled")); +} + +$agreement = AVideoPlugin::loadPluginIfEnabled("SignUpAgreement"); + +$signInLink = "{$global['webSiteRootURL']}user?redirectUri=" . urlencode($_GET['redirectUri'] ?? ""); +if (!empty($_GET['siteRedirectUri'])) { + $signInLink = $_GET['siteRedirectUri']; +} +?> + + + + <?php echo __("Sign Up") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    + messageToAppearAboveSignUpBox->value)) { + echo $advancedCustomUser->messageToAppearAboveSignUpBox->value; + } + ?> +
    +
    +
    +
    + +
    +
    + + " class="form-control" type="text" value="" required > +
    +
    +
    +
    + +
    +
    + + " class="form-control" type="forceLoginToBeTheEmail) ? "text" : "email"; ?>" value="" required > +
    +
    +
    + forceLoginToBeTheEmail)) { + ?> +
    + +
    +
    + + " class="form-control" type="email" value="" required > +
    +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    +
    + getSignupCheckBox(); + } + ?> +
    + +
    + +
    +
    + + + " class="form-control" type="text" style="height: 60px;" maxlength="5" id="captchaText"> +
    +
    +
    + + + +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + +
    + + + + + diff --git a/view/sitemap.xml.php b/view/sitemap.xml.php index 3935844470..5975a58379 100644 --- a/view/sitemap.xml.php +++ b/view/sitemap.xml.php @@ -1,36 +1,35 @@ - strtotime('-10 minutes')) { - _error_log('Please wait we are creating the sitemap'); - $sitemap = ObjectYPT::getCache($name, 0); - if(empty($sitemap)){ - echo ""; - exit; - }else{ - echo $sitemap; - exit; - } -} -if (empty($sitemap)) { - file_put_contents($lockFile, time()); - $sitemap = siteMap(); - ObjectYPT::setCache($name, $sitemap); - unlink($lockFile); -} else { - $sitemap .= ""; -} -echo $sitemap; -exit; + strtotime('-10 minutes')) { + _error_log('Please wait we are creating the sitemap'); + $sitemap = ObjectYPT::getCache($name, 0); + if (empty($sitemap)) { + echo ""; + exit; + } else { + echo $sitemap; + exit; + } +} +if (empty($sitemap)) { + file_put_contents($lockFile, time()); + $sitemap = siteMap(); + ObjectYPT::setCache($name, $sitemap); + unlink($lockFile); +} else { + $sitemap .= ""; +} +echo $sitemap; +exit; diff --git a/view/subscribeBtn.html b/view/subscribeBtn.html index 0647e59739..ab99b0db42 100644 --- a/view/subscribeBtn.html +++ b/view/subscribeBtn.html @@ -1,26 +1,26 @@ -
    - - - - +
    + + + +
    \ No newline at end of file diff --git a/view/subscribeBtnOffline.html b/view/subscribeBtnOffline.html index 0dfcdb1b6f..d70105dc7e 100644 --- a/view/subscribeBtnOffline.html +++ b/view/subscribeBtnOffline.html @@ -1,10 +1,10 @@ -
    - +
    +
    \ No newline at end of file diff --git a/view/theme.css.php b/view/theme.css.php index 8ed641a17a..4b6ac1c785 100644 --- a/view/theme.css.php +++ b/view/theme.css.php @@ -1,18 +1,18 @@ - - - - - <?php echo __("Trending") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - -
    -
    -
    - - - -
    - - - -
    -
    -
    - -
    -
    - -
    -

    -

    -
    - - - - - - - - - - - + + + + + <?php echo __("Trending") . getSEOComplement() . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + +
    +
    +
    + + + +
    + + + +
    +
    +
    + +
    +
    + +
    +

    +

    +
    + + + + + + + + + + + diff --git a/view/unsubscribe.php b/view/unsubscribe.php index 6f87171f8a..2eed3590b7 100644 --- a/view/unsubscribe.php +++ b/view/unsubscribe.php @@ -1,68 +1,68 @@ -setNotify(0); -$subscribe->save(); - -?> - - - - <?php echo __("Unsubscribe"); ?> - - - - - - -
    -
    -
    -
    - -
    -
    -

    - -
    -
    - -
    - - - - - +setNotify(0); +$subscribe->save(); + +?> + + + + <?php echo __("Unsubscribe"); ?> + + + + + + +
    +
    +
    +
    + +
    +
    +

    + +
    +
    + +
    + + + + + diff --git a/view/update.php b/view/update.php index aec497baa5..41b8e0935b 100644 --- a/view/update.php +++ b/view/update.php @@ -1,200 +1,197 @@ - - - - - <?php echo __("Update AVideo System") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - -
    -
    -
    - -
    -
    - getVersion()); ?> -
    - -
    -
    -
    - - - - " . count($updateFiles) . ""); ?> -
    - -
    -
    -
    - - - -
    - Our repository is now running at version version; ?>. - You can follow this Update Tutorial - to update your files and get the latest version. -
    - -
    -

    -
    - error = ""; - foreach ($lines as $line) { - if (substr($line, 0, 2) == '--' || $line == '') - continue; - $templine .= $line; - if (substr(trim($line), -1, 1) == ';') { - if (!$global['mysqli']->query($templine)) { - $obj->error = ('Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

    '); - echo json_encode($obj); - //exit; - } - $templine = ''; - } - } - - // insert configuration if is version 1.0 - if ($config->currentVersionLowerThen('1.0')) { - $sql = "DELETE FROM configurations WHERE id = 1 "; - if ($global['mysqli']->query($sql) !== TRUE) { - $obj->error = "Error deleting configuration: " . $global['mysqli']->error; - echo json_encode($obj); - exit; - } - - $sql = "INSERT INTO configurations (id, video_resolution, users_id, version, created, modified) VALUES (1, '426:240', " . User::getId() . ",'1.0', now(), now())"; - if ($global['mysqli']->query($sql) !== TRUE) { - $obj->error = "Error creating configuration: " . $global['mysqli']->error; - echo json_encode($obj); - exit; - } - } - - if ($config->currentVersionEqual('1.0')) { - $sql = "UPDATE configurations SET users_id = " . User::getId() . ", version = '1.1', webSiteTitle = '{$global['webSiteTitle']}', language = '{$global['language']}', contactEmail = '{$global['contactEmail']}', modified = now() WHERE id = 1"; - if ($global['mysqli']->query($sql) !== TRUE) { - $obj->error = "Error creating configuration: " . $global['mysqli']->error; - echo json_encode($obj); - exit; - } - } - - //$renamed = rename("{$global['systemRootPath']}updateDb.sql", "{$global['systemRootPath']}updateDb.sql.old"); - ?> -
    -
    - -
    - -
    - -
    - - - - - + + + + + <?php echo __("Update AVideo System") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + +
    +
    +
    + +
    +
    + getVersion()); ?> +
    + +
    +
    +
    + + + + " . count($updateFiles) . ""); ?> +
    + +
    +
    +
    + + + +
    + Our repository is now running at version version; ?>. + You can follow this Update Tutorial + to update your files and get the latest version. +
    + +
    +

    +
    + error = ''; + foreach ($lines as $line) { + if (substr($line, 0, 2) == '--' || $line == '') { + continue; + } + $templine .= $line; + if (substr(trim($line), -1, 1) == ';') { + if (!$global['mysqli']->query($templine)) { + $obj->error = ('Error performing query \'' . $templine . '\': ' . $global['mysqli']->error . '

    '); + echo json_encode($obj); + //exit; + } + $templine = ''; + } + } + + // insert configuration if is version 1.0 + if ($config->currentVersionLowerThen('1.0')) { + $sql = "DELETE FROM configurations WHERE id = 1 "; + if ($global['mysqli']->query($sql) !== true) { + $obj->error = "Error deleting configuration: " . $global['mysqli']->error; + echo json_encode($obj); + exit; + } + + $sql = "INSERT INTO configurations (id, video_resolution, users_id, version, created, modified) VALUES (1, '426:240', " . User::getId() . ",'1.0', now(), now())"; + if ($global['mysqli']->query($sql) !== true) { + $obj->error = "Error creating configuration: " . $global['mysqli']->error; + echo json_encode($obj); + exit; + } + } + + if ($config->currentVersionEqual('1.0')) { + $sql = "UPDATE configurations SET users_id = " . User::getId() . ", version = '1.1', webSiteTitle = '{$global['webSiteTitle']}', language = '{$global['language']}', contactEmail = '{$global['contactEmail']}', modified = now() WHERE id = 1"; + if ($global['mysqli']->query($sql) !== true) { + $obj->error = "Error creating configuration: " . $global['mysqli']->error; + echo json_encode($obj); + exit; + } + } + + //$renamed = rename("{$global['systemRootPath']}updateDb.sql", "{$global['systemRootPath']}updateDb.sql.old");?> +
    +
    + +
    + +
    + +
    + + + + + diff --git a/view/url2Embed.json.php b/view/url2Embed.json.php index c2a2bb6be3..c0ad7bb1a6 100644 --- a/view/url2Embed.json.php +++ b/view/url2Embed.json.php @@ -1,40 +1,39 @@ -error = true; -$obj->msg = ""; -$obj->url = @$_REQUEST['url']; -$obj->embed = ""; -$obj->playLink = ""; -$obj->playEmbedLink = ""; - -if (!isValidURL($obj->url)) { - $obj->msg = "URL is invalid"; - die(json_encode($obj)); -} - -$obj->error = false; -$obj->embed = parseVideos($obj->url, 1); - - -$evideo = new stdClass(); -$evideo->videos_id = 0; -$evideo->videoLink = $obj->url; -$evideo->title = ""; -$evideo->description = ""; -$evideo->webSiteRootURL = $global['webSiteRootURL']; -$evideo->thumbnails = false; -$evideo->poster = false; -$evideo->filename = ""; -$evideo->type = 'embed'; -$evideo->users_id = User::getId(); -$evideo->thumbnails = false; - -$obj->playLink = "{$global['webSiteRootURL']}evideo/" . encryptString(json_encode($evideo)); -$obj->playEmbedLink = "{$global['webSiteRootURL']}evideoEmbed/" . encryptString(json_encode($evideo)); - -die(json_encode($obj)); +error = true; +$obj->msg = ''; +$obj->url = @$_REQUEST['url']; +$obj->embed = ''; +$obj->playLink = ''; +$obj->playEmbedLink = ''; + +if (!isValidURL($obj->url)) { + $obj->msg = "URL is invalid"; + die(json_encode($obj)); +} + +$obj->error = false; +$obj->embed = parseVideos($obj->url, 1); + + +$evideo = new stdClass(); +$evideo->videos_id = 0; +$evideo->videoLink = $obj->url; +$evideo->title = ''; +$evideo->description = ''; +$evideo->webSiteRootURL = $global['webSiteRootURL']; +$evideo->thumbnails = false; +$evideo->poster = false; +$evideo->filename = ''; +$evideo->type = 'embed'; +$evideo->users_id = User::getId(); +$evideo->thumbnails = false; + +$obj->playLink = "{$global['webSiteRootURL']}evideo/" . encryptString(json_encode($evideo)); +$obj->playEmbedLink = "{$global['webSiteRootURL']}evideoEmbed/" . encryptString(json_encode($evideo)); + +die(json_encode($obj)); diff --git a/view/user.php b/view/user.php index 04d05c7b86..df870f4fa1 100644 --- a/view/user.php +++ b/view/user.php @@ -1,98 +1,97 @@ -type} fix-width\">{$value->text}"; -} -//$json_file = url_get_contents("{$global['webSiteRootURL']}plugin/CustomizeAdvanced/advancedCustom.json.php"); -// convert the string to a json object -//$advancedCustom = _json_decode($json_file); -?> - - - - <?php echo __("My Account") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - - - - - - - - - - - -
    - loadSelfUser(); - if (!empty($_REQUEST['basicInfoOnly'])) { - include $global['systemRootPath'] . './view/userBasicInfo.php'; - } else { - ?> -
    -
    -
    -
    -
    - -
    - -
    -
    -
    -
    - -
    - - disablePersonalInfo)) { ?> -
    - -
    - - getId()); ?> -
    -
    -
    - -
    -
    - - - -
    - - - - +type} fix-width\">{$value->text}"; +} +//$json_file = url_get_contents("{$global['webSiteRootURL']}plugin/CustomizeAdvanced/advancedCustom.json.php"); +// convert the string to a json object +//$advancedCustom = _json_decode($json_file); +?> + + + + <?php echo __("My Account") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> + + + + + + + + + + + +
    + loadSelfUser(); + if (!empty($_REQUEST['basicInfoOnly'])) { + include $global['systemRootPath'] . './view/userBasicInfo.php'; + } else { + ?> +
    +
    +
    +
    +
    + +
    + +
    +
    +
    +
    + +
    + + disablePersonalInfo)) { ?> +
    + +
    + + getId()); ?> +
    +
    +
    + +
    +
    + + + +
    + + + + diff --git a/view/userBasicInfo.php b/view/userBasicInfo.php index 3381de70ed..248d89c09e 100644 --- a/view/userBasicInfo.php +++ b/view/userBasicInfo.php @@ -1,371 +1,371 @@ -
    - - -
    - -
    -
    - - " class="form-control" type="text" value="getName(); ?>" required > -
    -
    -
    - -
    - -
    -
    - - " class="form-control" type="forceLoginToBeTheEmail) ? "text" : "email" ?>" value="getUser(); ?>" required userCanChangeUsername)) ? "readonly" : ""; ?> > -
    -
    -
    - -
    - -
    -
    - - " class="form-control" type="email" value="getEmail(); ?>" required - forceLoginToBeTheEmail)) { - echo "readonly"; - } - ?> > -
    -
    -
    - getEmailVerified()) { - ?> - - - - - - -
    -
    - -
    - -
    - -
    -
    - -
    - -
    - -
    -
    - - - - - - - - - - -
    -
    -
    -

    -
    -
    -
    -
    -
    - -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
    -

    - -
    -
    -
    -
    - -
    -
    - -
    - : 2048px
    - : 1152px
    - : 2560px
    - : 1440px
    -
    -
    -
    -
    -
    -
    - - - -
    -
    -
    -
    - -
    -
    -
    - + + + +
    + +
    +
    + + " class="form-control" type="text" value="getName(); ?>" required > +
    +
    +
    + +
    + +
    +
    + + " class="form-control" type="forceLoginToBeTheEmail) ? "text" : "email" ?>" value="getUser(); ?>" required userCanChangeUsername)) ? "readonly" : ""; ?> > +
    +
    +
    + +
    + +
    +
    + + " class="form-control" type="email" value="getEmail(); ?>" required + forceLoginToBeTheEmail)) { + echo "readonly"; + } + ?> > +
    +
    +
    + getEmailVerified()) { + ?> + + + + + + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + + + + + + + + + + +
    +
    +
    +

    +
    +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +

    + +
    +
    +
    +
    + +
    +
    + +
    + : 2048px
    + : 1152px
    + : 2560px
    + : 1440px
    +
    +
    +
    +
    +
    +
    + + + +
    +
    +
    +
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/view/userGetPhoto.php b/view/userGetPhoto.php index 075c2ec2dd..384854a148 100644 --- a/view/userGetPhoto.php +++ b/view/userGetPhoto.php @@ -1,8 +1,7 @@ - -
    - - -
    -
    -

    -

    -
    - :
    - Mozilla Firefox
    - Google Chrome -
    -
    - - -
    - -
    - -
    -
    -

    - -

    -
    - userMustBeLoggedInCloseButtonURL)) { - ?> -
    - - - -
    - -
    -
    -
    - disableNativeSignIn)) { - ?> -
    - -
    - -
    -
    - - " class="form-control" type="text" value="" required > -
    -
    -
    - - -
    - -
    - -
    -
    - - -
    " id="captchaForm"> - -
    -
    -
    - -
    -
    -
    "> - - -
    -
    -
    - -
    -
    - -
    -
    -
    -
    - disableNativeSignUp)) { - ?> - "> - -
    -
    - -
    - -
    - -
    - - - 1) { - switch ($totalLogins) { - case 2: - case 4: - case 5: - case 7: - case 8: - case 10: - case 11: - $columSize = 6; - break; - case 3: - case 6: - case 9: - case 12: - $columSize = 4; - break; - } - } - $loginCount = 0; - foreach ($login as $value) { - if (is_string($value) && file_exists($value)) { - //include $value; - } else if (is_array($value)) { - $loginCount++; - $uid = uniqid(); - $oauthURL = "{$global['webSiteRootURL']}login?type={$value['parameters']->type}&redirectUri=" . (isset($_GET['redirectUri']) ? $_GET['redirectUri'] : ""); - ?> -
    - -
    - - - messageToAppearBelowLoginBox->value)) { - echo "
    "; - echo $advancedCustomUser->messageToAppearBelowLoginBox->value; - echo "
    "; - } - ?> -
    - -
    - + +
    + + +
    +
    +

    +

    +
    + :
    + Mozilla Firefox
    + Google Chrome +
    +
    + + +
    + +
    + +
    +
    +

    + +

    +
    + userMustBeLoggedInCloseButtonURL)) { + ?> +
    + + + +
    + +
    +
    +
    + disableNativeSignIn)) { + ?> +
    + +
    + +
    +
    + + " class="form-control" type="text" value="" required > +
    +
    +
    + + +
    + +
    + +
    +
    + + +
    " id="captchaForm"> + +
    +
    +
    + +
    +
    +
    "> + + +
    +
    +
    + +
    +
    + +
    +
    +
    +
    + disableNativeSignUp)) { + ?> + "> + +
    +
    + +
    + +
    + +
    + + + 1) { + switch ($totalLogins) { + case 2: + case 4: + case 5: + case 7: + case 8: + case 10: + case 11: + $columSize = 6; + break; + case 3: + case 6: + case 9: + case 12: + $columSize = 4; + break; + } + } + $loginCount = 0; + foreach ($login as $value) { + if (is_string($value) && file_exists($value)) { + //include $value; + } elseif (is_array($value)) { + $loginCount++; + $uid = uniqid(); + $oauthURL = "{$global['webSiteRootURL']}login?type={$value['parameters']->type}&redirectUri=" . ($_GET['redirectUri'] ?? ""); ?> +
    + +
    + + + messageToAppearBelowLoginBox->value)) { + echo "
    "; + echo $advancedCustomUser->messageToAppearBelowLoginBox->value; + echo "
    "; + } + ?> +
    + +
    + diff --git a/view/userPersonalInfo.php b/view/userPersonalInfo.php index 7d1338d5ae..0499c921e3 100644 --- a/view/userPersonalInfo.php +++ b/view/userPersonalInfo.php @@ -1,251 +1,251 @@ -
    - disablePersonalInfo)) { - return false; - } - require_once $global['systemRootPath'] . 'plugin/User_Location/Objects/IP2Location.php'; - $text = "-- " . __('Select one Option') . " --"; - $myCountry = $user->getCountry(); - $myRegion = $user->getRegion(); - $myCity = $user->getCity(); - ?> -
    - -
    -
    - - " class="form-control" type="text" value="getFirst_name(); ?>" > -
    -
    -
    - -
    - -
    -
    - - " class="form-control" type="text" value="getLast_name(); ?>" > -
    -
    -
    - -
    - -
    -
    - - " class="form-control" type="text" value="getAddress(); ?>" > -
    -
    -
    - -
    - -
    -
    - - " class="form-control" type="text" value="getZip_code(); ?>" > -
    -
    -
    - - -
    - -
    - -
    - - -
    - -
    -
    - - -
    - -
    - -
    - - -
    - -
    -
    - -
    - -
    - -
    - - -
    - -
    -
    - -
    -
    -
    -
    - -
    -
    - -
    - - -
    -
    -
    -
    - -
    -
    -
    - + + disablePersonalInfo)) { + return false; + } + require_once $global['systemRootPath'] . 'plugin/User_Location/Objects/IP2Location.php'; + $text = "-- " . __('Select one Option') . " --"; + $myCountry = $user->getCountry(); + $myRegion = $user->getRegion(); + $myCity = $user->getCity(); + ?> +
    + +
    +
    + + " class="form-control" type="text" value="getFirst_name(); ?>" > +
    +
    +
    + +
    + +
    +
    + + " class="form-control" type="text" value="getLast_name(); ?>" > +
    +
    +
    + +
    + +
    +
    + + " class="form-control" type="text" value="getAddress(); ?>" > +
    +
    +
    + +
    + +
    +
    + + " class="form-control" type="text" value="getZip_code(); ?>" > +
    +
    +
    + + +
    + +
    + +
    + + +
    + +
    +
    + + +
    + +
    + +
    + + +
    + +
    +
    + +
    + +
    + +
    + + +
    + +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    + + +
    +
    +
    +
    + +
    +
    +
    +
    \ No newline at end of file diff --git a/view/videoComments.php b/view/videoComments.php index 81bf108cf2..c98a6354ca 100644 --- a/view/videoComments.php +++ b/view/videoComments.php @@ -1,386 +1,383 @@ -commentsNoIndex)) { - echo ""; - } - if (!empty($video['id'])) { - ?> -
    - - - > - - "> - - "> - -
    -
    - - - - -

    :

    - - - - - - - - - -
    - - - - - commentsNoIndex)) { - echo ""; - } -} -?> +commentsNoIndex)) { + echo ""; + } + if (!empty($video['id'])) { + ?> +
    + + + > + + "> + + "> + +
    +
    + + + + +

    :

    + + + + + + + + + +
    + + + + + commentsNoIndex)) { + echo ""; + } +} +?> diff --git a/view/videoCreator.html b/view/videoCreator.html index 2aca749671..e5d47da559 100644 --- a/view/videoCreator.html +++ b/view/videoCreator.html @@ -1,14 +1,14 @@ -
    - - {name} Photo - -
    - - {name} - {icon} - - {subscriptionButton} -
    -
    +
    + + {name} Photo + +
    + + {name} + {icon} + + {subscriptionButton} +
    +
    {html} \ No newline at end of file diff --git a/view/videoCreatorSmall.html b/view/videoCreatorSmall.html index 3c43fb82b4..b64dae35f1 100644 --- a/view/videoCreatorSmall.html +++ b/view/videoCreatorSmall.html @@ -1,9 +1,9 @@ -
    - - {name} Photo - {name} - {icon} - - {html} + \ No newline at end of file diff --git a/view/videoEmbeded.php b/view/videoEmbeded.php index adb55541fc..824509669b 100644 --- a/view/videoEmbeded.php +++ b/view/videoEmbeded.php @@ -1,582 +1,561 @@ -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 ($video['status']=='i') { - forbiddenPage("Video inactive"); -} -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"; -$showOnlyBasicControls = false; -$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'])) { - if ($_GET['controls'] == "0") { - $controls = ""; - } else if ($_GET['controls'] == "-1") { - $showOnlyBasicControls = true; - } else if ($_GET['controls'] == "-2") { - $showOnlyBasicControls = true; - $hideProgressBarAndUnPause = true; - } -} -if (!empty($_GET['loop'])) { - $loop = "loop"; -} -if (!empty($_GET['mute'])) { - $mute = 'muted="muted"'; -} -if (!empty($_GET['objectFit']) && (intval($_GET['objectFit']) == 1 || $_GET['objectFit'] == 'true')) { - $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%;" > -
    - - - -
    -
    -
    -
      - open($sources['zip']["path"]); - for ($i = 0; $i < $za->numFiles; $i++) { - $stat = $za->statIndex($i); - $fname = basename($stat['name']); - ?> -
    • - -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +thumbnails; + $poster = $evideo->thumbnails; + $imgw = 1280; + $imgh = 720; + $autoPlaySources = []; + $autoPlayURL = ''; + $autoPlayPoster = ''; + $autoPlayThumbsSprit = ''; +} elseif (!empty($_GET['v'])) { + $video = Video::getVideo($_GET['v'], "", true, false, false, true); +//$video['id'] = $_GET['v']; +} elseif (!empty($_GET['videoName'])) { + $video = Video::getVideoFromCleanTitle($_GET['videoName']); +} + +Video::unsetAddView($video['id']); + +AVideoPlugin::getEmbed($video['id']); + +if (empty($video)) { + forbiddenPage("Video not found"); +} +if ($video['status']=='i') { + forbiddenPage("Video inactive"); +} +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 = []; +$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 = []; + $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"; +$showOnlyBasicControls = false; +$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'])) { + if ($_GET['controls'] == "0") { + $controls = ''; + } elseif ($_GET['controls'] == "-1") { + $showOnlyBasicControls = true; + } elseif ($_GET['controls'] == "-2") { + $showOnlyBasicControls = true; + $hideProgressBarAndUnPause = true; + } +} +if (!empty($_GET['loop'])) { + $loop = "loop"; +} +if (!empty($_GET['mute'])) { + $mute = 'muted="muted"'; +} +if (!empty($_GET['objectFit']) && (intval($_GET['objectFit']) == 1 || $_GET['objectFit'] == 'true')) { + $objectFit = 'object-fit: ' . $_GET['objectFit']; +} +if (!empty($_GET['t'])) { + $t = intval($_GET['t']); +} elseif (!empty($video['progress']['lastVideoTime'])) { + $t = intval($video['progress']['lastVideoTime']); +} elseif (!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%;" > +
    + + + +
    +
    +
    +
      + open($sources['zip']["path"]); + for ($i = 0; $i < $za->numFiles; $i++) { + $stat = $za->statIndex($i); + $fname = basename($stat['name']); ?> +
    • + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/view/videoNotFound.php b/view/videoNotFound.php index 01f5052c09..1b0f9f45e4 100644 --- a/view/videoNotFound.php +++ b/view/videoNotFound.php @@ -1,59 +1,59 @@ - - - - - <?php echo __('Video Not Found'); ?> - - - - - -
    - -
    - - - - + + + + + <?php echo __('Video Not Found'); ?> + + + + + +
    + +
    + + + + diff --git a/view/videoViewsInfo.csv.php b/view/videoViewsInfo.csv.php index d863cf57a3..865fc39d59 100644 --- a/view/videoViewsInfo.csv.php +++ b/view/videoViewsInfo.csv.php @@ -1,40 +1,39 @@ -videos_id); -} else { - $videos_id = intval(@$_REQUEST['videos_id']); - if (!Video::canEdit($videos_id)) { - forbiddenPage("You cannot see this info"); - } -} -if (empty($videos_id)) { - forbiddenPage("Videos ID is required"); -} - -$rowsCount = getRowCount(); -$video = new Video('', '', $videos_id); -$year = intval(@$_REQUEST['created_year']); -$month = intval(@$_REQUEST['created_month']); -$filename = "{$year}{$month}_{$videos_id}_".$video->getClean_title(); -$rows = VideoStatistic::getAllFromVideos_id($videos_id); -//var_dump($rows);exit; -$output = fopen("php://output", 'w') or die("Can't open php://output"); -$fields = array('when', 'ip', 'users', 'location_name', 'seconds_watching_video'); -fputcsv($output, $fields); -foreach ($rows as $row) { - $statistic = array(); - foreach ($fields as $value) { - $statistic[$value] = $row[$value]; - } - //var_dump($statistic);exit; - fputcsv($output, $statistic); -} -header("Content-Type:application/csv"); -header("Content-Disposition:attachment;filename={$filename}.csv"); -fclose($output) or die("Can't close php://output"); -?> \ No newline at end of file +videos_id); +} else { + $videos_id = intval(@$_REQUEST['videos_id']); + if (!Video::canEdit($videos_id)) { + forbiddenPage("You cannot see this info"); + } +} +if (empty($videos_id)) { + forbiddenPage("Videos ID is required"); +} + +$rowsCount = getRowCount(); +$video = new Video('', '', $videos_id); +$year = intval(@$_REQUEST['created_year']); +$month = intval(@$_REQUEST['created_month']); +$filename = "{$year}{$month}_{$videos_id}_".$video->getClean_title(); +$rows = VideoStatistic::getAllFromVideos_id($videos_id); +//var_dump($rows);exit; +$output = fopen("php://output", 'w') or die("Can't open php://output"); +$fields = ['when', 'ip', 'users', 'location_name', 'seconds_watching_video']; +fputcsv($output, $fields); +foreach ($rows as $row) { + $statistic = []; + foreach ($fields as $value) { + $statistic[$value] = $row[$value]; + } + //var_dump($statistic);exit; + fputcsv($output, $statistic); +} +header("Content-Type:application/csv"); +header("Content-Disposition:attachment;filename={$filename}.csv"); +fclose($output) or die("Can't close php://output"); diff --git a/view/videoViewsInfo.json.php b/view/videoViewsInfo.json.php index 373ddd09f7..c89df7c087 100644 --- a/view/videoViewsInfo.json.php +++ b/view/videoViewsInfo.json.php @@ -1,26 +1,26 @@ -videos_id); -} else { - $videos_id = intval(@$_REQUEST['videos_id']); - if (!Video::canEdit($videos_id)) { - forbiddenPage("You cannot see this info"); - } -} -if (empty($videos_id)) { - forbiddenPage("Videos ID is required"); -} - -$rowsCount = getRowCount(); - -$rows = VideoStatistic::getAllFromVideos_id($videos_id); -$total = VideoStatistic::getTotalFromVideos_id($videos_id); -$totalPages = ceil($total / $rowsCount); - -?> +videos_id); +} else { + $videos_id = intval(@$_REQUEST['videos_id']); + if (!Video::canEdit($videos_id)) { + forbiddenPage("You cannot see this info"); + } +} +if (empty($videos_id)) { + forbiddenPage("Videos ID is required"); +} + +$rowsCount = getRowCount(); + +$rows = VideoStatistic::getAllFromVideos_id($videos_id); +$total = VideoStatistic::getTotalFromVideos_id($videos_id); +$totalPages = ceil($total / $rowsCount); + +?> {"data": , "draw": , "recordsTotal":, "recordsFiltered":} \ No newline at end of file diff --git a/view/videoViewsInfo.php b/view/videoViewsInfo.php index d2a4ff6063..3560ac4991 100644 --- a/view/videoViewsInfo.php +++ b/view/videoViewsInfo.php @@ -1,180 +1,180 @@ -videos_id); -} else { - $videos_id = intval(@$_REQUEST['videos_id']); - if (!Video::canEdit($videos_id)) { - forbiddenPage("You cannot see this info"); - } -} -if (empty($videos_id)) { - forbiddenPage("Videos ID is required"); -} -$v = new Video('', '', $videos_id); -//var_dump($total);exit; -?> - - - - Videos View info - - - - - - - -
    -
    -
    -
    - getTitle(); - $obj = new stdClass(); - $obj->videos_id = $videos_id; - $hash = encryptString($obj); - ?> -
    - - -
    -
    -
    -
    -
    - - -
    -
    - - -
    - - -
    -
    -

    - getViews_count()); - ?> - Views and watched - getTotal_seconds_watching()); - ?> -

    - - - - - - - - - - - - - - - - - - -
    UserWhenTimeLocation
    UserWhenTimeLocation
    - -
    -
    -
    - - - - - +videos_id); +} else { + $videos_id = intval(@$_REQUEST['videos_id']); + if (!Video::canEdit($videos_id)) { + forbiddenPage("You cannot see this info"); + } +} +if (empty($videos_id)) { + forbiddenPage("Videos ID is required"); +} +$v = new Video('', '', $videos_id); +//var_dump($total);exit; +?> + + + + Videos View info + + + + + + + +
    +
    +
    +
    + getTitle(); + $obj = new stdClass(); + $obj->videos_id = $videos_id; + $hash = encryptString($obj); + ?> +
    + + +
    +
    +
    +
    +
    + + +
    +
    + + +
    + + +
    +
    +

    + getViews_count()); + ?> + Views and watched + getTotal_seconds_watching()); + ?> +

    + + + + + + + + + + + + + + + + + + +
    UserWhenTimeLocation
    UserWhenTimeLocation
    + +
    +
    +
    + + + + + diff --git a/view/videosList.php b/view/videosList.php index 1c4d1d63b7..6cf114eb16 100644 --- a/view/videosList.php +++ b/view/videosList.php @@ -1,261 +1,261 @@ - 100) { - $_REQUEST['rowCount'] = 10; -} - -if (empty($_POST['sort'])) { - if (!empty($_SESSION['sort'])) { - $_POST['sort'] = $_SESSION['sort']; - } else { - $_POST['sort']['created'] = 'desc'; - } -} -$_SESSION['rowCount'] = $_REQUEST['rowCount']; -$_SESSION['sort'] = $_POST['sort']; - - -TimeLogEnd($timeLogNameVL, __LINE__, $TimeLogLimitVL); -$videos = Video::getAllVideos("viewableNotUnlisted"); -$total = Video::getTotalVideos("viewableNotUnlisted"); -TimeLogEnd($timeLogNameVL, __LINE__, $TimeLogLimitVL); -$totalPages = ceil($total / $_REQUEST['rowCount']); -$_POST = $post; -if (empty($totalPages)) { - $totalPages = 1; -} -$videoName = ""; -if (!empty($video['clean_title'])) { - $videoName = $video['clean_title']; -} else if (!empty($_GET['videoName'])) { - $videoName = $_GET['videoName']; -} -$get = array(); - -$get = array('channelName' => @$_GET['channelName'], 'catName' => @$_GET['catName']); -if (!empty($_GET['channelName']) && empty($advancedCustomUser->hideRemoveChannelFromModeYoutube)) { - $user = User::getChannelOwner($_GET['channelName']); - //var_dump($user);exit; - ?> -
    - User Photo -
    - -
    -
    - -
    - -
    -
    - -
    - - $value) { - if (!empty($video['id']) && $video['id'] == $value['id']) { - continue; // skip video - } - $getVideosListItem .= Video::getVideosListItem($value['id']); - } - ObjectYPT::setSessionCache($cacheName, $getVideosListItem); -} -echo $getVideosListItem; -TimeLogEnd($timeLogNameVL, __LINE__, $TimeLogLimitVL); -?> -
      -
    - - - 100) { + $_REQUEST['rowCount'] = 10; +} + +if (empty($_POST['sort'])) { + if (!empty($_SESSION['sort'])) { + $_POST['sort'] = $_SESSION['sort']; + } else { + $_POST['sort']['created'] = 'desc'; + } +} +$_SESSION['rowCount'] = $_REQUEST['rowCount']; +$_SESSION['sort'] = $_POST['sort']; + + +TimeLogEnd($timeLogNameVL, __LINE__, $TimeLogLimitVL); +$videos = Video::getAllVideos("viewableNotUnlisted"); +$total = Video::getTotalVideos("viewableNotUnlisted"); +TimeLogEnd($timeLogNameVL, __LINE__, $TimeLogLimitVL); +$totalPages = ceil($total / $_REQUEST['rowCount']); +$_POST = $post; +if (empty($totalPages)) { + $totalPages = 1; +} +$videoName = ''; +if (!empty($video['clean_title'])) { + $videoName = $video['clean_title']; +} elseif (!empty($_GET['videoName'])) { + $videoName = $_GET['videoName']; +} +$get = []; + +$get = ['channelName' => @$_GET['channelName'], 'catName' => @$_GET['catName']]; +if (!empty($_GET['channelName']) && empty($advancedCustomUser->hideRemoveChannelFromModeYoutube)) { + $user = User::getChannelOwner($_GET['channelName']); + //var_dump($user);exit;?> +
    + User Photo +
    + +
    +
    + +
    + +
    +
    + +
    + + $value) { + if (!empty($video['id']) && $video['id'] == $value['id']) { + continue; // skip video + } + $getVideosListItem .= Video::getVideosListItem($value['id']); + } + ObjectYPT::setSessionCache($cacheName, $getVideosListItem); +} +echo $getVideosListItem; +TimeLogEnd($timeLogNameVL, __LINE__, $TimeLogLimitVL); +?> +
      +
    + + + \ No newline at end of file diff --git a/view/xsendfile.php b/view/xsendfile.php index 732712be67..fd37a31101 100644 --- a/view/xsendfile.php +++ b/view/xsendfile.php @@ -38,7 +38,7 @@ if ($file == "configuration.php") { $path = Video::getPathToFile($file); if (file_exists($path)) { if (!empty($_GET['download'])) { - if(!CustomizeUser::canDownloadVideos()){ + if (!CustomizeUser::canDownloadVideos()) { _error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO"); forbiddenPage("Can't download this"); } @@ -62,7 +62,7 @@ if (file_exists($path)) { if (empty($advancedCustom->doNotUseXsendFile)) { //_error_log("X-Sendfile: {$path}"); header("X-Sendfile: {$path}"); - }else{ + } else { _error_log("Careful, we recommend 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 {