1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-05 19:42:38 +02:00

Refactor some plugins code.

This commit is contained in:
Caleb Mazalevskis 2022-01-06 19:43:51 +08:00
parent ab8fd13a56
commit 43c00721ca
No known key found for this signature in database
GPG key ID: 082E6BC1046FAB95
223 changed files with 12595 additions and 11447 deletions

View file

@ -1,5 +1,4 @@
<?php
/**
* https://support.google.com/adsense/answer/4455881
* https://support.google.com/adsense/answer/1705822
@ -10,34 +9,40 @@ global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
class AD_Server extends PluginAbstract {
public function getTags() {
return array(
class AD_Server extends PluginAbstract
{
public function getTags()
{
return [
PluginTags::$MONETIZATION,
PluginTags::$ADS,
PluginTags::$FREE,
PluginTags::$PLAYER,
);
];
}
public function getDescription() {
public function getDescription()
{
return "VAST Ad Server<br><small><a href='https://github.com/WWBN/AVideo/wiki/Ad-Server-Plugin' target='__blank'><i class='fas fa-question-circle'></i> Help</a></small>";
}
public function getName() {
public function getName()
{
return "AD_Server";
}
public function getUUID() {
public function getUUID()
{
return "3f2a707f-3c06-4b78-90f9-a22f2fda92ef";
}
public function getPluginVersion() {
public function getPluginVersion()
{
return "1.0";
}
public function getEmptyDataObject() {
public function getEmptyDataObject()
{
$obj = new stdClass();
$obj->start = true;
self::addDataObjectHelper('start', 'Show Pre-Roll ads');
@ -51,7 +56,7 @@ class AD_Server extends PluginAbstract {
self::addDataObjectHelper('end', 'Show Post-Roll ads');
$o = new stdClass();
$o->type = array();
$o->type = [];
for ($i = 0; $i <= 100; $i++) {
$o->type[$i . '%'] = "The skip button will appear when you watch {$i}% of the video";
}
@ -63,7 +68,7 @@ class AD_Server extends PluginAbstract {
self::addDataObjectHelper('showMarkers', 'Show Markers', 'Check it if you want to show the yellow markers on the video, where the advertising should appear');
$o = new stdClass();
$o->type = array(1 => 'Every video');
$o->type = [1 => 'Every video'];
for ($i = 2; $i < 10; $i++) {
$o->type[$i] = "Show ads on each {$i} videos";
}
@ -72,7 +77,7 @@ class AD_Server extends PluginAbstract {
self::addDataObjectHelper('showAdsOnEachVideoView', 'Show Ads on', 'This defines how often advertisements will appear, for example: if it is set to 2, you will see ads each 2 videos, but if it is set to 1 you will see ads on every video');
$o = new stdClass();
$o->type = array(0 => 'All positions');
$o->type = [0 => 'All positions'];
for ($i = 1; $i < 5; $i++) {
$o->type[$i] = "Show ads on {$i} random positions";
}
@ -83,9 +88,9 @@ class AD_Server extends PluginAbstract {
$o = new stdClass();
$o->type = array(0 => 'Do not auto add new videos on campaign');
$o->type = [0 => 'Do not auto add new videos on campaign'];
$rows = VastCampaigns::getAllActive();
if(!is_array($rows)){
if (!is_array($rows)) {
$o->value = 0;
$obj->autoAddNewVideosInCampaignId = $o;
return $obj;
@ -100,7 +105,8 @@ class AD_Server extends PluginAbstract {
return $obj;
}
public function afterNewVideo($videos_id) {
public function afterNewVideo($videos_id)
{
_error_log("AD_Server:afterNewVideo start");
$obj = $this->getDataObject();
if (!empty($obj->autoAddNewVideosInCampaignId)) {
@ -129,7 +135,8 @@ class AD_Server extends PluginAbstract {
return true;
}
public function canLoadAds() {
public function canLoadAds()
{
//if (empty($_GET['videoName']) && empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
@ -161,7 +168,8 @@ class AD_Server extends PluginAbstract {
return false;
}
public function getHeadCode() {
public function getHeadCode()
{
$obj = $this->getDataObject();
if (!$this->canLoadAds()) {
return "";
@ -179,7 +187,8 @@ class AD_Server extends PluginAbstract {
return $css;
}
private static function getVideoLength() {
private static function getVideoLength()
{
$video_length = 3600; // 1 hour
$videos_id = getVideos_id();
$video = new Video('', '', $videos_id);
@ -190,7 +199,8 @@ class AD_Server extends PluginAbstract {
return $video_length;
}
static function getVMAPSFromRequest() {
public static function getVMAPSFromRequest()
{
if (!empty($_REQUEST['vmaps'])) {
$vmaps = _json_decode(base64_decode($_REQUEST['vmaps']));
} else {
@ -201,7 +211,8 @@ class AD_Server extends PluginAbstract {
return object_to_array($vmaps);
}
static function addVMAPS($url, $vmaps) {
public static function addVMAPS($url, $vmaps)
{
if (empty($vmaps)) {
$vmaps = self::getVMAPSFromRequest();
}
@ -210,8 +221,8 @@ class AD_Server extends PluginAbstract {
return $vmapURL;
}
public function afterVideoJS() {
public function afterVideoJS()
{
$obj = $this->getDataObject();
if (!$this->canLoadAds() || empty($_GET['vmap_id'])) {
return "";
@ -246,10 +257,10 @@ class AD_Server extends PluginAbstract {
foreach ($vmaps as $value) {
$vastCampaingVideos = new VastCampaignsVideos($value['VAST']['campaing']);
$video = new Video("", "", $vastCampaingVideos->getVideos_id());
if(!empty($video_length) && $value['timeOffsetSeconds'] >= $video_length){
if (!empty($video_length) && $value['timeOffsetSeconds'] >= $video_length) {
$value['timeOffsetSeconds'] = $video_length-5;
}
$onPlayerReady .= "{time: {$value['timeOffsetSeconds']}, text: \"" . addcslashes($video->getTitle(), '"') . "\"},";
}
$onPlayerReady .= "]});";
@ -268,8 +279,8 @@ class AD_Server extends PluginAbstract {
return $js;
}
private function getRandomPositions() {
private function getRandomPositions()
{
if (empty($_GET['vmap_id'])) {
return "";
}
@ -282,7 +293,7 @@ class AD_Server extends PluginAbstract {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$options = array();
$options = [];
if (!empty($obj->start)) {
$options[] = 1;
@ -300,7 +311,7 @@ class AD_Server extends PluginAbstract {
$options[] = 5;
}
$selectedOptions = array();
$selectedOptions = [];
if (empty($_SESSION['lastAdRandomPositions']) || $_SESSION['lastAdRandomPositions'] + 20 <= time()) {
$_SESSION['lastAdRandomPositions'] = time();
@ -327,8 +338,9 @@ class AD_Server extends PluginAbstract {
return $adRandomPositions;
}
public function getVMAPs($video_length) {
$vmaps = array();
public function getVMAPs($video_length)
{
$vmaps = [];
$obj = $this->getDataObject();
@ -356,7 +368,8 @@ class AD_Server extends PluginAbstract {
return $vmaps;
}
public function VMAPsHasVideos() {
public function VMAPsHasVideos()
{
$vmaps = $this->getVMAPs(100);
//var_dump($vmaps);exit;
foreach ($vmaps as $value) {
@ -367,61 +380,67 @@ class AD_Server extends PluginAbstract {
return true;
}
public function showAdsNow() {
public function showAdsNow()
{
if (!$this->VMAPsHasVideos()) {
return false;
}
}
static public function getVideos() {
public static function getVideos()
{
$campaings = VastCampaigns::getValidCampaigns();
//var_dump($campaings);
$videos = array();
$videos = [];
foreach ($campaings as $key => $value) {
$v = VastCampaignsVideos::getValidVideos($value['id']);
$videos = array_merge($videos, $v);
$campaings[$key]['videos'] = $v;
}
return array('campaigns' => $campaings, 'videos' => $videos);
return ['campaigns' => $campaings, 'videos' => $videos];
}
static public function getRandomVideo() {
public static function getRandomVideo()
{
$result = static::getVideos();
$videos = $result['videos'];
shuffle($videos);
return array_pop($videos);
}
static public function getRandomCampaign() {
public static function getRandomCampaign()
{
$result = static::getVideos();
$campaing = $result['campaigns'];
shuffle($campaing);
return array_pop($campaing);
}
public function getPluginMenu() {
public function getPluginMenu()
{
global $global;
$filename = $global['systemRootPath'] . 'plugin/AD_Server/pluginMenu.html';
return file_get_contents($filename);
}
public function getValidCampaignsFromVideo($videos_id) {
public function getValidCampaignsFromVideo($videos_id)
{
return VastCampaigns::getValidCampaignsFromVideo($videos_id);
}
}
class VMAP {
class VMAP
{
public $timeOffset;
public $timeOffsetSeconds;
public $VAST;
public $idTag = "preroll-ad";
function __construct($time, VAST $VAST, $video_length = 0) {
public function __construct($time, VAST $VAST, $video_length = 0)
{
if ($time === 'start') {
$this->timeOffsetSeconds = 0;
} else if ($time === 'end') {
} elseif ($time === 'end') {
$this->timeOffsetSeconds = $video_length;
} else {
$this->timeOffsetSeconds = $time;
@ -430,16 +449,17 @@ class VMAP {
$this->setTimeOffset($time);
}
function setTimeOffset($time) {
public function setTimeOffset($time)
{
if (empty($time)) {
//$time = "start";
}
// if is longer then the video length will be END
if (empty($time) || $time == "start") {
$this->idTag = "preroll-ad-" . $this->VAST->id;
} else if ($time == "end") {
} elseif ($time == "end") {
$this->idTag = "postroll-ad-" . $this->VAST->id;
} else if (is_numeric($time)) {
} elseif (is_numeric($time)) {
$time = $this->format($time);
$this->idTag = "midroll-" . $this->VAST->id;
}
@ -447,21 +467,22 @@ class VMAP {
$this->timeOffset = $time;
}
private function format($seconds) {
private function format($seconds)
{
$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);
return sprintf('%02d:%02d:%02d.000', $hours, $mins, $secs);
}
}
class VAST {
class VAST
{
public $id;
public $campaing;
function __construct($id) {
public function __construct($id)
{
$this->id = $id;
$row = AD_Server::getRandomVideo();
if (!empty($row)) {
@ -470,5 +491,4 @@ class VAST {
$this->campaing = false;
}
}
}

View file

@ -1,312 +1,373 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php';
class VastCampaigns extends ObjectYPT {
protected $id, $name, $type, $status, $start_date, $end_date, $pricing_model,
$price, $max_impressions, $max_clicks, $priority, $users_id, $visibility, $cpc_budget_type, $cpc_total_budget, $cpc_max_price_per_click, $cpm_max_prints, $cpm_current_prints;
static function getSearchFieldsNames() {
return array('name');
}
static function getTableName() {
return 'vast_campaigns';
}
function getName() {
return $this->name;
}
function getType() {
return $this->type;
}
function getStatus() {
return $this->status;
}
function getStart_date() {
return $this->start_date;
}
function getEnd_date() {
return $this->end_date;
}
function getPricing_model() {
return $this->pricing_model;
}
function getPrice() {
return $this->price;
}
function getMax_impressions() {
return $this->max_impressions;
}
function getMax_clicks() {
return $this->max_clicks;
}
function getPriority() {
return $this->priority;
}
function getUsers_id() {
return $this->users_id;
}
function getVisibility() {
return $this->visibility;
}
function getCpc_budget_type() {
return $this->cpc_budget_type;
}
function getCpc_total_budget() {
return $this->cpc_total_budget;
}
function getCpc_max_price_per_click() {
return $this->cpc_max_price_per_click;
}
function getCpm_max_prints() {
return $this->cpm_max_prints;
}
function getCpm_current_prints() {
return $this->cpm_current_prints;
}
function getPrintsLeft() {
return ($this->cpm_max_prints-$this->cpm_current_prints);
}
function setName($name) {
$this->name = $name;
}
function setType($type) {
$this->type = $type;
}
function setStatus($status) {
$this->status = $status;
}
function setStart_date($start_date) {
$this->start_date = $start_date;
}
function setEnd_date($end_date) {
$this->end_date = $end_date;
}
function setPricing_model($pricing_model) {
$this->pricing_model = $pricing_model;
}
function setPrice($price) {
$this->price = $price;
}
function setMax_impressions($max_impressions) {
$this->max_impressions = $max_impressions;
}
function setMax_clicks($max_clicks) {
$this->max_clicks = $max_clicks;
}
function setPriority($priority) {
$this->priority = $priority;
}
function setUsers_id($users_id) {
$this->users_id = $users_id;
}
function setVisibility($visibility) {
$this->visibility = $visibility;
}
function setCpc_budget_type($cpc_budget_type) {
$this->cpc_budget_type = $cpc_budget_type;
}
function setCpc_total_budget($cpc_total_budget) {
$this->cpc_total_budget = $cpc_total_budget;
}
function setCpc_max_price_per_click($cpc_max_price_per_click) {
$this->cpc_max_price_per_click = $cpc_max_price_per_click;
}
function setCpm_max_prints($cpm_max_prints) {
$this->cpm_max_prints = $cpm_max_prints;
}
function setCpm_current_prints($cpm_current_prints) {
$this->cpm_current_prints = $cpm_current_prints;
}
function getId() {
return $this->id;
}
function setId($id) {
$this->id = $id;
}
function save() {
$this->cpm_current_prints = intval($this->cpm_current_prints);
if (empty($this->visibility)) {
$this->visibility = 'listed';
}
if (empty($this->cpc_budget_type)) {
$this->cpc_budget_type = 'Campaign Total';
}
if (empty($this->cpc_total_budget)) {
$this->cpc_total_budget = 0;
}
if (empty($this->cpc_max_price_per_click)) {
$this->cpc_max_price_per_click = 0;
}
if (empty($this->visibility)) {
$this->visibility = 'listed';
}
return parent::save();
}
function addVideo($videos_id, $status = 'a') {
$vast_campaigns_id = $this->getId();
if (empty($vast_campaigns_id)) {
$this->setId($this->save());
$vast_campaigns_id = $this->getId();
}
$campainVideos = new VastCampaignsVideos(0);
$campainVideos->loadFromCampainVideo($vast_campaigns_id, $videos_id);
$campainVideos->setStatus($status);
return $campainVideos->save();
}
static public function getValidCampaigns() {
global $global;
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
AVideoPlugin::loadPlugin('User_Location');
$User_Location = User_Location::getSessionLocation();
$sql = "SELECT * from " . static::getTableName() . " vc WHERE status = 'a' AND start_date <= now() AND end_date >=now() AND cpm_max_prints > cpm_current_prints ";
if(!empty($ad_server_location) && !empty($User_Location) && $User_Location['country_name'] !== '-'){
// show only campaign for the user location
$sql .= " AND ( (vc.id IN (SELECT vast_campaigns_id FROM campaign_locations WHERE (country_name = 'All' OR country_name IS NULL OR country_name = '') OR "
. " (country_name = \"{$User_Location['country_name']}\" AND region_name = 'All') OR "
. " (country_name = \"{$User_Location['country_name']}\" AND region_name = \"{$User_Location['region_name']}\" AND city_name = 'All') OR"
. " (country_name = \"{$User_Location['country_name']}\" AND region_name = \"{$User_Location['region_name']}\" AND city_name = \"{$User_Location['city_name']}\") ) ) "
. " OR vc.id NOT IN(SELECT vast_campaigns_id FROM campaign_locations) )";
}
$sql .= " ORDER BY priority ";
//echo $sql;
//_error_log($sql);
$res = sqlDAL::readSql($sql);
$rows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = array();
if ($res != false) {
foreach ($rows as $row) {
$row['printsLeft'] = $row['cpm_max_prints'] - $row['cpm_current_prints'];
$r[] = $row;
}
}
return $r;
}
static function getAll() {
global $global;
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
$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) {
$row['data'] = VastCampaignsLogs::getDataFromCampaign($row['id']);
$row['printsLeft'] = $row['cpm_max_prints'] - $row['cpm_current_prints'];
if (!empty($ad_server_location)) {
$row['locations'] = $ad_server_location->getCampaignLocations($row['id']);
}
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
function addView() {
global $global;
if (!empty($this->id)) {
$sql = "UPDATE " . static::getTableName() . " SET cpm_current_prints = cpm_current_prints+1 ";
$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 add view");
return false;
}
function delete() {
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM vast_campaigns_logs ";
$sql .= " WHERE vast_campaigns_has_videos_id IN (SELECT id FROM vast_campaigns_has_videos WHERE vast_campaigns_id = ?)";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
$campaigns_video_log = sqlDAL::writeSql($sql, "i", array($this->id));
$sql = "DELETE FROM vast_campaigns_has_videos ";
$sql .= " WHERE vast_campaigns_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
$campaigns_video = sqlDAL::writeSql($sql, "i", array($this->id));
}
return parent::delete();
}
static public function getValidCampaignsFromVideo($videos_id) {
global $global;
$sql = "SELECT vchv.*, vc.* from " . static::getTableName() . " vc LEFT JOIN vast_campaigns_has_videos vchv ON vchv.vast_campaigns_id = vc.id WHERE vc.status = 'a' "
. " AND start_date <= now() AND end_date >=now() AND cpm_max_prints > cpm_current_prints AND videos_id = {$videos_id}";
//echo $sql;
$res = sqlDAL::readSql($sql);
$rows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = array();
if ($res != false) {
foreach ($rows as $row) {
$row['printsLeft'] = $row['cpm_max_prints'] - $row['cpm_current_prints'];
$r[] = $row;
}
}
return $r;
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php';
class VastCampaigns extends ObjectYPT
{
protected $id;
protected $name;
protected $type;
protected $status;
protected $start_date;
protected $end_date;
protected $pricing_model;
protected $price;
protected $max_impressions;
protected $max_clicks;
protected $priority;
protected $users_id;
protected $visibility;
protected $cpc_budget_type;
protected $cpc_total_budget;
protected $cpc_max_price_per_click;
protected $cpm_max_prints;
protected $cpm_current_prints;
public static function getSearchFieldsNames()
{
return ['name'];
}
public static function getTableName()
{
return 'vast_campaigns';
}
public function getName()
{
return $this->name;
}
public function getType()
{
return $this->type;
}
public function getStatus()
{
return $this->status;
}
public function getStart_date()
{
return $this->start_date;
}
public function getEnd_date()
{
return $this->end_date;
}
public function getPricing_model()
{
return $this->pricing_model;
}
public function getPrice()
{
return $this->price;
}
public function getMax_impressions()
{
return $this->max_impressions;
}
public function getMax_clicks()
{
return $this->max_clicks;
}
public function getPriority()
{
return $this->priority;
}
public function getUsers_id()
{
return $this->users_id;
}
public function getVisibility()
{
return $this->visibility;
}
public function getCpc_budget_type()
{
return $this->cpc_budget_type;
}
public function getCpc_total_budget()
{
return $this->cpc_total_budget;
}
public function getCpc_max_price_per_click()
{
return $this->cpc_max_price_per_click;
}
public function getCpm_max_prints()
{
return $this->cpm_max_prints;
}
public function getCpm_current_prints()
{
return $this->cpm_current_prints;
}
public function getPrintsLeft()
{
return ($this->cpm_max_prints-$this->cpm_current_prints);
}
public function setName($name)
{
$this->name = $name;
}
public function setType($type)
{
$this->type = $type;
}
public function setStatus($status)
{
$this->status = $status;
}
public function setStart_date($start_date)
{
$this->start_date = $start_date;
}
public function setEnd_date($end_date)
{
$this->end_date = $end_date;
}
public function setPricing_model($pricing_model)
{
$this->pricing_model = $pricing_model;
}
public function setPrice($price)
{
$this->price = $price;
}
public function setMax_impressions($max_impressions)
{
$this->max_impressions = $max_impressions;
}
public function setMax_clicks($max_clicks)
{
$this->max_clicks = $max_clicks;
}
public function setPriority($priority)
{
$this->priority = $priority;
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function setVisibility($visibility)
{
$this->visibility = $visibility;
}
public function setCpc_budget_type($cpc_budget_type)
{
$this->cpc_budget_type = $cpc_budget_type;
}
public function setCpc_total_budget($cpc_total_budget)
{
$this->cpc_total_budget = $cpc_total_budget;
}
public function setCpc_max_price_per_click($cpc_max_price_per_click)
{
$this->cpc_max_price_per_click = $cpc_max_price_per_click;
}
public function setCpm_max_prints($cpm_max_prints)
{
$this->cpm_max_prints = $cpm_max_prints;
}
public function setCpm_current_prints($cpm_current_prints)
{
$this->cpm_current_prints = $cpm_current_prints;
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function save()
{
$this->cpm_current_prints = intval($this->cpm_current_prints);
if (empty($this->visibility)) {
$this->visibility = 'listed';
}
if (empty($this->cpc_budget_type)) {
$this->cpc_budget_type = 'Campaign Total';
}
if (empty($this->cpc_total_budget)) {
$this->cpc_total_budget = 0;
}
if (empty($this->cpc_max_price_per_click)) {
$this->cpc_max_price_per_click = 0;
}
if (empty($this->visibility)) {
$this->visibility = 'listed';
}
return parent::save();
}
public function addVideo($videos_id, $status = 'a')
{
$vast_campaigns_id = $this->getId();
if (empty($vast_campaigns_id)) {
$this->setId($this->save());
$vast_campaigns_id = $this->getId();
}
$campainVideos = new VastCampaignsVideos(0);
$campainVideos->loadFromCampainVideo($vast_campaigns_id, $videos_id);
$campainVideos->setStatus($status);
return $campainVideos->save();
}
public static function getValidCampaigns()
{
global $global;
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
AVideoPlugin::loadPlugin('User_Location');
$User_Location = User_Location::getSessionLocation();
$sql = "SELECT * from " . static::getTableName() . " vc WHERE status = 'a' AND start_date <= now() AND end_date >=now() AND cpm_max_prints > cpm_current_prints ";
if (!empty($ad_server_location) && !empty($User_Location) && $User_Location['country_name'] !== '-') {
// show only campaign for the user location
$sql .= " AND ( (vc.id IN (SELECT vast_campaigns_id FROM campaign_locations WHERE (country_name = 'All' OR country_name IS NULL OR country_name = '') OR "
. " (country_name = \"{$User_Location['country_name']}\" AND region_name = 'All') OR "
. " (country_name = \"{$User_Location['country_name']}\" AND region_name = \"{$User_Location['region_name']}\" AND city_name = 'All') OR"
. " (country_name = \"{$User_Location['country_name']}\" AND region_name = \"{$User_Location['region_name']}\" AND city_name = \"{$User_Location['city_name']}\") ) ) "
. " OR vc.id NOT IN(SELECT vast_campaigns_id FROM campaign_locations) )";
}
$sql .= " ORDER BY priority ";
//echo $sql;
//_error_log($sql);
$res = sqlDAL::readSql($sql);
$rows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = [];
if ($res != false) {
foreach ($rows as $row) {
$row['printsLeft'] = $row['cpm_max_prints'] - $row['cpm_current_prints'];
$r[] = $row;
}
}
return $r;
}
public static function getAll()
{
global $global;
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
$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) {
$row['data'] = VastCampaignsLogs::getDataFromCampaign($row['id']);
$row['printsLeft'] = $row['cpm_max_prints'] - $row['cpm_current_prints'];
if (!empty($ad_server_location)) {
$row['locations'] = $ad_server_location->getCampaignLocations($row['id']);
}
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public function addView()
{
global $global;
if (!empty($this->id)) {
$sql = "UPDATE " . static::getTableName() . " SET cpm_current_prints = cpm_current_prints+1 ";
$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 add view");
return false;
}
public function delete()
{
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM vast_campaigns_logs ";
$sql .= " WHERE vast_campaigns_has_videos_id IN (SELECT id FROM vast_campaigns_has_videos WHERE vast_campaigns_id = ?)";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
$campaigns_video_log = sqlDAL::writeSql($sql, "i", [$this->id]);
$sql = "DELETE FROM vast_campaigns_has_videos ";
$sql .= " WHERE vast_campaigns_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
$campaigns_video = sqlDAL::writeSql($sql, "i", [$this->id]);
}
return parent::delete();
}
public static function getValidCampaignsFromVideo($videos_id)
{
global $global;
$sql = "SELECT vchv.*, vc.* from " . static::getTableName() . " vc LEFT JOIN vast_campaigns_has_videos vchv ON vchv.vast_campaigns_id = vc.id WHERE vc.status = 'a' "
. " AND start_date <= now() AND end_date >=now() AND cpm_max_prints > cpm_current_prints AND videos_id = {$videos_id}";
//echo $sql;
$res = sqlDAL::readSql($sql);
$rows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = [];
if ($res != false) {
foreach ($rows as $row) {
$row['printsLeft'] = $row['cpm_max_prints'] - $row['cpm_current_prints'];
$r[] = $row;
}
}
return $r;
}
}

View file

@ -4,60 +4,77 @@ require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
require_once dirname(__FILE__) . '/../../../objects/video.php';
class VastCampaignsLogs extends ObjectYPT {
class VastCampaignsLogs extends ObjectYPT
{
protected $id;
protected $users_id;
protected $type;
protected $vast_campaigns_has_videos_id;
protected $ip;
protected $id, $users_id, $type, $vast_campaigns_has_videos_id, $ip;
static function getSearchFieldsNames() {
return array();
public static function getSearchFieldsNames()
{
return [];
}
static function getTableName() {
public static function getTableName()
{
return 'vast_campaigns_logs';
}
function getId() {
public function getId()
{
return $this->id;
}
function getUsers_id() {
public function getUsers_id()
{
return $this->users_id;
}
function getType() {
public function getType()
{
return $this->type;
}
function getVast_campaigns_has_videos_id() {
public function getVast_campaigns_has_videos_id()
{
return $this->vast_campaigns_has_videos_id;
}
function setId($id) {
public function setId($id)
{
$this->id = $id;
}
function setUsers_id($users_id) {
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
function setType($type) {
public function setType($type)
{
$this->type = $type;
}
function setVast_campaigns_has_videos_id($vast_campaigns_has_videos_id) {
public function setVast_campaigns_has_videos_id($vast_campaigns_has_videos_id)
{
$this->vast_campaigns_has_videos_id = $vast_campaigns_has_videos_id;
}
function getIp() {
public function getIp()
{
return $this->ip;
}
function save() {
public function save()
{
$this->ip = getRealIpAddr();
return parent::save();
}
static function getViews(){
public static function getViews()
{
global $global;
$sql = "SELECT count(*) as total FROM vast_campaigns_logs WHERE `type` = 'start'";
@ -71,15 +88,16 @@ class VastCampaignsLogs extends ObjectYPT {
}
return $row['total'];
}
static function getData($vast_campaigns_has_videos_id){
public static function getData($vast_campaigns_has_videos_id)
{
global $global;
$sql = "SELECT `type`, count(*) as total FROM vast_campaigns_logs WHERE vast_campaigns_has_videos_id = $vast_campaigns_has_videos_id GROUP BY `type`";
$res = sqlDAL::readSql($sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$data = array();
$data = [];
if ($res!=false) {
foreach ($fullData as $row) {
$data[$row['type']] = $row['total'];
@ -89,17 +107,18 @@ class VastCampaignsLogs extends ObjectYPT {
}
return $data;
}
static function getDataFromCampaign($vast_campaigns_id){
public static function getDataFromCampaign($vast_campaigns_id)
{
global $global;
$sql = "SELECT `type`, count(vast_campaigns_id) as total FROM vast_campaigns_logs vcl "
. " LEFT JOIN vast_campaigns_has_videos vchv ON vast_campaigns_has_videos_id = vchv.id "
. " WHERE vast_campaigns_id = $vast_campaigns_id GROUP BY `type`";
//echo $sql."\n";
$res = sqlDAL::readSql($sql);
//echo $sql."\n";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$data = array();
$data = [];
if ($res!=false) {
foreach ($fullData as $row) {
$data[$row['type']] = $row['total'];
@ -109,7 +128,4 @@ class VastCampaignsLogs extends ObjectYPT {
}
return $data;
}
}

View file

@ -5,35 +5,45 @@ require_once dirname(__FILE__) . '/../../../objects/user.php';
require_once dirname(__FILE__) . '/../../../objects/video.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php';
class VastCampaignsVideos extends ObjectYPT {
class VastCampaignsVideos extends ObjectYPT
{
protected $id;
protected $vast_campaigns_id;
protected $videos_id;
protected $status;
protected $link;
protected $ad_title;
protected $id, $vast_campaigns_id, $videos_id, $status, $link, $ad_title;
static function getSearchFieldsNames() {
return array();
public static function getSearchFieldsNames()
{
return [];
}
static function getTableName() {
public static function getTableName()
{
return 'vast_campaigns_has_videos';
}
function loadFromCampainVideo($vast_campaigns_id, $videos_id){
public function loadFromCampainVideo($vast_campaigns_id, $videos_id)
{
$row = self::getCampainVideo($vast_campaigns_id, $videos_id);
if (empty($row))
if (empty($row)) {
return false;
}
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
static protected function getCampainVideo($vast_campaigns_id, $videos_id) {
protected static function getCampainVideo($vast_campaigns_id, $videos_id)
{
global $global;
$vast_campaigns_id = intval($vast_campaigns_id);
$videos_id = intval($videos_id);
$sql = "SELECT * FROM " . static::getTableName() . " WHERE vast_campaigns_id = ? , videos_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,"ii",array($vast_campaigns_id, $videos_id));
$res = sqlDAL::readSql($sql, "ii", [$vast_campaigns_id, $videos_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
@ -43,20 +53,21 @@ class VastCampaignsVideos extends ObjectYPT {
}
return $row;
}
static function getRandomCampainVideo($vast_campaigns_id) {
public static function getRandomCampainVideo($vast_campaigns_id)
{
global $global;
$vast_campaigns_id = intval($vast_campaigns_id);
if(empty($vast_campaigns_id)){
if (empty($vast_campaigns_id)) {
$campaings = VastCampaigns::getValidCampaigns();
if(empty($campaings[0])){
if (empty($campaings[0])) {
return false;
}
$vast_campaigns_id = $campaings[0]['id'];
}
$sql = "SELECT * FROM " . static::getTableName() . " WHERE vast_campaigns_id = ? ORDER BY RAND() 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($vast_campaigns_id));
$res = sqlDAL::readSql($sql, "i", [$vast_campaigns_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
@ -66,25 +77,26 @@ class VastCampaignsVideos extends ObjectYPT {
}
return $row;
}
static function getAllFromCampaign($vast_campaigns_id, $getImages = false) {
public static function getAllFromCampaign($vast_campaigns_id, $getImages = false)
{
global $global;
$vast_campaigns_id = intval($vast_campaigns_id);
$sql = "SELECT v.*, c.* FROM " . static::getTableName() . " c "
. " LEFT JOIN videos v ON videos_id = v.id WHERE 1=1 ";
if(!empty($vast_campaigns_id)){
if (!empty($vast_campaigns_id)) {
$sql .= " AND vast_campaigns_id=$vast_campaigns_id ";
}
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res!=false) {
foreach ($fullData as $row) {
if($getImages){
if ($getImages) {
$row['poster'] = Video::getImageFromID($row['videos_id']);
}
$row['data'] = VastCampaignsLogs::getDataFromCampaign($row['vast_campaigns_id']);
@ -95,91 +107,104 @@ class VastCampaignsVideos extends ObjectYPT {
}
return $rows;
}
static public function getValidVideos($vast_campaigns_id){
public static function getValidVideos($vast_campaigns_id)
{
global $global;
$sql = "SELECT v.*, c.* from " . static::getTableName() . " c LEFT JOIN videos v ON v.id = videos_id WHERE vast_campaigns_id = ? AND c.status = 'a' ";
$sql = "SELECT v.*, c.* from " . static::getTableName() . " c LEFT JOIN videos v ON v.id = videos_id WHERE vast_campaigns_id = ? AND c.status = 'a' ";
$res = sqlDAL::readSql($sql,"i",array($vast_campaigns_id));
$rows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = array();
if ($res!=false) {
foreach($rows as $row) {
$r[] = $row;
}
$res = sqlDAL::readSql($sql, "i", [$vast_campaigns_id]);
$rows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = [];
if ($res!=false) {
foreach ($rows as $row) {
$r[] = $row;
}
}
return $r;
return $r;
}
function getId() {
public function getId()
{
return $this->id;
}
function getVast_campaigns_id() {
public function getVast_campaigns_id()
{
return $this->vast_campaigns_id;
}
function getVideos_id() {
public function getVideos_id()
{
return $this->videos_id;
}
function getStatus() {
public function getStatus()
{
return $this->status;
}
function setId($id) {
public function setId($id)
{
$this->id = $id;
}
function setVast_campaigns_id($vast_campaigns_id) {
public function setVast_campaigns_id($vast_campaigns_id)
{
$this->vast_campaigns_id = $vast_campaigns_id;
}
function setVideos_id($videos_id) {
public function setVideos_id($videos_id)
{
$this->videos_id = $videos_id;
}
function setStatus($status) {
public function setStatus($status)
{
$this->status = $status;
}
function getLink() {
public function getLink()
{
return $this->link;
}
function getAd_title() {
public function getAd_title()
{
return $this->ad_title;
}
function setLink($link) {
public function setLink($link)
{
$this->link = $link;
}
function setAd_title($ad_title) {
public function setAd_title($ad_title)
{
$this->ad_title = $ad_title;
}
function delete() {
public function delete()
{
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM vast_campaigns_logs ";
$sql .= " WHERE vast_campaigns_has_videos_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
$campaigns_video_log = sqlDAL::writeSql($sql,"i",array($this->id));
$campaigns_video_log = sqlDAL::writeSql($sql, "i", [$this->id]);
}
return parent::delete();
}
public function save() {
if(empty($this->vast_campaigns_id) || strtolower($this->vast_campaigns_id)=='null' ){
public function save()
{
if (empty($this->vast_campaigns_id) || strtolower($this->vast_campaigns_id)=='null') {
return false;
}
return parent::save();
}
}

View file

@ -7,7 +7,7 @@ require_once $global['systemRootPath'] . 'objects/video.php';
$ad_server = AVideoPlugin::loadPlugin('AD_Server');
$obj = AVideoPlugin::getObjectData('AD_Server');
if(empty($_GET['campaign_has_videos_id'])){
if (empty($_GET['campaign_has_videos_id'])) {
$video = VastCampaignsVideos::getRandomCampainVideo(intval(@$_GET['campaign_id']));
$_GET['campaign_has_videos_id'] = $video['id'];
}
@ -47,7 +47,7 @@ $video = new Video("", "", $vastCampaingVideos->getVideos_id());
</TrackingEvents>
<?php
$campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
if(!empty($campaignVideo)){
if (!empty($campaignVideo)) {
$link = $campaignVideo->getLink();
if (filter_var($link, FILTER_VALIDATE_URL)) {
?>
@ -55,7 +55,7 @@ $video = new Video("", "", $vastCampaingVideos->getVideos_id());
<ClickThrough id="GDFP"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=ClickThrough&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></ClickThrough>
</VideoClicks>
<?php
}else{
} else {
_error_log("VastCampaignsVideos has not a valid link: {$link}");
}
}
@ -68,7 +68,7 @@ $video = new Video("", "", $vastCampaingVideos->getVideos_id());
$adsCount++;
echo "\n " . '<MediaFile id="GDFP" delivery="progressive" type="video/mp4" scalable="true" maintainAspectRatio="true"><![CDATA[' . ($value['url']) . ']]></MediaFile>';
}
if(!$adsCount){
if (!$adsCount) {
echo "\n " . '<MediaFile id="GDFP" delivery="progressive" type="video/mp4" scalable="true" maintainAspectRatio="true"><![CDATA[' . $global['webSiteRootURL'].'plugin/AD_Server/view/adswarning.mp4]]></MediaFile>';
}
?>

View file

@ -4,14 +4,14 @@ header('Content-type: application/xml');
require_once '../../videos/configuration.php';
allowOrigin();
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if(empty($ad_server)){
if (empty($ad_server)) {
die("not enabled");
}
if(empty($_GET['video_length'])){
if (empty($_GET['video_length'])) {
$_GET['video_length'] = 300;
}
if(empty($_GET['vmap_id'])){
if (empty($_GET['vmap_id'])) {
$_GET['vmap_id'] = uniqid();
}
@ -20,11 +20,10 @@ $vmaps = AD_Server::getVMAPSFromRequest();
<?xml version="1.0" encoding="UTF-8"?>
<vmap:VMAP xmlns:vmap="http://www.iab.net/videosuite/vmap" version="1.0">
<?php
foreach ($vmaps as $value) {
if(empty($value['VAST']['campaing'])){
foreach ($vmaps as $value) {
if (empty($value['VAST']['campaing'])) {
continue;
}
?>
} ?>
<vmap:AdBreak timeOffset="<?php echo $value['timeOffset']; ?>" breakType="linear">
<vmap:AdSource id="<?php echo $value['idTag']; ?>" allowMultipleAds="true" followRedirects="true" breakId="<?php echo $value['idTag']; ?>-break">
<vmap:AdTagURI templateType="vast3"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/VAST.php?campaign_has_videos_id=<?php echo $value['VAST']['campaing']; ?>&vmap_id=<?php echo @$_GET['vmap_id']; ?>]]></vmap:AdTagURI>

View file

@ -7,9 +7,9 @@
var options = {id: 'mainVideo', adTagUrl: '<?php echo $global['webSiteRootURL'] ?>plugin/AD_Server/VMAP.php?video_length=<?php echo $video_length ?>&vmap_id=<?php echo $vmap_id ?>&random=<?php echo uniqid(); ?>'};
player.ima(options);
$(document).ready(function () {
<?php
if (!empty($obj->showMarkers)) {
?>
<?php
if (!empty($obj->showMarkers)) {
?>
$.getScript("<?php echo $global['webSiteRootURL'] ?>plugin/AD_Server/videojs-markers/videojs-markers.js", function (data, textStatus, jqxhr) {
if (typeof player == 'undefined') {
@ -27,21 +27,19 @@ if (!empty($obj->showMarkers)) {
}
},
markers: [
<?php
foreach ($vmaps as $value) {
$vastCampaingVideos = new VastCampaignsVideos($value->VAST->campaing);
$video = new Video("", "", $vastCampaingVideos->getVideos_id());
?>
<?php
foreach ($vmaps as $value) {
$vastCampaingVideos = new VastCampaignsVideos($value->VAST->campaing);
$video = new Video("", "", $vastCampaingVideos->getVideos_id()); ?>
{time: <?php echo $value->timeOffsetSeconds; ?>, text: "<?php echo addcslashes($video->getTitle(), '"'); ?>"},
<?php
}
?>
<?php
} ?>
]
});
});
<?php
}
?>
<?php
}
?>
// Remove controls from the player on iPad to stop native controls from stealing
// our click
var contentPlayer = document.getElementById('content_video_html5_api');
@ -76,4 +74,4 @@ if (!empty($obj->showMarkers)) {
$($('#mainVideo_ima-ad-container div:first-child')[0]).css({'width': width});
}
}
</script>
</script>

View file

@ -8,7 +8,7 @@ $obj->error = true;
$obj->msg = "";
$obj->views = 0;
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if(empty($ad_server)){
if (empty($ad_server)) {
$obj->msg = "not enabled";
die(json_encode($obj));
}
@ -16,4 +16,4 @@ if(empty($ad_server)){
$obj->error = false;
$obj->views = VastCampaignsLogs::getViews();
echo json_encode($obj);
echo json_encode($obj);

View file

@ -12,8 +12,8 @@ if (!User::isAdmin()) {
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle( __("VAST"));
<?php
echo getHTMLTitle(__("VAST"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';

View file

@ -471,10 +471,10 @@ if (!User::isAdmin()) {
avideoAlert("<?php echo __("Congratulations!"); ?>", "<?php echo __("Your register has been saved!"); ?>", "success");
<?php
if (!empty($ad_server_location)) {
?>
?>
$('#locationList').empty();
<?php
}
}
?>
$("#panelForm").trigger("reset");
}

View file

@ -1,34 +1,34 @@
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
if(empty($_GET['campaign_has_videos_id'])){
die('campaign_has_videos_id Can not be empty');
}
$users_id = 'null';
if(User::isLogged()){
$users_id = User::getId();
}
$log = new VastCampaignsLogs(0);
$log->setType($_GET['label']);
$log->setUsers_id($users_id);
$log->setVast_campaigns_has_videos_id($_GET['campaign_has_videos_id']);
$log->save();
$campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
if($_GET['label'] === 'Impression'){
$campaign = new VastCampaigns($campaignVideo->getVast_campaigns_id());
$campaign->addView();
}
if($_GET['label'] === 'ClickThrough'){
// get the URL
$link = $campaignVideo->getLink();
if(filter_var($link, FILTER_VALIDATE_URL) ){
header("Location: ".$link);
}
}
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
if (empty($_GET['campaign_has_videos_id'])) {
die('campaign_has_videos_id Can not be empty');
}
$users_id = 'null';
if (User::isLogged()) {
$users_id = User::getId();
}
$log = new VastCampaignsLogs(0);
$log->setType($_GET['label']);
$log->setUsers_id($users_id);
$log->setVast_campaigns_has_videos_id($_GET['campaign_has_videos_id']);
$log->save();
$campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
if ($_GET['label'] === 'Impression') {
$campaign = new VastCampaigns($campaignVideo->getVast_campaigns_id());
$campaign->addView();
}
if ($_GET['label'] === 'ClickThrough') {
// get the URL
$link = $campaignVideo->getLink();
if (filter_var($link, FILTER_VALIDATE_URL)) {
header("Location: ".$link);
}
}

View file

@ -1,41 +1,42 @@
<?php
header('Content-Type: application/json');
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new VastCampaigns(@$_POST['campId']);
$o->setName($_POST['name']);
$o->setType("Contract");
$o->setStatus($_POST['status']);
$o->setStart_date($_POST['start_date']);
$o->setEnd_date($_POST['end_date']);
$o->setPricing_model("CPM");
$o->setPriority(10);
$o->setUsers_id(User::getId());
$o->setCpm_max_prints($_POST['maxPrints']);
$o->setVisibility('listed');
if($id = $o->save()){
$obj->error = false;
}
if(!empty($ad_server_location) && !empty($id)){
CampaignLocations::deleteFromCapmpaign($id);
if(!empty($_POST['country_name'])){
$ad_server_location->addCampaignLocation($_POST['country_name'], $_POST['region_name'], $_POST['city_name'], $id);
}
}
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new VastCampaigns(@$_POST['campId']);
$o->setName($_POST['name']);
$o->setType("Contract");
$o->setStatus($_POST['status']);
$o->setStart_date($_POST['start_date']);
$o->setEnd_date($_POST['end_date']);
$o->setPricing_model("CPM");
$o->setPriority(10);
$o->setUsers_id(User::getId());
$o->setCpm_max_prints($_POST['maxPrints']);
$o->setVisibility('listed');
if ($id = $o->save()) {
$obj->error = false;
}
if (!empty($ad_server_location) && !empty($id)) {
CampaignLocations::deleteFromCapmpaign($id);
if (!empty($_POST['country_name'])) {
$ad_server_location->addCampaignLocation($_POST['country_name'], $_POST['region_name'], $_POST['city_name'], $id);
}
}
echo json_encode($obj);

View file

@ -1,29 +1,30 @@
<?php
header('Content-Type: application/json');
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['inputVideoAd_id']);
$o = new VastCampaignsVideos($id);
$o->setVast_campaigns_id($_POST['vast_campaigns_id']);
$o->setVideos_id($_POST['videos_id']);
$o->setLink($_POST['uri']);
$o->setAd_title($_POST['title']);
$o->setStatus('a');
if($o->save()){
$obj->error = false;
}
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['inputVideoAd_id']);
$o = new VastCampaignsVideos($id);
$o->setVast_campaigns_id($_POST['vast_campaigns_id']);
$o->setVideos_id($_POST['videos_id']);
$o->setLink($_POST['uri']);
$o->setAd_title($_POST['title']);
$o->setStatus('a');
if ($o->save()) {
$obj->error = false;
}
echo json_encode($obj);

View file

@ -1,8 +1,8 @@
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
header('Content-Type: application/json');
$rows = VastCampaigns::getAll();
?>
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
header('Content-Type: application/json');
$rows = VastCampaigns::getAll();
?>
{"data": <?php echo json_encode($rows); ?>}

View file

@ -1,8 +1,8 @@
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
header('Content-Type: application/json');
$rows = VastCampaignsVideos::getAllFromCampaign(intval(@$_POST['id']), true);
?>
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
header('Content-Type: application/json');
$rows = VastCampaignsVideos::getAllFromCampaign(intval(@$_POST['id']), true);
?>
{"data": <?php echo json_encode($rows); ?>}

View file

@ -1,22 +1,22 @@
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new VastCampaigns($id);
if($row->getUsers_id() == User::getId() || User::isAdmin()){
$obj->error = !$row->delete();
}
die(json_encode($obj));
?>
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaigns.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new VastCampaigns($id);
if ($row->getUsers_id() == User::getId() || User::isAdmin()) {
$obj->error = !$row->delete();
}
die(json_encode($obj));

View file

@ -1,22 +1,23 @@
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new VastCampaignsVideos($id);
if(User::isAdmin()){
$obj->error = !$row->delete();;
}
die(json_encode($obj));
?>
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new VastCampaignsVideos($id);
if (User::isAdmin()) {
$obj->error = !$row->delete();
;
}
die(json_encode($obj));

View file

@ -2,49 +2,56 @@
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class ADs extends PluginAbstract {
class ADs extends PluginAbstract
{
public static $AdsPositions = [
['leaderBoardBigVideo', 1],
['leaderBoardTop', 0],
['leaderBoardTop2', 0],
['channelLeaderBoardTop', 0],
['leaderBoardMiddle', 0],
['sideRectangle', 1],
['leaderBoardBigVideoMobile', 1],
['leaderBoardTopMobile', 1],
['leaderBoardTopMobile2', 1],
['channelLeaderBoardTopMobile', 1],
['leaderBoardMiddleMobile', 1],
];
static $AdsPositions = array(
array('leaderBoardBigVideo', 1)
, array('leaderBoardTop', 0)
, array('leaderBoardTop2', 0)
, array('channelLeaderBoardTop', 0)
, array('leaderBoardMiddle', 0)
, array('sideRectangle', 1)
, array('leaderBoardBigVideoMobile', 1)
, array('leaderBoardTopMobile', 1)
, array('leaderBoardTopMobile2', 1)
, array('channelLeaderBoardTopMobile', 1)
, array('leaderBoardMiddleMobile', 1));
public function getTags() {
return array(
public function getTags()
{
return [
PluginTags::$MONETIZATION,
PluginTags::$ADS,
PluginTags::$FREE
);
PluginTags::$FREE,
];
}
public function getDescription() {
public function getDescription()
{
$txt = "Handle the ads system, like Adsense or similar";
//$help = "<br><small><a href='https://github.com/WWBN/AVideo/wiki/AD_Overlay-Plugin' target='__blank'><i class='fas fa-question-circle'></i> Help</a></small>";
$help = "";
return $txt . $help;
}
public function getName() {
public function getName()
{
return "ADs";
}
public function getUUID() {
public function getUUID()
{
return "ADs73225-3807-4167-ba81-0509dd280e06";
}
public function getPluginVersion() {
public function getPluginVersion()
{
return "1.1";
}
public function getEmptyDataObject() {
public function getEmptyDataObject()
{
global $global, $config;
$obj = new stdClass();
@ -79,13 +86,15 @@ class ADs extends PluginAbstract {
return $obj;
}
public function getPluginMenu() {
public function getPluginMenu()
{
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/ADs/pluginMenu.html';
return file_get_contents($fileAPIName);
}
public function getHeadCode() {
public function getHeadCode()
{
$head = "<script> var adsbygoogleTimeout; </script>";
if (!empty($_GET['abkw'])) {
$abkw = preg_replace('/[^a-zA-Z0-9_ ,-]/', '', $_GET['abkw']);
@ -99,7 +108,7 @@ class ADs extends PluginAbstract {
if (!empty($v)) {
$channelName = $v["channelName"];
$category = $v["category"];
$head .= str_replace(array('{ChannelName}', '{Category}'), array(addcslashes($channelName, "'"), addcslashes($category, "'")), $obj->tags3rdParty);
$head .= str_replace(['{ChannelName}', '{Category}'], [addcslashes($channelName, "'"), addcslashes($category, "'")], $obj->tags3rdParty);
return $head;
}
@ -109,21 +118,22 @@ class ADs extends PluginAbstract {
if (!empty($obj->tags3rdParty)) {
$v = Category::getCategoryByName($_GET['catName']);
if (!empty($v)) {
$head .= str_replace(array(',', '{ChannelName}', '{Category}'), array('', '', addcslashes($v["name"], "'")), $obj->tags3rdParty);
$head .= str_replace([',', '{ChannelName}', '{Category}'], ['', '', addcslashes($v["name"], "'")], $obj->tags3rdParty);
return $head;
}
}
}
if (!empty($_GET['channelName'])) {
if (!empty($obj->tags3rdParty)) {
$head .= str_replace(array(',', '{ChannelName}', '{Category}'), array('', addcslashes($_GET['channelName'], "'"), ''), $obj->tags3rdParty);
$head .= str_replace([',', '{ChannelName}', '{Category}'], ['', addcslashes($_GET['channelName'], "'"), ''], $obj->tags3rdParty);
return $head;
}
}
return "{$head}<script> window.abkw = 'home-page'; </script>";
}
static function giveGoogleATimeout($adCode) {
public static function giveGoogleATimeout($adCode)
{
$videos_id = getVideos_id();
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
@ -135,16 +145,18 @@ class ADs extends PluginAbstract {
}
return $adCode;
}
function showAds($videos_id){
public function showAds($videos_id)
{
$obj = AVideoPlugin::getDataObject('ADs');
if($obj->doNotShowAdsForPaidUsers && User::isLogged()){
if ($obj->doNotShowAdsForPaidUsers && User::isLogged()) {
return !AVideoPlugin::isPaidUser(User::getId());
}
return true;
}
static function getAdsPath($type) {
public static function getAdsPath($type)
{
global $global;
$typeFound = false;
foreach (ADs::$AdsPositions as $key => $value) {
@ -161,10 +173,11 @@ class ADs extends PluginAbstract {
$videosURL = "{$global['webSiteRootURL']}videos/ADs/{$type}/";
make_path($videosDir);
return array('path' => $videosDir, 'url' => $videosURL);
return ['path' => $videosDir, 'url' => $videosURL];
}
static function getNewAdsPath($type) {
public static function getNewAdsPath($type)
{
$paths = self::getAdsPath($type);
if (empty($paths)) {
@ -173,10 +186,11 @@ class ADs extends PluginAbstract {
$fileName = uniqid();
return array('fileName' => $fileName, 'path' => $paths['path'] . $fileName . '.png', 'url' => $paths['url'] . $fileName . '.png', 'txt' => $paths['path'] . $fileName . '.txt');
return ['fileName' => $fileName, 'path' => $paths['path'] . $fileName . '.png', 'url' => $paths['url'] . $fileName . '.png', 'txt' => $paths['path'] . $fileName . '.txt'];
}
static function getAds($type) {
public static function getAds($type)
{
global $global;
$paths = self::getAdsPath($type);
@ -189,29 +203,31 @@ class ADs extends PluginAbstract {
$files = _glob($paths['path'], '/.png$/');
$return = array();
$return = [];
foreach ($files as $value) {
$fileName = str_replace($videosDir, '', $value);
$fileName = str_replace('.png', '', $fileName);
$return[] = array('type' => $type, 'fileName' => $fileName, 'url' => file_get_contents($videosDir . "{$fileName}.txt"), 'imageURL' => $videosURL . "{$fileName}.png", 'imagePath' => $value);
$return[] = ['type' => $type, 'fileName' => $fileName, 'url' => file_get_contents($videosDir . "{$fileName}.txt"), 'imageURL' => $videosURL . "{$fileName}.png", 'imagePath' => $value];
}
return $return;
}
static function getSize($type) {
public static function getSize($type)
{
$obj = AVideoPlugin::getObjectData("ADs");
foreach (ADs::$AdsPositions as $key => $value) {
if ($type == $value[0]) {
eval("\$width = \$obj->$value[0]Width;");
eval("\$height = \$obj->$value[0]Height;");
return array('width' => $width, 'height' => $height, 'isMobile' => preg_match('/mobile/i', $value[0]), 'isSquare' => $value[1]);
return ['width' => $width, 'height' => $height, 'isMobile' => preg_match('/mobile/i', $value[0]), 'isSquare' => $value[1]];
}
}
return array('width' => null, 'height' => null);
return ['width' => null, 'height' => null];
}
static function getAdsHTML($type) {
public static function getAdsHTML($type)
{
global $global;
$paths = self::getAds($type);
@ -238,7 +254,7 @@ class ADs extends PluginAbstract {
$validPaths = 0;
foreach ($paths as $value) {
$fsize= filesize($value['imagePath']);
if($fsize<5000){
if ($fsize<5000) {
continue;
}
$validPaths++;
@ -264,14 +280,15 @@ class ADs extends PluginAbstract {
<span class=\"glyphicon glyphicon-chevron-right\"></span>
<span class=\"sr-only\">Next</span>
</a>";
}else if(empty($validPaths) && User::isAdmin()){
} elseif (empty($validPaths) && User::isAdmin()) {
$html .= "<div class='alert alert-warning'>{$type} ADs Area</div>";
}
$html .= "</div></div></center>";
return $html;
}
public function getFooterCode() {
public function getFooterCode()
{
global $global;
$js = "<script>$(function(){
$('.carousel').carousel({
@ -281,12 +298,12 @@ class ADs extends PluginAbstract {
return $js;
}
static function saveAdsHTML($type) {
public static function saveAdsHTML($type)
{
$o = new stdClass();
$o->type = "textarea";
$o->value = self::getAdsHTML($type);
$p = new ADs();
return $p->updateParameter($type, $o);
}
}

View file

@ -1,62 +1,62 @@
<?php
global $global, $config;
header('Content-Type: application/json');
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
$result = new stdClass();
$result->error = true;
$result->msg = '';
if (!User::isAdmin()) {
$result->msg = __("You can not do this");
die(json_encode($result));
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$obj = AVideoPlugin::getObjectDataIfEnabled("ADs");
if (empty($obj)) {
$result->msg = __("The plugin is disabled");
die(json_encode($result));
}
$type = $_REQUEST['type'];
if (empty($type)) {
$result->msg = __("Type is not defined");
die(json_encode($result));
}
$typeFound = false;
foreach (ADs::$AdsPositions as $key => $value) {
if($type===$value[0]){
$typeFound = true;
break;
}
}
if (empty($typeFound)) {
$result->msg = __("Type NOT found");
die(json_encode($result));
}
$fileName = preg_replace('/[^0-9a-z]/i', '', $_REQUEST['fileName']);
if (empty($fileName)) {
$result->msg = __("Invalid filename");
die(json_encode($result));
}
$paths = ADs::getAdsPath($type);
$files = _glob($paths['path'], "/{$fileName}/");
foreach ($files as $value) {
unlink($value);
}
$result->type = $type;
$result->save = ADs::saveAdsHTML($type);
$result->error = false;
die(json_encode($result));
<?php
global $global, $config;
header('Content-Type: application/json');
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
$result = new stdClass();
$result->error = true;
$result->msg = '';
if (!User::isAdmin()) {
$result->msg = __("You can not do this");
die(json_encode($result));
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$obj = AVideoPlugin::getObjectDataIfEnabled("ADs");
if (empty($obj)) {
$result->msg = __("The plugin is disabled");
die(json_encode($result));
}
$type = $_REQUEST['type'];
if (empty($type)) {
$result->msg = __("Type is not defined");
die(json_encode($result));
}
$typeFound = false;
foreach (ADs::$AdsPositions as $key => $value) {
if ($type===$value[0]) {
$typeFound = true;
break;
}
}
if (empty($typeFound)) {
$result->msg = __("Type NOT found");
die(json_encode($result));
}
$fileName = preg_replace('/[^0-9a-z]/i', '', $_REQUEST['fileName']);
if (empty($fileName)) {
$result->msg = __("Invalid filename");
die(json_encode($result));
}
$paths = ADs::getAdsPath($type);
$files = _glob($paths['path'], "/{$fileName}/");
foreach ($files as $value) {
unlink($value);
}
$result->type = $type;
$result->save = ADs::saveAdsHTML($type);
$result->error = false;
die(json_encode($result));

View file

@ -1,39 +1,39 @@
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
if (!User::isAdmin()) {
gotToLoginAndComeBackHere(__("You can not do this"));
exit;
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$obj = AVideoPlugin::getObjectDataIfEnabled("ADs");
if (empty($obj)) {
forbiddenPage(__("The plugin is disabled"));
exit;
}
?>
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
if (!User::isAdmin()) {
gotToLoginAndComeBackHere(__("You can not do this"));
exit;
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$obj = AVideoPlugin::getObjectDataIfEnabled("ADs");
if (empty($obj)) {
forbiddenPage(__("The plugin is disabled"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("ADs Editor"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<?php
echo getHTMLTitle(__("ADs Editor"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<br>
<div class="panel panel-default">
<div class="panel-heading">
<?php echo __('Edit Ads'); ?>
<?php echo __('Edit Ads'); ?>
</div>
<div class="panel-body">
@ -41,43 +41,40 @@ if (empty($obj)) {
<div class="col-md-2">
<ul class="nav nav-tabs nav-pills nav-stacked">
<?php
$active = 'active';
foreach (ADs::$AdsPositions as $key => $value) {
echo '<li class="' . $active . '">'
. '<a onclick="restartForm' . $value[0] . '()" data-toggle="tab" href="#adsTabs' . $key . '">' . $value[0] . '</a>'
. '</li>';
$active = '';
}
?>
<?php
$active = 'active';
foreach (ADs::$AdsPositions as $key => $value) {
echo '<li class="' . $active . '">'
. '<a onclick="restartForm' . $value[0] . '()" data-toggle="tab" href="#adsTabs' . $key . '">' . $value[0] . '</a>'
. '</li>';
$active = '';
}
?>
</ul>
</div>
<div class="col-md-10">
<div class="tab-content">
<?php
$active = ' in active';
foreach (ADs::$AdsPositions as $key => $value) {
$size = ADs::getSize($value[0]);
$width = $size['width'];
$height = $size['height'];
?>
<?php
$active = ' in active';
foreach (ADs::$AdsPositions as $key => $value) {
$size = ADs::getSize($value[0]);
$width = $size['width'];
$height = $size['height']; ?>
<div id="adsTabs<?php echo $key; ?>" class="tab-pane fade <?php echo $active; ?>">
<div class="panel panel-default">
<div class="panel-heading">
<?php echo __("Image"), " {$width}X{$height} px"; ?>
<?php echo __("Image"), " {$width}X{$height} px"; ?>
</div>
<div class="panel-body">
<form>
<div class="form-group">
<?php
$croppie1 = getCroppie(__("Upload Image") . ' ' . $value[0], "setImage_" . $value[0], $width, $height);
echo $croppie1['html'];
?>
<?php
$croppie1 = getCroppie(__("Upload Image") . ' ' . $value[0], "setImage_" . $value[0], $width, $height);
echo $croppie1['html']; ?>
</div>
<div class="form-group">
<label for="inputAdsURL<?php echo $value[0]; ?>"><?php echo __("URL"); ?></label>
@ -88,23 +85,21 @@ if (empty($obj)) {
</div>
<div class="panel-footer">
<ul class="list-group" id="list-group-<?php echo $value[0]; ?>">
<?php
$adsList = ADs::getAds($value[0]);
foreach ($adsList as $item) {
?>
<?php
$adsList = ADs::getAds($value[0]);
foreach ($adsList as $item) {
?>
<li class="list-group-item clearfix" id="<?php echo $item["fileName"]; ?>" >
<img src="<?php echo $item["imageURL"]; ?>"
class="img img-responsive pull-left"
style="max-height: 60px; max-width: 150px; margin-right: 10px;">
<?php
echo $item["url"];
?>
<?php
echo $item["url"]; ?>
<button class="btn btn-sm btn-danger pull-right" onclick="deleteAdsImage('<?php echo $item["type"]; ?>', '<?php echo $item["fileName"]; ?>')"><i class="fas fa-trash"></i></button>
</li>
<?php
}
?>
<?php
} ?>
</ul>
</div>
</div>
@ -113,9 +108,8 @@ if (empty($obj)) {
$('#adsTabs<?php echo $key; ?> form').submit(function (evt) {
evt.preventDefault();
setTimeout(function () {
<?php
echo $croppie1['getCroppieFunction'];
?>
<?php
echo $croppie1['getCroppieFunction']; ?>
}, 500);
return false;
});
@ -125,7 +119,7 @@ if (empty($obj)) {
}
function restartForm<?php echo $value[0]; ?>() {
<?php echo $croppie1['restartCroppie'] . "('".getCDN()."view/img/transparent1px.png');"; ?>
<?php echo $croppie1['restartCroppie'] . "('".getCDN()."view/img/transparent1px.png');"; ?>
$('#inputAdsURL<?php echo $value[0]; ?>').val('');
}
@ -134,10 +128,10 @@ if (empty($obj)) {
});
</script>
<?php
$active = '';
}
?>
<?php
$active = '';
}
?>
</div>
</div>
</div>
@ -195,8 +189,8 @@ if (empty($obj)) {
}
</script>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>

View file

@ -1,65 +1,64 @@
<?php
global $global, $config;
header('Content-Type: application/json');
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
$result = new stdClass();
$result->error = true;
$result->msg = '';
$result->url = '';
$result->imageURL = '';
if (!User::isAdmin()) {
$result->msg = __("You can not do this");
die(json_encode($result));
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$obj = AVideoPlugin::getObjectDataIfEnabled("ADs");
if (empty($obj)) {
$result->msg = __("The plugin is disabled");
die(json_encode($result));
}
$type = $_REQUEST['type'];
if (empty($type)) {
$result->msg = __("Type is not defined");
die(json_encode($result));
}
$typeFound = false;
foreach (ADs::$AdsPositions as $key => $value) {
if($type===$value[0]){
$typeFound = true;
break;
}
}
if (empty($typeFound)) {
$result->msg = __("Type NOT found");
die(json_encode($result));
}
if(!IsValidURL(@$_REQUEST['url'])){
$_REQUEST['url'] = '';
}
$paths = ADs::getNewAdsPath($type);
saveCroppieImage($paths['path'], "image");
file_put_contents($paths['txt'], @$_REQUEST['url']);
$result->type = $type;
$result->url = $_REQUEST['url'];
$result->imageURL = $paths['url'];
$result->fileName = $paths['fileName'];
$result->error = false;
$result->save = ADs::saveAdsHTML($type);
// save plugin parameter
die(json_encode($result));
<?php
global $global, $config;
header('Content-Type: application/json');
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
$result = new stdClass();
$result->error = true;
$result->msg = '';
$result->url = '';
$result->imageURL = '';
if (!User::isAdmin()) {
$result->msg = __("You can not do this");
die(json_encode($result));
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$obj = AVideoPlugin::getObjectDataIfEnabled("ADs");
if (empty($obj)) {
$result->msg = __("The plugin is disabled");
die(json_encode($result));
}
$type = $_REQUEST['type'];
if (empty($type)) {
$result->msg = __("Type is not defined");
die(json_encode($result));
}
$typeFound = false;
foreach (ADs::$AdsPositions as $key => $value) {
if ($type===$value[0]) {
$typeFound = true;
break;
}
}
if (empty($typeFound)) {
$result->msg = __("Type NOT found");
die(json_encode($result));
}
if (!IsValidURL(@$_REQUEST['url'])) {
$_REQUEST['url'] = '';
}
$paths = ADs::getNewAdsPath($type);
saveCroppieImage($paths['path'], "image");
file_put_contents($paths['txt'], @$_REQUEST['url']);
$result->type = $type;
$result->url = $_REQUEST['url'];
$result->imageURL = $paths['url'];
$result->fileName = $paths['fileName'];
$result->error = false;
$result->save = ADs::saveAdsHTML($type);
// save plugin parameter
die(json_encode($result));

View file

@ -1,43 +1,49 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class API extends PluginAbstract {
public function getTags() {
return array(
class API extends PluginAbstract
{
public function getTags()
{
return [
PluginTags::$FREE,
PluginTags::$MOBILE
);
PluginTags::$MOBILE,
];
}
public function getDescription() {
public function getDescription()
{
return "Handle APIs for third party Applications";
}
public function getName() {
public function getName()
{
return "API";
}
public function getUUID() {
public function getUUID()
{
return "1apicbec-91db-4357-bb10-ee08b0913778";
}
public function getEmptyDataObject() {
public function getEmptyDataObject()
{
global $global;
$obj = new stdClass();
$obj->APISecret = md5($global['systemRootPath']);
return $obj;
}
public function getPluginMenu() {
public function getPluginMenu()
{
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/API/pluginMenu.html';
return file_get_contents($fileAPIName);
}
public function set($parameters) {
public function set($parameters)
{
if (empty($parameters['APIName'])) {
$object = new ApiObject("Parameter APIName can not be empty (set)");
} else {
@ -62,7 +68,8 @@ class API extends PluginAbstract {
return $object;
}
public function get($parameters) {
public function get($parameters)
{
if (empty($parameters['APIName'])) {
$object = new ApiObject("Parameter APIName can not be empty (get)");
} else {
@ -87,13 +94,14 @@ class API extends PluginAbstract {
return $object;
}
private function startResponseObject($parameters) {
private function startResponseObject($parameters)
{
$obj = new stdClass();
if (empty($parameters['sort']) && !empty($parameters['order'][0]['dir'])) {
$index = intval($parameters['order'][0]['column']);
$parameters['sort'][$parameters['columns'][$index]['data']] = $_GET['order'][0]['dir'];
}
$array = array('sort', 'rowCount', 'current', 'searchPhrase');
$array = ['sort', 'rowCount', 'current', 'searchPhrase'];
foreach ($array as $value) {
if (!empty($parameters[$value])) {
$obj->$value = $parameters[$value];
@ -104,20 +112,22 @@ class API extends PluginAbstract {
return $obj;
}
private function getToPost() {
private function getToPost()
{
foreach ($_GET as $key => $value) {
$_POST[$key] = $value;
}
}
/**
* @param type $parameters
* @param type $parameters
* 'plugin_name' The plugin name that you want to retrieve the parameters
* 'APISecret' to list all videos
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&rowCount=3&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_plugin_parameters($parameters) {
public function get_api_plugin_parameters($parameters)
{
global $global;
$name = "get_api_plugin_parameters" . json_encode($parameters);
$obj = ObjectYPT::getCache($name, 3600);
@ -139,7 +149,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* This will check if the provided UserAgent/Headers comes from a mobile
* Returns true if any type of mobile device detected, including special ones
* PHP Sample code: "plugin/API/{getOrSet}.json.php?APIName={APIName}&userAgent=".urlencode($_SERVER["HTTP_USER_AGENT"])."&httpHeaders=".urlencode(json_encode(getallheaders()))
@ -148,7 +158,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&userAgent=Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F89.0.4389.82+Safari%2F537.36
* @return \ApiObject
*/
public function get_api_is_mobile($parameters) {
public function get_api_is_mobile($parameters)
{
global $global;
$obj = $this->startResponseObject($parameters);
if (!empty($_REQUEST['httpHeaders'])) {
@ -156,7 +167,7 @@ class API extends PluginAbstract {
if (!empty($json)) {
$_REQUEST['httpHeaders'] = $json;
} else {
$_REQUEST['httpHeaders'] = array($_REQUEST['httpHeaders']);
$_REQUEST['httpHeaders'] = [$_REQUEST['httpHeaders']];
}
}
$obj->userAgent = @$_REQUEST['userAgent'];
@ -166,7 +177,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* ['sort' database sort column]
* ['rowCount' max numbers of rows]
* ['current' current page]
@ -175,7 +186,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&rowCount=3&current=1&sort[created]=DESC
* @return \ApiObject
*/
public function get_api_category($parameters) {
public function get_api_category($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/category.php';
$obj = $this->startResponseObject($parameters);
@ -188,14 +200,15 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* 'APISecret' to list all videos
* 'playlists_id' the program id
* 'index' the position of the video
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&playlists_id=1&index=2&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_video_from_program($parameters) {
public function get_api_video_from_program($parameters)
{
global $global;
$playlists = AVideoPlugin::loadPlugin("PlayLists");
if (empty($parameters['playlists_id'])) {
@ -239,7 +252,6 @@ class API extends PluginAbstract {
$parameters['totalPlaylistDuration'] = 0;
$parameters['currentPlaylistTime'] = 0;
foreach ($parameters['videos'] as $key => $value) {
$parameters['videos'][$key]['path'] = Video::getHigherVideoPathFromID($value['id']);
if ($key && $key <= $parameters['index']) {
$parameters['currentPlaylistTime'] += durationToSeconds($parameters['videos'][$key - 1]['duration']);
@ -264,13 +276,14 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* 'APISecret' to list all videos
* 'videos_id' the video id
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_video_file($parameters) {
public function get_api_video_file($parameters)
{
global $global;
$obj = $this->startResponseObject($parameters);
$obj->videos_id = $parameters['videos_id'];
@ -289,7 +302,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* ['APISecret' to list all videos]
* ['sort' database sort column]
* ['videos_id' the video id (will return only 1 or 0 video)]
@ -304,8 +317,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&catName=default&rowCount=10
* @return \ApiObject
*/
public function get_api_video($parameters) {
public function get_api_video($parameters)
{
$rowCount = getRowCount();
if ($rowCount > 100) {
// use 1 hour cache
@ -327,12 +340,12 @@ class API extends PluginAbstract {
$status = "";
$ignoreGroup = true;
}
$rows = array(Video::getVideo($parameters['videos_id'], $status, $ignoreGroup));
$rows = [Video::getVideo($parameters['videos_id'], $status, $ignoreGroup)];
$totalRows = empty($rows) ? 0 : 1;
} else if ($dataObj->APISecret === @$_GET['APISecret']) {
} elseif ($dataObj->APISecret === @$_GET['APISecret']) {
$rows = Video::getAllVideos("viewable", false, true);
$totalRows = Video::getTotalVideos("viewable", false, true);
} else if (!empty($parameters['clean_title'])) {
} elseif (!empty($parameters['clean_title'])) {
$rows = Video::getVideoFromCleanTitle($parameters['clean_title']);
$totalRows = empty($rows) ? 0 : 1;
} else {
@ -418,7 +431,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* ['APISecret' to list all videos]
* ['searchPhrase' to search on the categories]
* ['tags_id' the ID of the tag you want to filter]
@ -427,7 +440,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_videosCount($parameters) {
public function get_api_videosCount($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
$obj = $this->startResponseObject($parameters);
@ -444,7 +458,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* 'videos_id' the video id that will be deleted
* ['APISecret' if passed will not require user and pass]
* ['user' usename of the user that will like the video]
@ -452,7 +466,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&user=admin&pass=123&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_video_delete($parameters) {
public function get_api_video_delete($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
$obj = $this->startResponseObject($parameters);
@ -476,7 +491,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* 'comment' String with the comment
* 'videos_id' the video that will receive the comment
* ['id' the comment id if you will edit some]
@ -486,14 +501,15 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&user=admin&pass=123&APISecret={APISecret}
* @return \ApiObject
*/
public function set_api_comment($parameters) {
public function set_api_comment($parameters)
{
global $global;
$obj = $this->startResponseObject($parameters);
$dataObj = $this->getDataObject();
if (!empty($parameters['videos_id'])) {
if (!empty($_GET['APISecret']) && $dataObj->APISecret !== $_GET['APISecret']) {
return new ApiObject("Secret does not match");
} else if (!User::canComment()) {
} elseif (!User::canComment()) {
return new ApiObject("Access denied");
}
$parameters['comments_id'] = intval(@$parameters['comments_id']);
@ -516,7 +532,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* 'videos_id' the video id that will be deleted
* 'title' the video title
* 'status' the video status
@ -526,7 +542,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&user=admin&pass=123&APISecret={APISecret}
* @return \ApiObject
*/
public function set_api_video_save($parameters) {
public function set_api_video_save($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
$obj = $this->startResponseObject($parameters);
@ -557,11 +574,12 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}
* @return \ApiObject
*/
public function get_api_livestreams($parameters) {
public function get_api_livestreams($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'plugin/Live/stats.json.php';
exit;
@ -569,7 +587,7 @@ class API extends PluginAbstract {
/**
* Return a user livestream information
* @param type $parameters
* @param type $parameters
* ['title' Livestream title]
* ['public' 1 = live is listed; 0 = not listed]
* ['APISecret' if passed will not require user and pass]
@ -579,7 +597,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}&users_id=1
* @return \ApiObject
*/
public function set_api_livestream_save($parameters) {
public function set_api_livestream_save($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
$obj = $this->startResponseObject($parameters);
@ -618,7 +637,7 @@ class API extends PluginAbstract {
/**
* Return a user livestream information
* @param type $parameters
* @param type $parameters
* ['APISecret' if passed will not require user and pass]
* ['users_id' the user ID]
* ['user' usename if does not have the APISecret]
@ -626,13 +645,13 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}&users_id=1
* @return \ApiObject
*/
public function get_api_user($parameters) {
public function get_api_user($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
$obj = $this->startResponseObject($parameters);
$dataObj = $this->getDataObject();
if ($dataObj->APISecret === @$_GET['APISecret'] || User::isLogged()) {
if (!empty($parameters['users_id'])) {
if ($dataObj->APISecret !== @$_GET['APISecret']) {
$parameters['users_id'] = User::getId();
@ -662,7 +681,7 @@ class API extends PluginAbstract {
/**
* Return a users list
* @param type $parameters
* @param type $parameters
* 'APISecret' is required for this call
* ['rowCount' max numbers of rows]
* ['current' current page]
@ -671,12 +690,12 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}&status=a&rowCount=3&searchPhrase=test
* @return \ApiObject
*/
public function get_api_users_list($parameters) {
public function get_api_users_list($parameters)
{
global $global;
$obj = $this->startResponseObject($parameters);
$dataObj = $this->getDataObject();
if ($dataObj->APISecret === $_GET['APISecret']) {
$status = '';
if (!empty($_GET['status'])) {
if ($_GET['status'] === 'i') {
@ -686,7 +705,7 @@ class API extends PluginAbstract {
}
}
$rows = User::getAllUsers(true, array('user', 'name'), $status);
$rows = User::getAllUsers(true, ['user', 'name'], $status);
return new ApiObject("", false, $rows);
} else {
@ -695,7 +714,7 @@ class API extends PluginAbstract {
}
/**
* @param type $parameters
* @param type $parameters
* ['APISecret' to list all videos]
* ['sort' database sort column]
* ['videos_id' the video id (will return only 1 or 0 video)]
@ -709,7 +728,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_videosViewsCount($parameters) {
public function get_api_videosViewsCount($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
$obj = $this->startResponseObject($parameters);
@ -717,10 +737,10 @@ class API extends PluginAbstract {
if ($dataObj->APISecret === @$_GET['APISecret']) {
$rows = Video::getAllVideos("viewable", false, true);
$totalRows = Video::getTotalVideos("viewable", false, true);
} else if (!empty($parameters['videos_id'])) {
$rows = array(Video::getVideo($parameters['videos_id']));
} elseif (!empty($parameters['videos_id'])) {
$rows = [Video::getVideo($parameters['videos_id'])];
$totalRows = empty($rows) ? 0 : 1;
} else if (!empty($parameters['clean_title'])) {
} elseif (!empty($parameters['clean_title'])) {
$rows = Video::getVideoFromCleanTitle($parameters['clean_title']);
$totalRows = empty($rows) ? 0 : 1;
} else {
@ -746,11 +766,12 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}
* @return \ApiObject
*/
public function get_api_channels($parameters) {
public function get_api_channels($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/Channel.php';
$channels = Channel::getChannels();
$list = array();
$list = [];
foreach ($channels as $value) {
$obj = new stdClass();
$obj->id = $value['id'];
@ -769,11 +790,12 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}
* @return \ApiObject
*/
public function get_api_programs($parameters) {
public function get_api_programs($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/playlist.php';
$playlists = PlayList::getAll();
$list = array();
$list = [];
foreach ($playlists as $value) {
$videosArrayId = PlayList::getVideosIdFromPlaylist($value['id']);
if (empty($videosArrayId) || $value['status'] == "favorite" || $value['status'] == "watch_later") {
@ -798,7 +820,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?users_id=1&APIName={APIName}&APISecret={APISecret}
* @return \ApiObject
*/
public function get_api_subscribers($parameters) {
public function get_api_subscribers($parameters)
{
global $global;
$name = "get_api_subscribers" . json_encode($parameters);
@ -825,12 +848,13 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}
* @return \ApiObject
*/
public function get_api_categories($parameters) {
public function get_api_categories($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/category.php';
$categories = Category::getAllCategories();
array_multisort(array_column($categories, 'hierarchyAndName'), SORT_ASC, $categories);
$list = array();
$list = [];
foreach ($categories as $value) {
$obj = new stdClass();
$obj->id = $value['id'];
@ -846,11 +870,12 @@ class API extends PluginAbstract {
/**
* @param type $parameters
* 'videos_id' the video ID what you want to get the likes
* 'videos_id' the video ID what you want to get the likes
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1
* @return \ApiObject
*/
public function get_api_likes($parameters) {
public function get_api_likes($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/like.php';
if (empty($parameters['videos_id'])) {
@ -867,7 +892,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&user=admin&pass=123
* @return \ApiObject
*/
public function set_api_like($parameters) {
public function set_api_like($parameters)
{
return $this->like($parameters, 1);
}
@ -879,7 +905,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&user=admin&pass=123
* @return \ApiObject
*/
public function set_api_dislike($parameters) {
public function set_api_dislike($parameters)
{
return $this->like($parameters, -1);
}
@ -891,12 +918,13 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=1&user=admin&pass=123
* @return \ApiObject
*/
public function set_api_removelike($parameters) {
public function set_api_removelike($parameters)
{
return $this->like($parameters, 0);
}
/**
*
*
* @param type $parameters
* 'user' usename of the user
* 'pass' password of the user
@ -904,7 +932,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function get_api_signIn($parameters) {
public function get_api_signIn($parameters)
{
global $global;
$this->getToPost();
require_once $global['systemRootPath'] . 'objects/login.json.php';
@ -912,9 +941,9 @@ class API extends PluginAbstract {
}
/**
*
*
* @param type $parameters
* 'user' usename of the user
* 'user' usename of the user
* 'pass' password of the user
* 'email' email of the user
* 'name' real name of the user
@ -922,7 +951,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}&user=admin&pass=123&email=me@mysite.com&name=Yeshua
* @return type
*/
public function set_api_signUp($parameters) {
public function set_api_signUp($parameters)
{
global $global;
$this->getToPost();
$obj = $this->getDataObject();
@ -934,7 +964,8 @@ class API extends PluginAbstract {
exit;
}
private function like($parameters, $like) {
private function like($parameters, $like)
{
global $global;
require_once $global['systemRootPath'] . 'objects/like.php';
if (empty($parameters['videos_id'])) {
@ -959,7 +990,8 @@ class API extends PluginAbstract {
* @example for JSON response: {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=3&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true&optionalAdTagUrl=2&json=1
* @return type
*/
public function get_api_vmap($parameters) {
public function get_api_vmap($parameters)
{
global $global;
$this->getToPost();
require_once $global['systemRootPath'] . 'plugin/GoogleAds_IMA/VMAP.php';
@ -977,7 +1009,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=3&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true&optionalAdTagUrl=2
* @return type
*/
public function get_api_vast($parameters) {
public function get_api_vast($parameters)
{
global $global;
$this->getToPost();
$vastOnly = 1;
@ -993,7 +1026,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}&ip=2.20.147.123
* @return type
*/
public function get_api_IP2Location($parameters) {
public function get_api_IP2Location($parameters)
{
global $global;
$this->getToPost();
$obj = $this->getDataObject();
@ -1019,7 +1053,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function get_api_favorite($parameters) {
public function get_api_favorite($parameters)
{
$plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists");
if (empty($plugin)) {
return new ApiObject("Plugin disabled");
@ -1053,7 +1088,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=3&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function set_api_favorite($parameters) {
public function set_api_favorite($parameters)
{
$this->favorite($parameters, true);
}
@ -1066,11 +1102,13 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=3&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function set_api_removeFavorite($parameters) {
public function set_api_removeFavorite($parameters)
{
$this->favorite($parameters, false);
}
private function favorite($parameters, $add) {
private function favorite($parameters, $add)
{
global $global;
$plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists");
if (empty($plugin)) {
@ -1095,7 +1133,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function get_api_watch_later($parameters) {
public function get_api_watch_later($parameters)
{
$plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists");
if (empty($plugin)) {
return new ApiObject("Plugin disabled");
@ -1134,7 +1173,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=3&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function set_api_watch_later($parameters) {
public function set_api_watch_later($parameters)
{
$this->watch_later($parameters, true);
}
@ -1147,11 +1187,13 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&videos_id=3&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function set_api_removeWatch_later($parameters) {
public function set_api_removeWatch_later($parameters)
{
$this->watch_later($parameters, false);
}
private function watch_later($parameters, $add) {
private function watch_later($parameters, $add)
{
global $global;
$plugin = AVideoPlugin::loadPluginIfEnabled("PlayLists");
if (empty($plugin)) {
@ -1180,7 +1222,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&message=HelloWorld&users_id=2&room_users_id=4&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function set_api_chat2_message($parameters) {
public function set_api_chat2_message($parameters)
{
global $global;
$plugin = AVideoPlugin::loadPluginIfEnabled("Chat2");
if (empty($plugin)) {
@ -1210,7 +1253,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&greater_then_id=88&lower_then_id=98&to_users_id=2&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function get_api_chat2_chat($parameters) {
public function get_api_chat2_chat($parameters)
{
global $global;
$plugin = AVideoPlugin::loadPluginIfEnabled("Chat2");
if (empty($plugin)) {
@ -1224,10 +1268,10 @@ class API extends PluginAbstract {
if (!empty($parameters['greater_then_id'])) {
if (empty($_SESSION['chatLog'])) {
$_SESSION['chatLog'] = array();
$_SESSION['chatLog'] = [];
}
if (empty($_SESSION['chatLog'][$_GET['to_users_id']])) {
$_SESSION['chatLog'][$_GET['to_users_id']] = array();
$_SESSION['chatLog'][$_GET['to_users_id']] = [];
}
$_SESSION['chatLog'][$_GET['to_users_id']][0]['id'] = $parameters['greater_then_id'];
}
@ -1250,7 +1294,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&greater_then_id=88&lower_then_id=98&room_users_id=2&user=admin&pass=f321d14cdeeb7cded7489f504fa8862b&encodedPass=true
* @return type
*/
public function get_api_chat2_room($parameters) {
public function get_api_chat2_room($parameters)
{
global $global;
$plugin = AVideoPlugin::loadPluginIfEnabled("Chat2");
if (empty($plugin)) {
@ -1264,10 +1309,10 @@ class API extends PluginAbstract {
if (!empty($parameters['greater_then_id'])) {
if (empty($_SESSION['chatLog'])) {
$_SESSION['chatLog'] = array();
$_SESSION['chatLog'] = [];
}
if (empty($_SESSION['chatLog'][$_GET['to_users_id']])) {
$_SESSION['chatLog'][$_GET['to_users_id']] = array();
$_SESSION['chatLog'][$_GET['to_users_id']] = [];
}
$_SESSION['chatLog'][$_GET['to_users_id']][0]['id'] = $parameters['greater_then_id'];
}
@ -1276,7 +1321,8 @@ class API extends PluginAbstract {
exit;
}
static function getAPISecret() {
public static function getAPISecret()
{
$obj = AVideoPlugin::getDataObject("API");
return $obj->APISecret;
}
@ -1287,7 +1333,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}
* @return type
*/
public function get_api_locales($parameters) {
public function get_api_locales($parameters)
{
global $global, $config;
$langs = new stdClass();
$langs->default = $config->getLanguage();
@ -1303,7 +1350,8 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&language=cn
* @return type
*/
public function get_api_locale($parameters) {
public function get_api_locale($parameters)
{
global $global, $config;
$obj = $this->startResponseObject($parameters);
@ -1332,13 +1380,13 @@ class API extends PluginAbstract {
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIName={APIName}&APISecret={APISecret}&user=admin
* @return \ApiObject
*/
public function set_api_userImages($parameters) {
public function set_api_userImages($parameters)
{
global $global;
require_once $global['systemRootPath'] . 'objects/video.php';
// $obj = $this->startResponseObject($parameters);
$dataObj = $this->getDataObject();
if ($dataObj->APISecret === @$_GET['APISecret']) {
$user = new User("", $parameters['user'], false);
if (empty($user->getUser())) {
return new ApiObject("User Not defined");
@ -1352,19 +1400,18 @@ class API extends PluginAbstract {
return new ApiObject("API Secret is not valid");
}
}
}
class ApiObject {
class ApiObject
{
public $error;
public $message;
public $response;
function __construct($message = "api not started or not found", $error = true, $response = array()) {
public function __construct($message = "api not started or not found", $error = true, $response = [])
{
$this->error = $error;
$this->message = $message;
$this->response = $response;
}
}

View file

@ -1,10 +1,11 @@
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
list($scriptPath) = get_included_files();
[$scriptPath] = get_included_files();
$path = pathinfo($scriptPath);
$configFile = $path['dirname'] . "/" . $configFile;
}
require_once $configFile;
require_once $global['systemRootPath'].'plugin/API/API.php';
header('Content-Type: application/json');
@ -14,21 +15,21 @@ header("Access-Control-Allow-Headers: Content-Type");
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
if(empty($plugin)){
if (empty($plugin)) {
$obj = new ApiObject("API Plugin disabled");
die(json_encode($obj));
}
// gettig the mobile submited value
$inputJSON = url_get_contents('php://input');
$input = _json_decode($inputJSON, TRUE); //convert JSON into array
if(empty($input)){
$input = array();
}else{
$input = _json_decode($inputJSON, true); //convert JSON into array
if (empty($input)) {
$input = [];
} else {
$input = object_to_array($input);
}
$parameters = array_merge($_GET, $_POST, $input);
$obj = $plugin->get($parameters);
die(json_encode($obj));
die(json_encode($obj));

View file

@ -81,22 +81,21 @@ $reflector = new ReflectionClass('API');
foreach ($class_methods as $method_name) {
if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) {
continue;
}
?>
} ?>
<li class="list-group-item">
<details>
<summary style="cursor: pointer;"><i class="fas fa-sign-<?php echo strtoupper($matches[1]) === "GET" ? "out" : "in" ?>-alt"></i> <?php echo strtoupper($matches[1]) ?> <?php echo $matches[2] ?></summary>
<br>
<pre><?php
$comment = $reflector->getMethod($method_name)->getDocComment();
$comment = str_replace(array('{webSiteRootURL}', '{getOrSet}', '{APIName}', '{APISecret}'), array($global['webSiteRootURL'], $matches[1], $matches[2], $obj->APISecret), $comment);
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $comment, $match2);
//var_dump($match2[0]);
$link = "<a target='_blank' href='{$match2[0][0]}'>" . htmlentities($match2[0][0]) . "</a>";
$comment = str_replace(array($match2[0][0], " *"), array($link, "*"), $comment);
$comment = str_replace(['{webSiteRootURL}', '{getOrSet}', '{APIName}', '{APISecret}'], [$global['webSiteRootURL'], $matches[1], $matches[2], $obj->APISecret], $comment);
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $comment, $match2);
//var_dump($match2[0]);
$link = "<a target='_blank' href='{$match2[0][0]}'>" . htmlentities($match2[0][0]) . "</a>";
$comment = str_replace([$match2[0][0], " *"], [$link, "*"], $comment);
echo ($comment);
//{webSiteRootURL}plugin/API/{getOrSet}.json.php?name={name}
echo($comment);
//{webSiteRootURL}plugin/API/{getOrSet}.json.php?name={name}
?>
</pre>
</details>

View file

@ -1,10 +1,11 @@
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
list($scriptPath) = get_included_files();
[$scriptPath] = get_included_files();
$path = pathinfo($scriptPath);
$configFile = $path['dirname'] . "/" . $configFile;
}
require_once $configFile;
require_once $global['systemRootPath'].'plugin/API/API.php';
header('Content-Type: application/json');
@ -14,21 +15,21 @@ header("Access-Control-Allow-Headers: Content-Type");
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
if(empty($plugin)){
if (empty($plugin)) {
$obj = new ApiObject("API Plugin disabled");
die(json_encode($obj));
}
// gettig the mobile submited value
$inputJSON = url_get_contents('php://input');
$input = _json_decode($inputJSON, TRUE); //convert JSON into array
if(empty($input)){
$input = array();
}else{
$input = _json_decode($inputJSON, true); //convert JSON into array
if (empty($input)) {
$input = [];
} else {
$input = object_to_array($input);
}
$parameters = array_merge($_GET, $_POST, $input);
$obj = $plugin->set($parameters);
die(json_encode($obj));
die(json_encode($obj));

View file

@ -1,10 +1,11 @@
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
list($scriptPath) = get_included_files();
[$scriptPath] = get_included_files();
$path = pathinfo($scriptPath);
$configFile = $path['dirname'] . "/" . $configFile;
}
require_once $configFile;
require_once $global['systemRootPath'].'plugin/API/API.php';
header('Content-Type: application/json');
@ -12,11 +13,11 @@ header('Content-Type: application/json');
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
if(empty($plugin)){
if (empty($plugin)) {
$obj = new ApiObject("API Plugin disabled");
}else{
} else {
$obj = new ApiObject("API Plugin enabled", false);
}
die(json_encode($obj));
die(json_encode($obj));

File diff suppressed because it is too large Load diff

View file

@ -3,18 +3,20 @@
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/CDN/Storage/CDNStorage.php';
class CDN extends PluginAbstract {
public function getTags() {
return array(
class CDN extends PluginAbstract
{
public function getTags()
{
return [
PluginTags::$RECOMMENDED,
PluginTags::$LIVE,
PluginTags::$PLAYER,
PluginTags::$STORAGE
);
PluginTags::$STORAGE,
];
}
public function getDescription() {
public function getDescription()
{
global $global;
$txt = "With our CDN we will provide you a highly-distributed platform of servers that helps minimize delays in loading web page content "
. "by reducing the physical distance between the server and the user. This helps users around the world view the same high-quality "
@ -25,19 +27,23 @@ class CDN extends PluginAbstract {
return $txt . $help;
}
public function getName() {
public function getName()
{
return "CDN";
}
public function getUUID() {
public function getUUID()
{
return "CDN73225-3807-4167-ba81-0509dd280e06";
}
public function getPluginVersion() {
public function getPluginVersion()
{
return "2.0";
}
public function getEmptyDataObject() {
public function getEmptyDataObject()
{
global $global, $config;
$obj = new stdClass();
$obj->key = "";
@ -60,15 +66,17 @@ class CDN extends PluginAbstract {
return $obj;
}
public function getVideosManagerListButton() {
if(!self::userCanMoveVideoStorage()){
public function getVideosManagerListButton()
{
if (!self::userCanMoveVideoStorage()) {
return '';
}
$btn = '<button type="button" class="btn btn-default btn-light btn-sm btn-xs btn-block " onclick="avideoModalIframeSmall(webSiteRootURL+\\\'plugin/CDN/Storage/syncVideo.php?videos_id=\'+ row.id +\'\\\');" ><i class="fas fa-project-diagram"></i> CDN Storage</button>';
return $btn;
}
public function getPluginMenu() {
public function getPluginMenu()
{
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/CDN/pluginMenu.html';
$content = file_get_contents($fileAPIName);
@ -81,7 +89,7 @@ class CDN extends PluginAbstract {
$cdnMenu = str_replace('{url}', $url, $content);
$storageMenu = '';
if(self::userCanMoveVideoStorage()){
if (self::userCanMoveVideoStorage()) {
$fileStorageMenu = $global['systemRootPath'] . 'plugin/CDN/Storage/pluginMenu.html';
$storageMenu = file_get_contents($fileStorageMenu);
}
@ -89,13 +97,13 @@ class CDN extends PluginAbstract {
}
/**
*
*
* @param type $type enum(CDN, CDN_S3,CDN_B2,CDN_YPTStorage,CDN_Live,CDN_LiveServers)
* @param type $id the ID of the URL in case the CDN is an array
* @param type $id the ID of the URL in case the CDN is an array
* @return boolean
*/
static public function getURL($type = 'CDN', $id = 0) {
public static function getURL($type = 'CDN', $id = 0)
{
$obj = AVideoPlugin::getObjectData('CDN');
if (empty($obj->{$type})) {
@ -138,8 +146,9 @@ class CDN extends PluginAbstract {
return false;
}
static function getCDN_S3URL() {
public static function getCDN_S3URL()
{
$plugin = AVideoPlugin::getDataObjectIfEnabled('AWS_S3');
$CDN_S3 = '';
if (!empty($plugin)) {
@ -148,7 +157,7 @@ class CDN extends PluginAbstract {
$endpoint = trim($plugin->endpoint);
if (!empty($endpoint)) {
$CDN_S3 = str_replace('https://', "https://{$bucket_name}.", $endpoint);
} else if (!empty($plugin->region)) {
} elseif (!empty($plugin->region)) {
$CDN_S3 = "https://{$bucket_name}.s3-accesspoint.{$region}.amazonaws.com";
}
if (!empty($resp->CDN_S3)) {
@ -158,7 +167,8 @@ class CDN extends PluginAbstract {
return $CDN_S3;
}
static function getCDN_B2URL() {
public static function getCDN_B2URL()
{
$CDN_B2 = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('Blackblaze_B2');
if (!empty($plugin)) {
@ -171,7 +181,8 @@ class CDN extends PluginAbstract {
return $CDN_B2;
}
static function getCDN_FTPURL() {
public static function getCDN_FTPURL()
{
$CDN_FTP = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (!empty($plugin)) {
@ -179,14 +190,15 @@ class CDN extends PluginAbstract {
}
return $CDN_FTP;
}
public static function getVideoTags($videos_id) {
public static function getVideoTags($videos_id)
{
global $global;
if (empty($videos_id)) {
return array();
return [];
}
if (!Video::canEdit($videos_id)) {
return array();
return [];
}
$video = Video::getVideoLight($videos_id);
$sites_id = $video['sites_id'];
@ -197,7 +209,7 @@ class CDN extends PluginAbstract {
if ($isMoving) {
$obj->type = "danger";
$obj->text = '<i class="fas fa-sync fa-spin"></i> ' . __('Moving');
} else if (empty($sites_id)) {
} elseif (empty($sites_id)) {
$obj->type = "success";
$obj->text = '<i class="fas fa-map-marker-alt"></i> ' . __('Local');
} else {
@ -205,33 +217,37 @@ class CDN extends PluginAbstract {
$obj->text = "<i class=\"fas fa-project-diagram\"></i> " . __('Storage');
}
//var_dump($obj);exit;
return array($obj);
return [$obj];
}
public function onEncoderNotifyIsDone($videos_id) {
public function onEncoderNotifyIsDone($videos_id)
{
return $this->processNewVideo($videos_id);
}
public function onUploadIsDone($videos_id) {
public function onUploadIsDone($videos_id)
{
return $this->processNewVideo($videos_id);
}
private function processNewVideo($videos_id) {
private function processNewVideo($videos_id)
{
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if($obj->enable_storage){
if($obj->storage_autoupload_new_videos){
if ($obj->enable_storage) {
if ($obj->storage_autoupload_new_videos) {
CDNStorage::moveLocalToRemote($videos_id, false);
}
}
}
public static function userCanMoveVideoStorage(){
public static function userCanMoveVideoStorage()
{
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if(empty($obj->enable_storage)){
if (empty($obj->enable_storage)) {
return false;
}
if(User::isAdmin()){
if (User::isAdmin()) {
return true;
}
if (!empty($obj->storage_users_can_choose_storage) && User::canUpload()) {
@ -239,12 +255,12 @@ class CDN extends PluginAbstract {
}
return false;
}
public function getFooterCode() {
public function getFooterCode()
{
global $global;
if(self::userCanMoveVideoStorage()){
if (self::userCanMoveVideoStorage()) {
include $global['systemRootPath'] . 'plugin/CDN/Storage/footer.php';
}
}
}

View file

@ -9,9 +9,10 @@
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
use \Countable;
use Countable;
/**
* The FTP and SSL-FTP client for PHP.
@ -280,7 +281,7 @@ class FtpClient implements Countable
throw new FtpException('Unable to list directory');
}
$result = array();
$result = [];
$dir_len = strlen($directory);
// if it's the current
@ -289,7 +290,7 @@ class FtpClient implements Countable
}
// if it's the parent
if(false !== ($kdot = array_search('..', $files))) {
if (false !== ($kdot = array_search('..', $files))) {
unset($files[$kdot]);
}
@ -334,7 +335,6 @@ class FtpClient implements Countable
foreach ($items as $item) {
$result[] = $item;
}
} else {
$result[] = $file;
}
@ -618,7 +618,6 @@ class FtpClient implements Countable
// do the following if it is a directory
if (is_dir($source_directory.'/'.$file)) {
if (!$this->isDir($target_directory.'/'.$file)) {
// create directories that do not yet exist
@ -627,14 +626,16 @@ class FtpClient implements Countable
// recursive part
$this->putAll(
$source_directory.'/'.$file, $target_directory.'/'.$file,
$source_directory.'/'.$file,
$target_directory.'/'.$file,
$mode
);
} else {
// put the files
$this->ftp->put(
$target_directory.'/'.$file, $source_directory.'/'.$file,
$target_directory.'/'.$file,
$source_directory.'/'.$file,
$mode
);
}
@ -643,14 +644,14 @@ class FtpClient implements Countable
return $this;
}
public function put($source_directory, $target_directory, $mode = FTP_BINARY)
{
$this->ftp->put($source_directory, $target_directory, $mode);
return $this;
}
/**
* Returns a detailed list of files in the given directory.
@ -670,7 +671,7 @@ class FtpClient implements Countable
}
$list = $this->ftp->rawlist($directory);
$items = array();
$items = [];
if (!$list) {
return $items;
@ -718,8 +719,7 @@ class FtpClient implements Countable
// ".."
or $item[$len-1] == '.' && $item[$len-2] == '.' && $item[$len-3] == ' ')
){
) {
continue;
}
@ -769,7 +769,7 @@ class FtpClient implements Countable
*/
public function parseRawList(array $rawlist)
{
$items = array();
$items = [];
$path = '';
foreach ($rawlist as $key => $child) {
@ -825,7 +825,6 @@ class FtpClient implements Countable
}
$items[$key] = $item;
} else {
// the key is the path, behavior of FtpClient::rawlist() method()

View file

@ -9,6 +9,7 @@
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
@ -17,4 +18,6 @@ namespace FtpClient;
* @inheritDoc
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpException extends \Exception {}
class FtpException extends \Exception
{
}

View file

@ -9,6 +9,7 @@
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**

File diff suppressed because it is too large Load diff

View file

@ -25,7 +25,7 @@ if (empty($_REQUEST['videos_id'])) {
die(json_encode($obj));
}
if (!is_array($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = array($_REQUEST['videos_id']);
$_REQUEST['videos_id'] = [$_REQUEST['videos_id']];
}
_error_log('Start to move file ');
@ -41,7 +41,6 @@ foreach ($_REQUEST['videos_id'] as $videos_id) {
$obj->error = false;
//$obj->response = CDNStorage::moveLocalToRemote($videos_id);
$obj->response = CDNStorage::put($videos_id, 4);
}
_error_log('Finish to move file ');
echo json_encode($obj);

View file

@ -10,12 +10,12 @@ $obj->error = true;
$obj->msg = "";
$isEnabled = AVideoPlugin::isEnabledByName('CDN');
if(!$isEnabled){
if (!$isEnabled) {
$obj->msg = "CDN is disabled";
die(json_encode($obj));
}
if(empty($_REQUEST['videos_id'])){
if (empty($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = intval(@$argv[1]);
}
@ -25,7 +25,7 @@ if (empty($_REQUEST['videos_id'])) {
}
if (!is_array($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = array($_REQUEST['videos_id']);
$_REQUEST['videos_id'] = [$_REQUEST['videos_id']];
}
_error_log('Start to move remote to local ');
@ -40,7 +40,6 @@ foreach ($_REQUEST['videos_id'] as $videos_id) {
$obj->error = false;
$obj->response = CDNStorage::moveRemoteToLocal($videos_id);
}
_error_log('Finish to move remote to local ');

View file

@ -7,7 +7,7 @@
<?php
$totalL = $totalR = $totalFileSizeR = $totalFileSizeL = 0;
$list = CDNStorage::getFilesListBoth($videos_id);
$listString = array();
$listString = [];
foreach ($list as $key => $value) {
if (!empty($value['local']['local_filesize']) && $value['local']['local_filesize'] > 20 && $value['local']['local_filesize'] > 0) {
$totalL++;
@ -33,9 +33,8 @@
<i class="fas fa-project-diagram"></i>
<?php
printf(__('Upload %d files to storage'), $totalL);
$humanSize = humanFileSize($totalFileSizeL);
echo ' (' . $humanSize . ')';
?>
$humanSize = humanFileSize($totalFileSizeL);
echo ' (' . $humanSize . ')'; ?>
</button>
<script>
@ -59,17 +58,15 @@
<?php
}
if ($totalR) {
if(empty($totalL)){
if (empty($totalL)) {
CDNStorage::setSite($videos_id, true);
}
?>
} ?>
<button type="button" class="btn btn-success" onclick="CDNStorageDownload();">
<i class="fas fa-project-diagram"></i>
<?php
printf(__('Download %d files to disk'), $totalR);
$humanSize = humanFileSize($totalFileSizeR);
echo ' (' . $humanSize . ')';
?>
$humanSize = humanFileSize($totalFileSizeR);
echo ' (' . $humanSize . ')'; ?>
</button>
<script>

View file

@ -28,9 +28,9 @@ $video = Video::getVideoLight($videos_id);
<div class="container-fluid">
<?php
$isMoving = CDNStorage::isMoving($videos_id);
if(!empty($isMoving)){
if (!empty($isMoving)) {
include './panelIsMoving.php';
}else{
} else {
include './panelMove.php';
}
?>

View file

@ -1,41 +1,41 @@
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$resp = new stdClass();
$resp->error = true;
$resp->msg = '';
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj)) {
$resp->msg = 'Disable: CDN Plugin disabled, please enable it and clear the cache';
die(json_encode($resp));
}
if (empty($_REQUEST['key'])) {
$resp->msg = 'Key is empty';
die(json_encode($resp));
}
if (!empty($obj->key)) {
//check the key
if ($obj->key !== $_REQUEST['key']) {
$resp->msg = 'Key Does not match';
die(json_encode($resp));
}
}
$obj->key = $_REQUEST['key'];
foreach ($_REQUEST['par'] as $key => $value) {
$obj->{$key} = $value;
$resp->{$key} = $value;
}
$row = Plugin::getPluginByName('CDN');
$cdn = new Plugin($row['id']);
$cdn->setStatus('inactive');
$id = $cdn->save();
$resp->error = empty($id);
die(json_encode($resp));
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$resp = new stdClass();
$resp->error = true;
$resp->msg = '';
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj)) {
$resp->msg = 'Disable: CDN Plugin disabled, please enable it and clear the cache';
die(json_encode($resp));
}
if (empty($_REQUEST['key'])) {
$resp->msg = 'Key is empty';
die(json_encode($resp));
}
if (!empty($obj->key)) {
//check the key
if ($obj->key !== $_REQUEST['key']) {
$resp->msg = 'Key Does not match';
die(json_encode($resp));
}
}
$obj->key = $_REQUEST['key'];
foreach ($_REQUEST['par'] as $key => $value) {
$obj->{$key} = $value;
$resp->{$key} = $value;
}
$row = Plugin::getPluginByName('CDN');
$cdn = new Plugin($row['id']);
$cdn->setStatus('inactive');
$id = $cdn->save();
$resp->error = empty($id);
die(json_encode($resp));

View file

@ -1,100 +1,100 @@
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$resp = new stdClass();
$resp->error = true;
$resp->msg = '';
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj)) {
$resp->msg = 'Status: CDN Plugin disabled, please enable it and clear the cache';
die(json_encode($resp));
}
if (empty($_REQUEST['key'])) {
$resp->msg = 'Key is empty';
die(json_encode($resp));
}
if (!empty($obj->key)) {
//check the key
if ($obj->key !== $_REQUEST['key']) {
$resp->msg = 'Key Does not match';
die(json_encode($resp));
}
}
$obj->key = $_REQUEST['key'];
foreach ($_REQUEST['par'] as $key => $value) {
$obj->{$key} = $value;
$resp->{$key} = $value;
}
// Update S3 CDN
if (AVideoPlugin::isEnabledByName('AWS_S3')) {
$resp->CDN_S3 = CDN::getCDN_S3URL();
}else{
$resp->CDN_S3 = '';
}
// Update B2 CDN
if (AVideoPlugin::isEnabledByName('Blackblaze_B2')) {
$resp->CDN_B2 = CDN::getCDN_B2URL();
}else{
$resp->CDN_B2 = '';
}
// Update FTP CDN
if (AVideoPlugin::isEnabledByName('FTP_Storage')) {
$resp->CDN_FTP = CDN::getCDN_FTPURL();
}else{
$resp->CDN_FTP = '';
}
// Update Live CDN
$resp->CDN_Live = '';
$resp->CDN_LiveServers = array();
$plugin = AVideoPlugin::getDataObjectIfEnabled('Live');
if (!empty($plugin)) {
if ($plugin->useLiveServers) {
$rows = Live_servers::getAllActive();
foreach ($rows as $value) {
if (empty($value['playerServer'])) {
continue;
}
$resp->CDN_LiveServers[] = array(
'id' => $value['id'],
'url' => addLastSlash($value['playerServer'])
);
}
} else {
$resp->CDN_Live = addLastSlash($plugin->playerServer);
}
}
// Update YPT Storage CDN
$resp->CDN_YPTStorage = array();
$plugin = AVideoPlugin::getDataObjectIfEnabled('YPTStorage');
if (!empty($plugin)) {
$rows = Sites::getAllActive();
foreach ($rows as $value) {
if (empty($value['url'])) {
continue;
}
$resp->CDN_YPTStorage[] = array(
'id' => $value['id'],
'url' => addLastSlash($value['url'])
);
}
}
// Update Liveservers CDN
$cdn = AVideoPlugin::loadPluginIfEnabled('CDN');
$id = $cdn->setDataObject($obj);
if (!empty($id)) {
$resp->error = false;
}
die(json_encode($resp));
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$resp = new stdClass();
$resp->error = true;
$resp->msg = '';
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj)) {
$resp->msg = 'Status: CDN Plugin disabled, please enable it and clear the cache';
die(json_encode($resp));
}
if (empty($_REQUEST['key'])) {
$resp->msg = 'Key is empty';
die(json_encode($resp));
}
if (!empty($obj->key)) {
//check the key
if ($obj->key !== $_REQUEST['key']) {
$resp->msg = 'Key Does not match';
die(json_encode($resp));
}
}
$obj->key = $_REQUEST['key'];
foreach ($_REQUEST['par'] as $key => $value) {
$obj->{$key} = $value;
$resp->{$key} = $value;
}
// Update S3 CDN
if (AVideoPlugin::isEnabledByName('AWS_S3')) {
$resp->CDN_S3 = CDN::getCDN_S3URL();
} else {
$resp->CDN_S3 = '';
}
// Update B2 CDN
if (AVideoPlugin::isEnabledByName('Blackblaze_B2')) {
$resp->CDN_B2 = CDN::getCDN_B2URL();
} else {
$resp->CDN_B2 = '';
}
// Update FTP CDN
if (AVideoPlugin::isEnabledByName('FTP_Storage')) {
$resp->CDN_FTP = CDN::getCDN_FTPURL();
} else {
$resp->CDN_FTP = '';
}
// Update Live CDN
$resp->CDN_Live = '';
$resp->CDN_LiveServers = [];
$plugin = AVideoPlugin::getDataObjectIfEnabled('Live');
if (!empty($plugin)) {
if ($plugin->useLiveServers) {
$rows = Live_servers::getAllActive();
foreach ($rows as $value) {
if (empty($value['playerServer'])) {
continue;
}
$resp->CDN_LiveServers[] = [
'id' => $value['id'],
'url' => addLastSlash($value['playerServer']),
];
}
} else {
$resp->CDN_Live = addLastSlash($plugin->playerServer);
}
}
// Update YPT Storage CDN
$resp->CDN_YPTStorage = [];
$plugin = AVideoPlugin::getDataObjectIfEnabled('YPTStorage');
if (!empty($plugin)) {
$rows = Sites::getAllActive();
foreach ($rows as $value) {
if (empty($value['url'])) {
continue;
}
$resp->CDN_YPTStorage[] = [
'id' => $value['id'],
'url' => addLastSlash($value['url']),
];
}
}
// Update Liveservers CDN
$cdn = AVideoPlugin::loadPluginIfEnabled('CDN');
$id = $cdn->setDataObject($obj);
if (!empty($id)) {
$resp->error = false;
}
die(json_encode($resp));

View file

@ -1,48 +1,47 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
ob_end_flush();
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
require_once './functions.php';
set_time_limit(300);
ini_set('max_execution_time', 300);
getConnID(0);
/*
$list = ftp_mlsd_recursive($conn_id[0], "/{$CDNObj->storage_username}/");
var_dump($list);
*/
$index = intval(@$argv[1]);
$list = ftp_rawlist($conn_id[0], "/{$CDNObj->storage_username}/", true);
for ($i=$index;$i<count($list);$i++){
$value = $list[$i];
$parts = explode(' ', $value);
$dir = end($parts);
//echo $value.PHP_EOL;exit;
echo $i.' Searching '."/{$CDNObj->storage_username}/{$dir}/".PHP_EOL;
$files = ftp_rawlist($conn_id[0], "/{$CDNObj->storage_username}/{$dir}/", true);
foreach ($files as $file) {
trim($file);
if(preg_match('/enc_[0-9a-z]+.key$/i', $file)){
$parts = explode(' ', $file);
$file = end($parts);
$file = "/{$CDNObj->storage_username}/{$dir}/{$file}";
echo '******** Delete '.$file.PHP_EOL;
ftp_delete($conn_id[0], $file);
}
}
}
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
ob_end_flush();
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
require_once './functions.php';
set_time_limit(300);
ini_set('max_execution_time', 300);
getConnID(0);
/*
$list = ftp_mlsd_recursive($conn_id[0], "/{$CDNObj->storage_username}/");
var_dump($list);
*/
$index = intval(@$argv[1]);
$list = ftp_rawlist($conn_id[0], "/{$CDNObj->storage_username}/", true);
for ($i=$index;$i<count($list);$i++) {
$value = $list[$i];
$parts = explode(' ', $value);
$dir = end($parts);
//echo $value.PHP_EOL;exit;
echo $i.' Searching '."/{$CDNObj->storage_username}/{$dir}/".PHP_EOL;
$files = ftp_rawlist($conn_id[0], "/{$CDNObj->storage_username}/{$dir}/", true);
foreach ($files as $file) {
trim($file);
if (preg_match('/enc_[0-9a-z]+.key$/i', $file)) {
$parts = explode(' ', $file);
$file = end($parts);
$file = "/{$CDNObj->storage_username}/{$dir}/{$file}";
echo '******** Delete '.$file.PHP_EOL;
ftp_delete($conn_id[0], $file);
}
}
}

View file

@ -1,69 +1,67 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
error_reporting(E_ALL);
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = array();
foreach ($videos as $value) {
$count++;
//echo "{$count}/{$total} Checking {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
if (empty($value['sites_id'])) {
$countSiteIdEmpty++;
//echo "sites_id is not empty {$value['sites_id']}" . PHP_EOL;
continue;
}
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
//echo "The video status is not active {$value['status']}" . PHP_EOL;
continue;
}
$countMoved++;
$sites_id_to_move[] = $value['id'];
echo "{$key}/{$total} added to download {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
echo "{$key}/{$total} Start download {$value}" . PHP_EOL;
$startF = microtime(true);
//$response = CDNStorage::get($value, 10);
$response = CDNStorage::moveRemoteToLocal($value, false, false);
if(empty($response)){
echo "{$key}/{$total} ERROR " . PHP_EOL;
}else{
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} download done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
error_reporting(E_ALL);
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = [];
foreach ($videos as $value) {
$count++;
//echo "{$count}/{$total} Checking {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
if (empty($value['sites_id'])) {
$countSiteIdEmpty++;
//echo "sites_id is not empty {$value['sites_id']}" . PHP_EOL;
continue;
}
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
//echo "The video status is not active {$value['status']}" . PHP_EOL;
continue;
}
$countMoved++;
$sites_id_to_move[] = $value['id'];
echo "{$key}/{$total} added to download {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
echo "{$key}/{$total} Start download {$value}" . PHP_EOL;
$startF = microtime(true);
//$response = CDNStorage::get($value, 10);
$response = CDNStorage::moveRemoteToLocal($value, false, false);
if (empty($response)) {
echo "{$key}/{$total} ERROR " . PHP_EOL;
} else {
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} download done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();

View file

@ -1,84 +1,82 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$storages = array('https://storage.wetube.club/', 'https://storage1.wetube.club/');
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$videosDir = getVideosDir();
$errorsFound = 0;
foreach ($videos as $value) {
$count++;
$videos_id = $value['id'];
$list = CDNStorage::getLocalFolder($videos_id);
//echo "videos_id = {$videos_id} Files found " . count($list) . PHP_EOL;
$m3u8 = false;
$enckey = false;
foreach ($list as $file) {
if (is_array($file)) {
foreach ($file as $file2) {
if (preg_match('/index.m3u8$/', $file2)) {
$m3u8 = true;
} else if (preg_match('/enc.*.key$/', $file2)) {
$enckey = true;
}
}
} else {
if (preg_match('/index.m3u8$/', $file)) {
$m3u8 = true;
} else if (preg_match('/enc.*.key$/', $file)) {
$enckey = true;
}
}
}
if ($m3u8 && !$enckey) {
$errorsFound++;
//$video = Video::getVideoLight($value);
$paths = Video::getPaths($value['filename']);
echo "[$errorsFound] Missing enc key for video {$videos_id} {$paths['path']}" . PHP_EOL;
foreach ($storages as $s) {
$url = "{$s}tools/getenckey.json.php?folder={$value['filename']}";
echo "{$url}" . PHP_EOL;
$content = file_get_contents("{$s}tools/getenckey.json.php?folder={$value['filename']}");
if(!empty($content)){
$json = json_decode($content);
if(!empty($json->pathinfo)){
file_put_contents("{$paths['path']}missingkey", time());
file_put_contents("{$paths['path']}{$json->pathinfo->basename}", base64_decode($json->content));
echo "Saved from {$s} on {$paths['path']}{$json->pathinfo->basename}" . PHP_EOL;
break;
}
}
}
}
}
echo PHP_EOL . " Done! " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$storages = ['https://storage.wetube.club/', 'https://storage1.wetube.club/'];
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$videosDir = getVideosDir();
$errorsFound = 0;
foreach ($videos as $value) {
$count++;
$videos_id = $value['id'];
$list = CDNStorage::getLocalFolder($videos_id);
//echo "videos_id = {$videos_id} Files found " . count($list) . PHP_EOL;
$m3u8 = false;
$enckey = false;
foreach ($list as $file) {
if (is_array($file)) {
foreach ($file as $file2) {
if (preg_match('/index.m3u8$/', $file2)) {
$m3u8 = true;
} elseif (preg_match('/enc.*.key$/', $file2)) {
$enckey = true;
}
}
} else {
if (preg_match('/index.m3u8$/', $file)) {
$m3u8 = true;
} elseif (preg_match('/enc.*.key$/', $file)) {
$enckey = true;
}
}
}
if ($m3u8 && !$enckey) {
$errorsFound++;
//$video = Video::getVideoLight($value);
$paths = Video::getPaths($value['filename']);
echo "[$errorsFound] Missing enc key for video {$videos_id} {$paths['path']}" . PHP_EOL;
foreach ($storages as $s) {
$url = "{$s}tools/getenckey.json.php?folder={$value['filename']}";
echo "{$url}" . PHP_EOL;
$content = file_get_contents("{$s}tools/getenckey.json.php?folder={$value['filename']}");
if (!empty($content)) {
$json = json_decode($content);
if (!empty($json->pathinfo)) {
file_put_contents("{$paths['path']}missingkey", time());
file_put_contents("{$paths['path']}{$json->pathinfo->basename}", base64_decode($json->content));
echo "Saved from {$s} on {$paths['path']}{$json->pathinfo->basename}" . PHP_EOL;
break;
}
}
}
}
}
echo PHP_EOL . " Done! " . PHP_EOL;
die();

View file

@ -1,67 +1,65 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$index = intval(@$argv[1]);
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = array();
foreach ($videos as $value) {
$count++;
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
//echo "The video status is not active {$value['status']}" . PHP_EOL;
continue;
}
$countMoved++;
$sites_id_to_move[] = $value['id'];
echo "{$key}/{$total} added to move {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
if(!empty($index) && $key<$index){
continue;
}
echo "{$key}/{$total} Start move {$value} " . PHP_EOL;
$startF = microtime(true);
$response = CDNStorage::put($value, 4);
if(empty($response)){
echo "{$key}/{$total} ERROR " . PHP_EOL;
}else{
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} Moved done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdNotEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$index = intval(@$argv[1]);
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = [];
foreach ($videos as $value) {
$count++;
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
//echo "The video status is not active {$value['status']}" . PHP_EOL;
continue;
}
$countMoved++;
$sites_id_to_move[] = $value['id'];
echo "{$key}/{$total} added to move {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
if (!empty($index) && $key<$index) {
continue;
}
echo "{$key}/{$total} Start move {$value} " . PHP_EOL;
$startF = microtime(true);
$response = CDNStorage::put($value, 4);
if (empty($response)) {
echo "{$key}/{$total} ERROR " . PHP_EOL;
} else {
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} Moved done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdNotEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();

View file

@ -1,83 +1,81 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$videosDir = getVideosDir();
$errorsFound = array();
foreach ($videos as $value) {
$count++;
//echo "{$count}/{$total} Checking {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
if (empty($value['sites_id'])) {
echo "sites_id is empty {$value['id']} {$value['title']}" . PHP_EOL;
ob_flush();
continue;
}
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
echo "The video status is not active {$value['status']}" . PHP_EOL;
ob_flush();
continue;
}
echo "Checking {$value['id']} {$value['title']}" . PHP_EOL;
$videos_id = $value['id'];
$list = CDNStorage::getLocalFolder($videos_id);
echo "Files found ".count($list) . PHP_EOL;
echo "Errors found ".count($errorsFound) . PHP_EOL;
foreach ($list as $value) {
if(is_array($value)){
foreach ($value as $value2) {
if(preg_match('/index.m3u8$/', $value2)){
$remote_filename = str_replace($videosDir, '', $value2);
echo "Check {$value2}" . PHP_EOL;
$content = trim(CDNStorage::file_get_contents($remote_filename));
if($content=='Dummy File'){
$errorsFound[] = $value2;
//echo "Found ERROR {$value2}" . PHP_EOL;
}
}
}
}else{
if(preg_match('/index.m3u8$/', $value)){
$remote_filename = str_replace($videosDir, '', $value);
echo "Check {$value}" . PHP_EOL;
$content = trim(CDNStorage::file_get_contents($remote_filename));
if($content=='Dummy File'){
$errorsFound[] = $value;
//echo "Found ERROR {$value}" . PHP_EOL;
}
}
}
}
}
foreach ($errorsFound as $value) {
echo "*** ERROR {$value}" . PHP_EOL;
}
echo PHP_EOL . " Done! errorsFound = {$errorsFound} " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$videosDir = getVideosDir();
$errorsFound = [];
foreach ($videos as $value) {
$count++;
//echo "{$count}/{$total} Checking {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
if (empty($value['sites_id'])) {
echo "sites_id is empty {$value['id']} {$value['title']}" . PHP_EOL;
ob_flush();
continue;
}
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
echo "The video status is not active {$value['status']}" . PHP_EOL;
ob_flush();
continue;
}
echo "Checking {$value['id']} {$value['title']}" . PHP_EOL;
$videos_id = $value['id'];
$list = CDNStorage::getLocalFolder($videos_id);
echo "Files found ".count($list) . PHP_EOL;
echo "Errors found ".count($errorsFound) . PHP_EOL;
foreach ($list as $value) {
if (is_array($value)) {
foreach ($value as $value2) {
if (preg_match('/index.m3u8$/', $value2)) {
$remote_filename = str_replace($videosDir, '', $value2);
echo "Check {$value2}" . PHP_EOL;
$content = trim(CDNStorage::file_get_contents($remote_filename));
if ($content=='Dummy File') {
$errorsFound[] = $value2;
//echo "Found ERROR {$value2}" . PHP_EOL;
}
}
}
} else {
if (preg_match('/index.m3u8$/', $value)) {
$remote_filename = str_replace($videosDir, '', $value);
echo "Check {$value}" . PHP_EOL;
$content = trim(CDNStorage::file_get_contents($remote_filename));
if ($content=='Dummy File') {
$errorsFound[] = $value;
//echo "Found ERROR {$value}" . PHP_EOL;
}
}
}
}
}
foreach ($errorsFound as $value) {
echo "*** ERROR {$value}" . PHP_EOL;
}
echo PHP_EOL . " Done! errorsFound = {$errorsFound} " . PHP_EOL;
die();

View file

@ -1,8 +1,8 @@
<?php
$CDNObj = AVideoPlugin::getDataObject('CDN');
function getConnID($index) {
function getConnID($index)
{
global $conn_id, $CDNObj;
if (empty($conn_id[$index])) {
$conn_id[$index] = ftp_connect($CDNObj->storage_hostname);
@ -18,7 +18,8 @@ function getConnID($index) {
return $conn_id[$index];
}
function ftp_mlsd_recursive($ftp_stream, $directory) {
function ftp_mlsd_recursive($ftp_stream, $directory)
{
$result = [];
$files = ftp_mlsd($ftp_stream, $directory);
@ -31,7 +32,7 @@ function ftp_mlsd_recursive($ftp_stream, $directory) {
$filepath = $directory . "/" . $name;
if (($file["type"] == "cdir") || ($file["type"] == "pdir")) {
// noop
} else if ($file["type"] == "dir") {
} elseif ($file["type"] == "dir") {
$result = array_merge($result, ftp_mlsd_recursive($ftp_stream, $filepath));
} else {
$result[] = $filepath;

View file

@ -1,79 +1,77 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$onlyExtension = trim(@$argv[1]);
$index = intval(@$argv[2]);
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
ini_set('display_errors', '1');
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = array();
foreach ($videos as $value) {
$count++;
//echo "{$count}/{$total} Checking {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
if (!empty($value['sites_id'])) {
echo "sites_id is not empty {$value['sites_id']}" . PHP_EOL;
//CDNStorage::createDummyFiles($value['id']);
$countSiteIdNotEmpty++;
// make sure it is dummy files
//CDNStorage::createDummyFiles($value['id']);
continue;
}
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
//echo "The video status is not active {$value['status']}" . PHP_EOL;
continue;
}
$countMoved++;
$sites_id_to_move[] = $value['id'];
echo "{$key}/{$total} added to move {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
if(!empty($index) && $key<$index){
continue;
}
echo "{$key}/{$total} Start move {$value} onlyExtension={$onlyExtension}" . PHP_EOL;
$startF = microtime(true);
$response = CDNStorage::put($value, 4, $onlyExtension);
if(empty($response)){
echo "{$key}/{$total} ERROR " . PHP_EOL;
}else{
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} Moved done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdNotEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$onlyExtension = trim(@$argv[1]);
$index = intval(@$argv[2]);
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
ini_set('display_errors', '1');
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = [];
foreach ($videos as $value) {
$count++;
//echo "{$count}/{$total} Checking {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
if (!empty($value['sites_id'])) {
echo "sites_id is not empty {$value['sites_id']}" . PHP_EOL;
//CDNStorage::createDummyFiles($value['id']);
$countSiteIdNotEmpty++;
// make sure it is dummy files
//CDNStorage::createDummyFiles($value['id']);
continue;
}
if ($value['status'] !== Video::$statusActive) {
$countStatusNotActive++;
//echo "The video status is not active {$value['status']}" . PHP_EOL;
continue;
}
$countMoved++;
$sites_id_to_move[] = $value['id'];
echo "{$key}/{$total} added to move {$global['webSiteRootURL']}v/{$value['id']} {$value['title']}" . PHP_EOL;
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
if (!empty($index) && $key<$index) {
continue;
}
echo "{$key}/{$total} Start move {$value} onlyExtension={$onlyExtension}" . PHP_EOL;
$startF = microtime(true);
$response = CDNStorage::put($value, 4, $onlyExtension);
if (empty($response)) {
echo "{$key}/{$total} ERROR " . PHP_EOL;
} else {
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} Moved done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdNotEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();

View file

@ -1,81 +1,79 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$onlyExtension = trim(@$argv[1]);
$index = intval(@$argv[2]);
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = array();
foreach ($videos as $value) {
$count++;
$videos_id = $value['id'];
$list = CDNStorage::getLocalFolder($videos_id);
foreach ($list as $file) {
if (is_array($file)) {
foreach ($file as $file2) {
if (preg_match('/.mp4$/', $file2)) {
if (filesize($file2) > 20) {
$sites_id_to_move[] = $videos_id;
break 2;
}
}
}
} else {
if (preg_match('/.mp4$/', $file)) {
if (filesize($file) > 20) {
$sites_id_to_move[] = $videos_id;
break;
}
}
}
}
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
if (!empty($index) && $key < $index) {
continue;
}
echo "{$key}/{$total} Start move {$value}" . PHP_EOL;
$startF = microtime(true);
$response = CDNStorage::put($value, 2);
if (empty($response)) {
echo "{$key}/{$total} ERROR " . PHP_EOL;
} else {
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} Moved done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdNotEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
$onlyExtension = trim(@$argv[1]);
$index = intval(@$argv[2]);
ob_end_flush();
set_time_limit(300);
ini_set('max_execution_time', 300);
$global['rowCount'] = $global['limitForUnlimitedVideos'] = 999999;
$path = getVideosDir();
$total = Video::getTotalVideos("", false, true, true, false, false);
$videos = Video::getAllVideosLight("", false, true, false);
$count = 0;
$countSiteIdNotEmpty = 0;
$countStatusNotActive = 0;
$countMoved = 0;
$sites_id_to_move = [];
foreach ($videos as $value) {
$count++;
$videos_id = $value['id'];
$list = CDNStorage::getLocalFolder($videos_id);
foreach ($list as $file) {
if (is_array($file)) {
foreach ($file as $file2) {
if (preg_match('/.mp4$/', $file2)) {
if (filesize($file2) > 20) {
$sites_id_to_move[] = $videos_id;
break 2;
}
}
}
} else {
if (preg_match('/.mp4$/', $file)) {
if (filesize($file) > 20) {
$sites_id_to_move[] = $videos_id;
break;
}
}
}
}
}
$total = count($sites_id_to_move);
foreach ($sites_id_to_move as $key => $value) {
if (!empty($index) && $key < $index) {
continue;
}
echo "{$key}/{$total} Start move {$value}" . PHP_EOL;
$startF = microtime(true);
$response = CDNStorage::put($value, 2);
if (empty($response)) {
echo "{$key}/{$total} ERROR " . PHP_EOL;
} else {
$endF = microtime(true) - $startF;
$ETA = ($total - $key + 1) * $endF;
$ps = humanFileSize($response['totalBytesTransferred'] / ($endF));
echo "{$key}/{$total} Moved done {$value} filesCopied={$response['filesCopied']} totalBytesTransferred=" . humanFileSize($response['totalBytesTransferred']) . " in " . secondsToDuration($endF) . " ETA: " . secondsToDuration($ETA) . " " . $ps . 'ps' . PHP_EOL;
}
}
echo "SiteIdNotEmpty = $countSiteIdNotEmpty; StatusNotActive=$countStatusNotActive; Moved=$countMoved;" . PHP_EOL;
echo PHP_EOL . " Done! " . PHP_EOL;
die();

View file

@ -1,55 +1,53 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
ob_end_flush();
set_time_limit(1800);
ini_set('max_execution_time', 1800);
error_reporting(E_ALL);
ini_set('display_errors', '1');
$sql = "SELECT * FROM videos WHERE 1=1 ORDER BY id DESC ";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
if ($row['status'] === Video::$statusActive) {
exec("rm /var/www/html/AVideo/videos/{$row['filename']}/*.tgz");
$localList = CDNStorage::getFilesListLocal($row['id'], false);
$last = end($localList);
if(empty($last)){
continue;
}
if($last['acumulativeFilesize']<10000){
//echo "SKIP videos_id = {$row['id']} sites_id is not empty {$row['sites_id']} [{$last['acumulativeFilesize']}] ".humanFileSize($last['acumulativeFilesize']) . PHP_EOL;
}else{
if(CDNStorage::isMoving($row['id'])){
echo "videos_id = {$row['id']} {$row['title']} Is moving ". PHP_EOL;
}else{
echo "videos_id = {$row['id']} {$row['title']} sites_id is not empty {$row['sites_id']} [{$last['acumulativeFilesize']}] ".humanFileSize($last['acumulativeFilesize']) . PHP_EOL;
CDNStorage::put($row['id'], 4);
//CDNStorage::createDummyFiles($row['id']);
}
}
}
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
echo PHP_EOL . " Done! " . PHP_EOL;
die();
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
if (!isCommandLineInterface()) {
return die('Command Line only');
}
$isCDNEnabled = AVideoPlugin::isEnabledByName('CDN');
if (empty($isCDNEnabled)) {
return die('Plugin disabled');
}
ob_end_flush();
set_time_limit(1800);
ini_set('max_execution_time', 1800);
error_reporting(E_ALL);
ini_set('display_errors', '1');
$sql = "SELECT * FROM videos WHERE 1=1 ORDER BY id DESC ";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
if ($row['status'] === Video::$statusActive) {
exec("rm /var/www/html/AVideo/videos/{$row['filename']}/*.tgz");
$localList = CDNStorage::getFilesListLocal($row['id'], false);
$last = end($localList);
if (empty($last)) {
continue;
}
if ($last['acumulativeFilesize']<10000) {
//echo "SKIP videos_id = {$row['id']} sites_id is not empty {$row['sites_id']} [{$last['acumulativeFilesize']}] ".humanFileSize($last['acumulativeFilesize']) . PHP_EOL;
} else {
if (CDNStorage::isMoving($row['id'])) {
echo "videos_id = {$row['id']} {$row['title']} Is moving ". PHP_EOL;
} else {
echo "videos_id = {$row['id']} {$row['title']} sites_id is not empty {$row['sites_id']} [{$last['acumulativeFilesize']}] ".humanFileSize($last['acumulativeFilesize']) . PHP_EOL;
CDNStorage::put($row['id'], 4);
//CDNStorage::createDummyFiles($row['id']);
}
}
}
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
echo PHP_EOL . " Done! " . PHP_EOL;
die();

View file

@ -1,385 +1,408 @@
<?php
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/Cache/Objects/CachesInDB.php';
class Cache extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$RECOMMENDED,
PluginTags::$FREE
);
}
public function getDescription() {
global $global;
$txt = "AVideo application accelerator to cache pages.<br>Your website has 10,000 visitors who are online, and your dynamic page has to send 10,000 times the same queries to database on every page load. With this plugin, your page only sends 1 query to your DB, and uses the cache to serve the 9,999 other visitors.";
$txt .= "<br>To auto delete the old cache files you can use this crontab command <code>0 2 * * * php {$global['systemRootPath']}plugin/Cache/crontab.php</code> this will delete cache files that are 3 days old everyday at 2 AM";
$help = "<br><small><a href='https://github.com/WWBN/AVideo/wiki/Cache-Plugin' target='__blank'><i class='fas fa-question-circle'></i> Help</a></small>";
return $txt . $help;
}
public function getName() {
return "Cache";
}
public function getUUID() {
return "10573225-3807-4167-ba81-0509dd280e06";
}
public function getPluginVersion() {
return "2.0";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->enableCachePerUser = false;
$obj->enableCacheForLoggedUsers = false;
$obj->cacheTimeInSeconds = 600;
$obj->cacheDir = $global['systemRootPath'] . 'videos/cache/';
$obj->logPageLoadTime = false;
$obj->stopBotsFromNonCachedPages = false;
$obj->deleteStatisticsDaysOld = 180; // 6 months
return $obj;
}
public function getCacheDir($ignoreFirstPage = true) {
global $global;
$obj = $this->getDataObject();
if (!$ignoreFirstPage && $this->isFirstPage()) {
$obj->cacheDir .= "firstPage" . DIRECTORY_SEPARATOR;
}
if (User::isLogged()) {
if (User::isAdmin()) {
$obj->cacheDir .= 'admin_' . md5("admin" . $global['salt']) . DIRECTORY_SEPARATOR;
} else {
$obj->cacheDir .= 'user_' . md5("user" . $global['salt']) . DIRECTORY_SEPARATOR;
}
} else {
$obj->cacheDir .= 'notlogged_' . md5("notlogged" . $global['salt']) . DIRECTORY_SEPARATOR;
}
$obj->cacheDir = fixPath($obj->cacheDir, true);
if (!file_exists($obj->cacheDir)) {
$obj->cacheDir = $global['systemRootPath'] . 'videos' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
$this->setDataObject($obj);
if (!file_exists($obj->cacheDir)) {
mkdir($obj->cacheDir, 0777, true);
}
}
return $obj->cacheDir;
}
private function getFileName() {
if (empty($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = "";
}
$obj = $this->getDataObject();
$session_id = "";
if (!empty($obj->enableCachePerUser)) {
$session_id = session_id();
}
$compl = "";
if (!empty($_SERVER['HTTP_USER_AGENT']) && get_browser_name($_SERVER['HTTP_USER_AGENT']) === 'Safari') {
$compl .= "safari_";
}
$dir = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('User_Location');
if (!empty($plugin)) {
$location = User_Location::getThisUserLocation();
if (!empty($location['country_code'])) {
$dir = $location['country_code'] . "/";
}
}
return $dir . User::getId() . "_{$compl}" . md5(@$_SESSION['channelName'] . $_SERVER['REQUEST_URI'] . $_SERVER['HTTP_HOST']) . "_" . $session_id . "_" . (!empty($_SERVER['HTTPS']) ? 'a' : '') . (@$_SESSION['language']) . '.cache';
}
private function isFirstPage() {
return isFirstPage();
}
public function getStart() {
global $global;
// ignore cache if it is command line
//var_dump($this->isFirstPage());exit;
$obj = $this->getDataObject();
if ($obj->logPageLoadTime) {
$this->start();
}
if (isCommandLineInterface()) {
return true;
}
$whitelistedFiles = array('user.php', 'status.php', 'canWatchVideo.json.php', '/login', '/status');
$blacklistedFiles = array('videosAndroid.json.php');
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
if (getVideos_id() || isVideo() || isLive() || isLiveLink() || in_array($baseName, $whitelistedFiles) || in_array($_SERVER['REQUEST_URI'], $whitelistedFiles)) {
return true;
}
$isBot = isBot();
if ($this->isBlacklisted() || $this->isFirstPage() || !class_exists('User') || !User::isLogged() || !empty($obj->enableCacheForLoggedUsers)) {
$cacheName = $this->getFileName();
if($this->isFirstPage()){
$cacheName = 'firstPage' . DIRECTORY_SEPARATOR . $cacheName;
}
$lifetime = $obj->cacheTimeInSeconds;
if ($isBot && $lifetime < 3600) {
$lifetime = 3600;
}
$firstPageCache = ObjectYPT::getCache($cacheName, $lifetime, true);
if (!empty($firstPageCache) && strtolower($firstPageCache) != 'false') {
if ($isBot && $_SERVER['REQUEST_URI'] !== '/login') {
//_error_log("Bot Detected, showing the cache ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
}
//$c = @local_get_contents($cachefile);
if (preg_match("/\.json\.?/", $baseName)) {
header('Content-Type: application/json');
}
if ($isBot) {
$firstPageCache = strip_specific_tags($firstPageCache);
$firstPageCache = strip_render_blocking_resources($firstPageCache);
} else {
$firstPageCache = optimizeHTMLTags($firstPageCache);
}
echo $firstPageCache . PHP_EOL . '<!-- Cached Page Generated in ' . getScriptRunMicrotimeInSeconds() . ' Seconds -->';
if ($obj->logPageLoadTime) {
$this->end("Cache");
}
exit;
}
}
if ($isBot && !self::isREQUEST_URIWhitelisted() && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$_SERVER['HTTP_USER_AGENT'] = "";
}
//_error_log("Bot Detected, NOT showing the cache ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
if ($obj->stopBotsFromNonCachedPages) {
_error_log("Bot stopped ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
exit;
}
}
//ob_start('sanitize_output');
ob_start();
}
public function getEnd() {
global $global;
$obj = $this->getDataObject();
echo PHP_EOL . '<!-- Page Generated in ' . getScriptRunMicrotimeInSeconds() . ' Seconds -->';
$c = ob_get_clean();
$c = optimizeHTMLTags($c);
ob_start();
echo $c;
if (!headers_sent()) {
header_remove('Set-Cookie');
}
/*
if (!file_exists($this->getCacheDir())) {
mkdir($this->getCacheDir(), 0777, true);
}
*
*/
if ($this->isBlacklisted() || $this->isFirstPage() || !class_exists('User') || !User::isLogged() || !empty($obj->enableCacheForLoggedUsers)) {
$cacheName = $this->getFileName();
if($this->isFirstPage()){
$cacheName = 'firstPage' . DIRECTORY_SEPARATOR . $cacheName;
}
$c = preg_replace('/<script id="infoForNonCachedPages">[^<]+<\/script>/', '', $c);
$r = ObjectYPT::setCache($cacheName, $c);
//var_dump($r);
}
if ($obj->logPageLoadTime) {
$this->end();
}
}
private function isREQUEST_URIWhitelisted() {
$cacheBotWhitelist = array(
'aVideoEncoder',
'plugin/Live/on_',
'plugin/YPTStorage',
'/login',
'restreamer.json.php',
'plugin/API',
'/info?version=',
'Meet',
'/roku.json',
'mrss',
'/sitemap.xml',
'plugin/Live/verifyToken.json.php',
'control.json.php');
foreach ($cacheBotWhitelist as $value) {
if (strpos($_SERVER['REQUEST_URI'], $value) !== false) {
_error_log("Cache::isREQUEST_URIWhitelisted: ($value) is whitelisted");
return true;
}
}
return false;
}
private function isBlacklisted() {
$blacklistedFiles = array('videosAndroid.json.php');
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
return in_array($baseName, $blacklistedFiles);
}
private function start() {
global $global;
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$global['cachePluginStart'] = $time;
}
private function end($type = "No Cache") {
global $global;
if (empty($global['cachePluginStart'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
if (User::isLogged()) {
$type = "User: " . User::getUserName() . " - " . $type;
} else {
$type = "User: Not Logged - " . $type;
}
$t = (floatval($finish) - floatval($global['cachePluginStart']));
$total_time = round($t, 4);
_error_log("Page generated in {$total_time} seconds. {$type} ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
}
public function getPluginMenu() {
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/Cache/pluginMenu.html';
$content = file_get_contents($fileAPIName);
return $content;
}
public function getFooterCode() {
global $global;
if (preg_match('/managerPlugins.php$/', $_SERVER["SCRIPT_FILENAME"])) {
return "<script src=\"{$global['webSiteRootURL']}plugin/Cache/pluginMenu.js\"></script>";
}
}
public static function getCacheMetaData(){
global $_getCacheMetaData;
if(!empty($_getCacheMetaData)){
return $_getCacheMetaData;
}
$domain = getDomain();
$ishttps = isset($_SERVER["HTTPS"]) ? 1 : 0;
$user_location = 'undefined';
if (class_exists("User_Location")) {
$loc = User_Location::getThisUserLocation();
if (!empty($loc) && !empty($loc['country_code']) && $loc['country_code'] != '-') {
$user_location = $loc['country_code'];
}
}
$loggedType = CachesInDB::$loggedType_NOT_LOGGED;
if (User::isLogged()) {
if (User::isAdmin()) {
$loggedType = CachesInDB::$loggedType_ADMIN;
} else {
$loggedType = CachesInDB::$loggedType_LOGGED;
}
}
$_getCacheMetaData = array('domain'=>$domain, 'ishttps'=>$ishttps, 'user_location'=>$user_location, 'loggedType'=>$loggedType);
return $_getCacheMetaData;
}
public static function _getCache($name){
$metadata = self::getCacheMetaData();
return CachesInDB::_getCache($name, $metadata['domain'], $metadata['ishttps'], $metadata['user_location'], $metadata['loggedType']);
}
public static function _setCache($name, $value) {
$metadata = self::getCacheMetaData();
return CachesInDB::_setCache($name, $value, $metadata['domain'], $metadata['ishttps'], $metadata['user_location'], $metadata['loggedType']);
}
public static function getCache($name, $lifetime = 60) {
global $_getCacheDB, $global;
if(!empty($global['ignoreAllCache'])){
return null;
}
if(!isset($_getCacheDB)){
$_getCacheDB = array();
}
$index = "{$name}_{$lifetime}";
if(empty($_getCacheDB[$index])){
$_getCacheDB[$index] = null;
$metadata = self::getCacheMetaData();
$row = CachesInDB::_getCache($name, $metadata['domain'], $metadata['ishttps'], $metadata['user_location'], $metadata['loggedType']);
if (!empty($row)) {
$time = getTimeInTimezone(strtotime($row['modified']), $row['timezone']);
if (!empty($lifetime) && ($time + $lifetime) < time()) {
$c = new CachesInDB($row['id']);
$c->delete();
}else{
$_getCacheDB[$index] = _json_decode($row['content']);
}
}
}
return $_getCacheDB[$index];
}
public static function deleteCache($name) {
return CachesInDB::_deleteCache($name);
}
public static function deleteAllCache() {
return CachesInDB::_deleteAllCache();
}
public static function deleteFirstPageCache() {
clearCache(true);
return CachesInDB::_deleteCacheStartingWith('firstPage');
}
}
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/' // Remove HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$len = strlen($buffer);
if ($len) {
_error_log("Before Sanitize: " . strlen($buffer));
$buffer = preg_replace($search, $replace, $buffer);
$lenAfter = strlen($buffer);
_error_log("After Sanitize: {$lenAfter} = " . (($len / $lenAfter) * 100) . "%");
}
return $buffer;
}
<?php
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/Cache/Objects/CachesInDB.php';
class Cache extends PluginAbstract
{
public function getTags()
{
return [
PluginTags::$RECOMMENDED,
PluginTags::$FREE,
];
}
public function getDescription()
{
global $global;
$txt = "AVideo application accelerator to cache pages.<br>Your website has 10,000 visitors who are online, and your dynamic page has to send 10,000 times the same queries to database on every page load. With this plugin, your page only sends 1 query to your DB, and uses the cache to serve the 9,999 other visitors.";
$txt .= "<br>To auto delete the old cache files you can use this crontab command <code>0 2 * * * php {$global['systemRootPath']}plugin/Cache/crontab.php</code> this will delete cache files that are 3 days old everyday at 2 AM";
$help = "<br><small><a href='https://github.com/WWBN/AVideo/wiki/Cache-Plugin' target='__blank'><i class='fas fa-question-circle'></i> Help</a></small>";
return $txt . $help;
}
public function getName()
{
return "Cache";
}
public function getUUID()
{
return "10573225-3807-4167-ba81-0509dd280e06";
}
public function getPluginVersion()
{
return "2.0";
}
public function getEmptyDataObject()
{
global $global;
$obj = new stdClass();
$obj->enableCachePerUser = false;
$obj->enableCacheForLoggedUsers = false;
$obj->cacheTimeInSeconds = 600;
$obj->cacheDir = $global['systemRootPath'] . 'videos/cache/';
$obj->logPageLoadTime = false;
$obj->stopBotsFromNonCachedPages = false;
$obj->deleteStatisticsDaysOld = 180; // 6 months
return $obj;
}
public function getCacheDir($ignoreFirstPage = true)
{
global $global;
$obj = $this->getDataObject();
if (!$ignoreFirstPage && $this->isFirstPage()) {
$obj->cacheDir .= "firstPage" . DIRECTORY_SEPARATOR;
}
if (User::isLogged()) {
if (User::isAdmin()) {
$obj->cacheDir .= 'admin_' . md5("admin" . $global['salt']) . DIRECTORY_SEPARATOR;
} else {
$obj->cacheDir .= 'user_' . md5("user" . $global['salt']) . DIRECTORY_SEPARATOR;
}
} else {
$obj->cacheDir .= 'notlogged_' . md5("notlogged" . $global['salt']) . DIRECTORY_SEPARATOR;
}
$obj->cacheDir = fixPath($obj->cacheDir, true);
if (!file_exists($obj->cacheDir)) {
$obj->cacheDir = $global['systemRootPath'] . 'videos' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
$this->setDataObject($obj);
if (!file_exists($obj->cacheDir)) {
mkdir($obj->cacheDir, 0777, true);
}
}
return $obj->cacheDir;
}
private function getFileName()
{
if (empty($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = "";
}
$obj = $this->getDataObject();
$session_id = "";
if (!empty($obj->enableCachePerUser)) {
$session_id = session_id();
}
$compl = "";
if (!empty($_SERVER['HTTP_USER_AGENT']) && get_browser_name($_SERVER['HTTP_USER_AGENT']) === 'Safari') {
$compl .= "safari_";
}
$dir = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('User_Location');
if (!empty($plugin)) {
$location = User_Location::getThisUserLocation();
if (!empty($location['country_code'])) {
$dir = $location['country_code'] . "/";
}
}
return $dir . User::getId() . "_{$compl}" . md5(@$_SESSION['channelName'] . $_SERVER['REQUEST_URI'] . $_SERVER['HTTP_HOST']) . "_" . $session_id . "_" . (!empty($_SERVER['HTTPS']) ? 'a' : '') . (@$_SESSION['language']) . '.cache';
}
private function isFirstPage()
{
return isFirstPage();
}
public function getStart()
{
global $global;
// ignore cache if it is command line
//var_dump($this->isFirstPage());exit;
$obj = $this->getDataObject();
if ($obj->logPageLoadTime) {
$this->start();
}
if (isCommandLineInterface()) {
return true;
}
$whitelistedFiles = ['user.php', 'status.php', 'canWatchVideo.json.php', '/login', '/status'];
$blacklistedFiles = ['videosAndroid.json.php'];
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
if (getVideos_id() || isVideo() || isLive() || isLiveLink() || in_array($baseName, $whitelistedFiles) || in_array($_SERVER['REQUEST_URI'], $whitelistedFiles)) {
return true;
}
$isBot = isBot();
if ($this->isBlacklisted() || $this->isFirstPage() || !class_exists('User') || !User::isLogged() || !empty($obj->enableCacheForLoggedUsers)) {
$cacheName = $this->getFileName();
if ($this->isFirstPage()) {
$cacheName = 'firstPage' . DIRECTORY_SEPARATOR . $cacheName;
}
$lifetime = $obj->cacheTimeInSeconds;
if ($isBot && $lifetime < 3600) {
$lifetime = 3600;
}
$firstPageCache = ObjectYPT::getCache($cacheName, $lifetime, true);
if (!empty($firstPageCache) && strtolower($firstPageCache) != 'false') {
if ($isBot && $_SERVER['REQUEST_URI'] !== '/login') {
//_error_log("Bot Detected, showing the cache ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
}
//$c = @local_get_contents($cachefile);
if (preg_match("/\.json\.?/", $baseName)) {
header('Content-Type: application/json');
}
if ($isBot) {
$firstPageCache = strip_specific_tags($firstPageCache);
$firstPageCache = strip_render_blocking_resources($firstPageCache);
} else {
$firstPageCache = optimizeHTMLTags($firstPageCache);
}
echo $firstPageCache . PHP_EOL . '<!-- Cached Page Generated in ' . getScriptRunMicrotimeInSeconds() . ' Seconds -->';
if ($obj->logPageLoadTime) {
$this->end("Cache");
}
exit;
}
}
if ($isBot && !self::isREQUEST_URIWhitelisted() && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$_SERVER['HTTP_USER_AGENT'] = "";
}
//_error_log("Bot Detected, NOT showing the cache ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
if ($obj->stopBotsFromNonCachedPages) {
_error_log("Bot stopped ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
exit;
}
}
//ob_start('sanitize_output');
ob_start();
}
public function getEnd()
{
global $global;
$obj = $this->getDataObject();
echo PHP_EOL . '<!-- Page Generated in ' . getScriptRunMicrotimeInSeconds() . ' Seconds -->';
$c = ob_get_clean();
$c = optimizeHTMLTags($c);
ob_start();
echo $c;
if (!headers_sent()) {
header_remove('Set-Cookie');
}
/*
if (!file_exists($this->getCacheDir())) {
mkdir($this->getCacheDir(), 0777, true);
}
*
*/
if ($this->isBlacklisted() || $this->isFirstPage() || !class_exists('User') || !User::isLogged() || !empty($obj->enableCacheForLoggedUsers)) {
$cacheName = $this->getFileName();
if ($this->isFirstPage()) {
$cacheName = 'firstPage' . DIRECTORY_SEPARATOR . $cacheName;
}
$c = preg_replace('/<script id="infoForNonCachedPages">[^<]+<\/script>/', '', $c);
$r = ObjectYPT::setCache($cacheName, $c);
//var_dump($r);
}
if ($obj->logPageLoadTime) {
$this->end();
}
}
private function isREQUEST_URIWhitelisted()
{
$cacheBotWhitelist = [
'aVideoEncoder',
'plugin/Live/on_',
'plugin/YPTStorage',
'/login',
'restreamer.json.php',
'plugin/API',
'/info?version=',
'Meet',
'/roku.json',
'mrss',
'/sitemap.xml',
'plugin/Live/verifyToken.json.php',
'control.json.php', ];
foreach ($cacheBotWhitelist as $value) {
if (strpos($_SERVER['REQUEST_URI'], $value) !== false) {
_error_log("Cache::isREQUEST_URIWhitelisted: ($value) is whitelisted");
return true;
}
}
return false;
}
private function isBlacklisted()
{
$blacklistedFiles = ['videosAndroid.json.php'];
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
return in_array($baseName, $blacklistedFiles);
}
private function start()
{
global $global;
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$global['cachePluginStart'] = $time;
}
private function end($type = "No Cache")
{
global $global;
if (empty($global['cachePluginStart'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
if (User::isLogged()) {
$type = "User: " . User::getUserName() . " - " . $type;
} else {
$type = "User: Not Logged - " . $type;
}
$t = (floatval($finish) - floatval($global['cachePluginStart']));
$total_time = round($t, 4);
_error_log("Page generated in {$total_time} seconds. {$type} ({$_SERVER['REQUEST_URI']}) FROM: {$_SERVER['REMOTE_ADDR']} Browser: {$_SERVER['HTTP_USER_AGENT']}");
}
public function getPluginMenu()
{
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/Cache/pluginMenu.html';
$content = file_get_contents($fileAPIName);
return $content;
}
public function getFooterCode()
{
global $global;
if (preg_match('/managerPlugins.php$/', $_SERVER["SCRIPT_FILENAME"])) {
return "<script src=\"{$global['webSiteRootURL']}plugin/Cache/pluginMenu.js\"></script>";
}
}
public static function getCacheMetaData()
{
global $_getCacheMetaData;
if (!empty($_getCacheMetaData)) {
return $_getCacheMetaData;
}
$domain = getDomain();
$ishttps = isset($_SERVER["HTTPS"]) ? 1 : 0;
$user_location = 'undefined';
if (class_exists("User_Location")) {
$loc = User_Location::getThisUserLocation();
if (!empty($loc) && !empty($loc['country_code']) && $loc['country_code'] != '-') {
$user_location = $loc['country_code'];
}
}
$loggedType = CachesInDB::$loggedType_NOT_LOGGED;
if (User::isLogged()) {
if (User::isAdmin()) {
$loggedType = CachesInDB::$loggedType_ADMIN;
} else {
$loggedType = CachesInDB::$loggedType_LOGGED;
}
}
$_getCacheMetaData = ['domain'=>$domain, 'ishttps'=>$ishttps, 'user_location'=>$user_location, 'loggedType'=>$loggedType];
return $_getCacheMetaData;
}
public static function _getCache($name)
{
$metadata = self::getCacheMetaData();
return CachesInDB::_getCache($name, $metadata['domain'], $metadata['ishttps'], $metadata['user_location'], $metadata['loggedType']);
}
public static function _setCache($name, $value)
{
$metadata = self::getCacheMetaData();
return CachesInDB::_setCache($name, $value, $metadata['domain'], $metadata['ishttps'], $metadata['user_location'], $metadata['loggedType']);
}
public static function getCache($name, $lifetime = 60)
{
global $_getCacheDB, $global;
if (!empty($global['ignoreAllCache'])) {
return null;
}
if (!isset($_getCacheDB)) {
$_getCacheDB = [];
}
$index = "{$name}_{$lifetime}";
if (empty($_getCacheDB[$index])) {
$_getCacheDB[$index] = null;
$metadata = self::getCacheMetaData();
$row = CachesInDB::_getCache($name, $metadata['domain'], $metadata['ishttps'], $metadata['user_location'], $metadata['loggedType']);
if (!empty($row)) {
$time = getTimeInTimezone(strtotime($row['modified']), $row['timezone']);
if (!empty($lifetime) && ($time + $lifetime) < time()) {
$c = new CachesInDB($row['id']);
$c->delete();
} else {
$_getCacheDB[$index] = _json_decode($row['content']);
}
}
}
return $_getCacheDB[$index];
}
public static function deleteCache($name)
{
return CachesInDB::_deleteCache($name);
}
public static function deleteAllCache()
{
return CachesInDB::_deleteAllCache();
}
public static function deleteFirstPageCache()
{
clearCache(true);
return CachesInDB::_deleteCacheStartingWith('firstPage');
}
}
function sanitize_output($buffer)
{
$search = [
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/', // Remove HTML comments
];
$replace = [
'>',
'<',
'\\1',
'',
];
$len = strlen($buffer);
if ($len) {
_error_log("Before Sanitize: " . strlen($buffer));
$buffer = preg_replace($search, $replace, $buffer);
$lenAfter = strlen($buffer);
_error_log("After Sanitize: {$lenAfter} = " . (($len / $lenAfter) * 100) . "%");
}
return $buffer;
}

View file

@ -2,105 +2,134 @@
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class CachesInDB extends ObjectYPT {
class CachesInDB extends ObjectYPT
{
public static $loggedType_NOT_LOGGED = 'n';
public static $loggedType_LOGGED = 'l';
public static $loggedType_ADMIN = 'a';
public static $prefix = 'ypt_cache_';
protected $id;
protected $content;
protected $domain;
protected $ishttps;
protected $loggedType;
protected $user_location;
protected $expires;
protected $timezone;
protected $name;
static $loggedType_NOT_LOGGED = 'n';
static $loggedType_LOGGED = 'l';
static $loggedType_ADMIN = 'a';
static $prefix = 'ypt_cache_';
protected $id, $content, $domain, $ishttps, $loggedType, $user_location, $expires, $timezone, $name;
static function getSearchFieldsNames() {
return array('domain', 'ishttps', 'user_location', 'timezone', 'name');
public static function getSearchFieldsNames()
{
return ['domain', 'ishttps', 'user_location', 'timezone', 'name'];
}
static function getTableName() {
public static function getTableName()
{
return 'CachesInDB';
}
function setId($id) {
public function setId($id)
{
$this->id = intval($id);
}
function setContent($content) {
public function setContent($content)
{
$content = self::encodeContent($content);
$this->content = $content;
}
function setDomain($domain) {
public function setDomain($domain)
{
$this->domain = $domain;
}
function setIshttps($ishttps) {
public function setIshttps($ishttps)
{
$this->ishttps = $ishttps;
}
function setLoggedType($loggedType) {
public function setLoggedType($loggedType)
{
$this->loggedType = $loggedType;
}
function setUser_location($user_location) {
public function setUser_location($user_location)
{
$this->user_location = $user_location;
}
function setExpires($expires) {
public function setExpires($expires)
{
$this->expires = $expires;
}
function setTimezone($timezone) {
public function setTimezone($timezone)
{
$this->timezone = $timezone;
}
function setName($name) {
public function setName($name)
{
$this->name = $name;
}
function getId() {
public function getId()
{
return intval($this->id);
}
function getContent() {
public function getContent()
{
$this->content = self::decodeContent($this->content);
return $this->content;
}
function getDomain() {
public function getDomain()
{
return $this->domain;
}
function getIshttps() {
public function getIshttps()
{
return $this->ishttps;
}
function getLoggedType() {
public function getLoggedType()
{
return $this->loggedType;
}
function getUser_location() {
public function getUser_location()
{
return $this->user_location;
}
function getExpires() {
public function getExpires()
{
return $this->expires;
}
function getTimezone() {
public function getTimezone()
{
return $this->timezone;
}
function getName() {
public function getName()
{
return $this->name;
}
static function _getCache($name, $domain, $ishttps, $user_location, $loggedType) {
public static function _getCache($name, $domain, $ishttps, $user_location, $loggedType)
{
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE ishttps = ? AND loggedType = ? AND name = ? AND domain = ? AND user_location = ? 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, "issss", array($ishttps, $loggedType, $name, $domain, $user_location), true);
$res = sqlDAL::readSql($sql, "issss", [$ishttps, $loggedType, $name, $domain, $user_location], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
if(!empty($data) && !empty($data['content'])){
if (!empty($data) && !empty($data['content'])) {
$data['content'] = self::decodeContent($data['content']);
}
$row = $data;
@ -110,14 +139,15 @@ class CachesInDB extends ObjectYPT {
return $row;
}
public static function _setCache($name, $value, $domain, $ishttps, $user_location, $loggedType) {
if(!is_string($value)){
public static function _setCache($name, $value, $domain, $ishttps, $user_location, $loggedType)
{
if (!is_string($value)) {
$value = _json_encode($value);
}
if(empty($value)){
if (empty($value)) {
return false;
}
$row = self::_getCache($name, $domain, $ishttps, $user_location, $loggedType);
if (!empty($row)) {
$c = new CachesInDB($row['id']);
@ -134,21 +164,23 @@ class CachesInDB extends ObjectYPT {
return $c->save();
}
public static function _deleteCache($name) {
public static function _deleteCache($name)
{
global $global;
if(empty($name)){
if (empty($name)) {
return false;
}
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE name = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "s", array($name));
return sqlDAL::writeSql($sql, "s", [$name]);
}
public static function _deleteCacheStartingWith($name) {
public static function _deleteCacheStartingWith($name)
{
global $global;
if(empty($name)){
if (empty($name)) {
return false;
}
$sql = "DELETE FROM " . static::getTableName() . " ";
@ -158,33 +190,35 @@ class CachesInDB extends ObjectYPT {
return sqlDAL::writeSql($sql);
}
public static function _deleteAllCache() {
public static function _deleteAllCache()
{
global $global;
$sql = "TRUNCATE TABLE " . static::getTableName() . " ";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql);
}
public static function encodeContent($content){
if(!is_string($content)){
public static function encodeContent($content)
{
if (!is_string($content)) {
$content = _json_encode($content);
}
$prefix = substr($content, 0, 10);
if($prefix!== CachesInDB::$prefix){
if ($prefix!== CachesInDB::$prefix) {
$base64 = base64_encode($content);
$content = CachesInDB::$prefix.$base64;
}
return $content;
}
public static function decodeContent($content){
public static function decodeContent($content)
{
$prefix = substr($content, 0, 10);
if($prefix === CachesInDB::$prefix){
if ($prefix === CachesInDB::$prefix) {
$content = str_replace(CachesInDB::$prefix, '', $content);
$content = base64_decode($content);
}
return $content;
}
}

View file

@ -10,7 +10,7 @@ $daysLimit = 3;
// delete object cache
$cacheDir = ObjectYPT::getCacheDir();
if(empty($cacheDir) || !preg_match('/YPTObjectCache/', $cacheDir)){
if (empty($cacheDir) || !preg_match('/YPTObjectCache/', $cacheDir)) {
die('Wrong dir: '.$cacheDir);
}
_error_log('crontab.php: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
@ -22,11 +22,11 @@ exec($cmd);
//delete site cache
$cacheDir = getCacheDir();
if(empty($cacheDir) || !preg_match('/cache/', $cacheDir)){
if (empty($cacheDir) || !preg_match('/cache/', $cacheDir)) {
die('Wrong dir: '.$cacheDir);
}
echo "deleting {$cacheDir}".PHP_EOL;
// delete caches 3 days old
$cmd = "find {$cacheDir}* -mtime +{$daysLimit} -type f -name \"*.cache\" -exec rm {} \;".PHP_EOL;
echo "Command: {$cmd}";
exec($cmd);
exec($cmd);

View file

@ -1,31 +1,30 @@
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$obj->result = "";
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
require_once $global['systemRootPath'] . 'objects/video_statistic.php';
$objC = AVideoPlugin::getDataObject('Cache');
$days = $objC->deleteStatisticsDaysOld;
if(empty($days)){
$days = 180;
}
$obj->before = VideoStatistic::getTotalStatisticsRecords();
$obj->result = VideoStatistic::deleteOldStatistics($days);
$obj->after = VideoStatistic::getTotalStatisticsRecords();
$obj->error = empty($obj->result);
$obj->msg = "you had ". number_format($obj->before, 0)." statistics records and removed ". number_format($obj->before-$obj->after, 0)." now you have ". number_format($obj->after, 0);
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$obj->result = "";
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
require_once $global['systemRootPath'] . 'objects/video_statistic.php';
$objC = AVideoPlugin::getDataObject('Cache');
$days = $objC->deleteStatisticsDaysOld;
if (empty($days)) {
$days = 180;
}
$obj->before = VideoStatistic::getTotalStatisticsRecords();
$obj->result = VideoStatistic::deleteOldStatistics($days);
$obj->after = VideoStatistic::getTotalStatisticsRecords();
$obj->error = empty($obj->result);
$obj->msg = "you had ". number_format($obj->before, 0)." statistics records and removed ". number_format($obj->before-$obj->after, 0)." now you have ". number_format($obj->after, 0);
echo json_encode($obj);

View file

@ -1,9 +1,10 @@
<?php
class CloneLog{
class CloneLog
{
public $file;
function __construct() {
public function __construct()
{
global $global;
$clonesDir = Video::getStoragePath()."cache/clones/";
$this->file = "{$clonesDir}client.log";
@ -13,9 +14,10 @@ class CloneLog{
}
file_put_contents($this->file, "");
}
function add($message){
public function add($message)
{
_error_log($message);
file_put_contents($this->file, $message.PHP_EOL , FILE_APPEND | LOCK_EX);
file_put_contents($this->file, $message.PHP_EOL, FILE_APPEND | LOCK_EX);
}
}

View file

@ -3,49 +3,55 @@ global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
class CloneSite extends PluginAbstract {
public function getTags() {
return array(
class CloneSite extends PluginAbstract
{
public function getTags()
{
return [
PluginTags::$SECURITY,
PluginTags::$FREE
);
PluginTags::$FREE,
];
}
public function getDescription() {
public function getDescription()
{
global $global;
$obj = $this->getDataObject();
$txt = "Clone and Backup AVideo Sites";
$txt .= "<br>Crontab every day at 1am:<br><code>0 1 * * * php {$global['systemRootPath']}plugin/CloneSite/cloneClient.json.php {$obj->myKey}</code>";
if(!isRsync()){
if (!isRsync()) {
$txt .= "<div class='alert alert-danger'>To use rsync feature you must install it <code>sudo apt-get install rsync</code></div>";
}
if(!isSshpass()){
if (!isSshpass()) {
$txt .= "<div class='alert alert-danger'>To use rsync feature you must install sshpass <code>sudo apt-get install sshpass</code></div>";
}
$help = "<br><small><a href='https://github.com/WWBN/AVideo/wiki/Clone-Site-Plugin' target='__blank'><i class='fas fa-question-circle'></i> Help</a></small>";
return $txt . $help;
}
public function getName() {
public function getName()
{
return "CloneSite";
}
public function getUUID() {
public function getUUID()
{
return "c0731de9-b4f7-4462-bda6-458b0736593d";
}
public function getPluginVersion() {
return "1.1";
public function getPluginVersion()
{
return "1.1";
}
public function getPluginMenu() {
public function getPluginMenu()
{
global $global;
$filename = $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html';
return file_get_contents($filename);
}
public function getEmptyDataObject() {
public function getEmptyDataObject()
{
global $global;
$obj = new stdClass();
$obj->cloneSiteURL = "";
@ -54,29 +60,30 @@ class CloneSite extends PluginAbstract {
$obj->cloneSiteSSHPort = "22";
$o = new stdClass();
$o->type = "encrypted";
$o->value = "";
$o->value = "";
$obj->cloneSiteSSHPassword = $o;
$obj->useRsync = true;
$obj->MaintenanceMode = false;
$obj->myKey = md5($global['systemRootPath'].$global['salt']);
return $obj;
}
public function getStart() {
public function getStart()
{
$obj = $this->getDataObject();
if($obj->MaintenanceMode){
if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getStart();
}
}
public function getFooterCode() {
public function getFooterCode()
{
$obj = $this->getDataObject();
if($obj->MaintenanceMode){
if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getFooterCode();
}
}
}

View file

@ -1,160 +1,182 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
class Clones extends ObjectYPT {
protected $id, $url, $status, $key, $last_clone_request;
static function getSearchFieldsNames() {
return array('url');
}
static function getTableName() {
return 'clone_SitesAllowed';
}
static function getFromURL($url){
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE url = ? LIMIT 1";
$res = sqlDAL::readSql($sql,"s",array($url));
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
function updateLastCloneRequest() {
global $global;
if (!empty($this->id)) {
$sql = "UPDATE " . static::getTableName() . " SET last_clone_request = now() ";
$sql .= " WHERE id = {$this->id}";
} else {
return false;
}
$insert_row = sqlDAL::writeSql($sql);
if ($insert_row) {
$id = $this->id;
return $id;
} else {
die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
function loadFromURL($url) {
$row = self::getFromURL($url);
if (empty($row))
return false;
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
static function thisURLCanCloneMe($url, $key){
$resp = new stdClass();
$resp->canClone = false;
$resp->clone = null;
$resp->msg = "";
$clone = new Clones(0);
$clone->loadFromURL($url);
if(empty($clone->getId())){
$resp->msg = "The URL {$url} was just added in our server, ask the Server Manager to approve this URL on plugins->Clone Site->Clones Manager (The Blue Button) and Activate your client";
self::addURL($url, $key);
return $resp;
}
if($clone->getKey() !== $key){
$resp->msg = "Invalid Key";
return $resp;
}
if($clone->getStatus() !== 'a'){
$resp->msg = "The URL {$url} is inactive in our Clone Server";
return $resp;
}
$resp->clone = $clone;
$resp->canClone = true;
return $resp;
}
static function addURL($url, $key){
$clone = new Clones(0);
$clone->loadFromURL($url);
if(empty($clone->getId())){
$clone->setUrl($url);
$clone->setKey($key);
return $clone->save();
}
return false;
}
function save() {
if(empty($this->status)){
$this->status = 'i';
}
if(empty($this->last_clone_request)){
$this->last_clone_request = 'null';
}
return parent::save();
}
function getId() {
return $this->id;
}
function getUrl() {
return $this->url;
}
function getStatus() {
return $this->status;
}
function getKey() {
return $this->key;
}
function getLast_clone_request() {
return $this->last_clone_request;
}
function setId($id) {
$this->id = $id;
}
function setUrl($url) {
$this->url = $url;
}
function setStatus($status) {
$this->status = $status;
}
function setKey($key) {
$this->key = $key;
}
function setLast_clone_request($last_clone_request) {
$this->last_clone_request = $last_clone_request;
}
function toogleStatus(){
if(empty($this->id)){
return false;
}
if($this->status==='i'){
$this->status='a';
}else{
$this->status='i';
}
return $this->save();
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
class Clones extends ObjectYPT
{
protected $id;
protected $url;
protected $status;
protected $key;
protected $last_clone_request;
public static function getSearchFieldsNames()
{
return ['url'];
}
public static function getTableName()
{
return 'clone_SitesAllowed';
}
public static function getFromURL($url)
{
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE url = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", [$url]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public function updateLastCloneRequest()
{
global $global;
if (!empty($this->id)) {
$sql = "UPDATE " . static::getTableName() . " SET last_clone_request = now() ";
$sql .= " WHERE id = {$this->id}";
} else {
return false;
}
$insert_row = sqlDAL::writeSql($sql);
if ($insert_row) {
$id = $this->id;
return $id;
} else {
die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
public function loadFromURL($url)
{
$row = self::getFromURL($url);
if (empty($row)) {
return false;
}
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
public static function thisURLCanCloneMe($url, $key)
{
$resp = new stdClass();
$resp->canClone = false;
$resp->clone = null;
$resp->msg = "";
$clone = new Clones(0);
$clone->loadFromURL($url);
if (empty($clone->getId())) {
$resp->msg = "The URL {$url} was just added in our server, ask the Server Manager to approve this URL on plugins->Clone Site->Clones Manager (The Blue Button) and Activate your client";
self::addURL($url, $key);
return $resp;
}
if ($clone->getKey() !== $key) {
$resp->msg = "Invalid Key";
return $resp;
}
if ($clone->getStatus() !== 'a') {
$resp->msg = "The URL {$url} is inactive in our Clone Server";
return $resp;
}
$resp->clone = $clone;
$resp->canClone = true;
return $resp;
}
public static function addURL($url, $key)
{
$clone = new Clones(0);
$clone->loadFromURL($url);
if (empty($clone->getId())) {
$clone->setUrl($url);
$clone->setKey($key);
return $clone->save();
}
return false;
}
public function save()
{
if (empty($this->status)) {
$this->status = 'i';
}
if (empty($this->last_clone_request)) {
$this->last_clone_request = 'null';
}
return parent::save();
}
public function getId()
{
return $this->id;
}
public function getUrl()
{
return $this->url;
}
public function getStatus()
{
return $this->status;
}
public function getKey()
{
return $this->key;
}
public function getLast_clone_request()
{
return $this->last_clone_request;
}
public function setId($id)
{
$this->id = $id;
}
public function setUrl($url)
{
$this->url = $url;
}
public function setStatus($status)
{
$this->status = $status;
}
public function setKey($key)
{
$this->key = $key;
}
public function setLast_clone_request($last_clone_request)
{
$this->last_clone_request = $last_clone_request;
}
public function toogleStatus()
{
if (empty($this->id)) {
return false;
}
if ($this->status==='i') {
$this->status='a';
} else {
$this->status='i';
}
return $this->save();
}
}

View file

@ -1,20 +1,20 @@
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new Clones($_POST['id']);
if($o->toogleStatus()){
$obj->error = false;
}
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new Clones($_POST['id']);
if ($o->toogleStatus()) {
$obj->error = false;
}
echo json_encode($obj);

View file

@ -1,212 +1,211 @@
<?php
$time_start = microtime(true);
$config = '../../videos/configuration.php';
session_write_close();
if (!file_exists($config)) {
list($scriptPath) = get_included_files();
$path = pathinfo($scriptPath);
$config = $path['dirname'] . "/" . $config;
}
header('Content-Type: application/json');
require_once $config;
set_time_limit(0);
require_once $global['systemRootPath'] . 'objects/plugin.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneSite.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneLog.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
$totalSteps = 7;
$total2 = $total = 0;
$resp = new stdClass();
$resp->error = true;
$resp->msg = "";
$log = new CloneLog();
$log->add("Clone: Clone Start");
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if (empty($objClone)) {
$resp->msg = "Your Clone Site Plugin is not enabled";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
if (empty($objClone->cloneSiteURL)) {
$resp->msg = "Your Clone Site URL is empty, please click on the Edit parameters buttons and place an AVideo URL";
_error_log("{$resp->msg} (".json_encode($objClone).")");
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$objClone->cloneSiteURL = rtrim($objClone->cloneSiteURL,"/").'/';
$objCloneOriginal = $objClone;
$argv[1] = preg_replace("/[^A-Za-z0-9 ]/", '', @$argv[1]);
if (empty($objClone) || empty($argv[1]) || $objClone->myKey !== $argv[1]) {
if (!User::isAdmin()) {
$resp->msg = "You can't do this";
$log->add("Clone: {$resp->msg}");
echo "$objClone->myKey !== $argv[1]";
die(json_encode($resp));
}
}
$videosSite = "{$objClone->cloneSiteURL}videos/";
$videosDir = Video::getStoragePath()."";
$clonesDir = "{$videosDir}cache/clones/";
$photosDir = "{$videosDir}userPhoto/";
$photosSite = "{$videosSite}userPhoto/";
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir . "index.html", '');
}
if (!file_exists($photosDir)) {
mkdir($photosDir, 0777, true);
}
$url = $objClone->cloneSiteURL . "plugin/CloneSite/cloneServer.json.php?url=" . urlencode($global['webSiteRootURL']) . "&key={$objClone->myKey}&useRsync=" . intval($objClone->useRsync);
// check if it respond
$log->add("Clone (1 of {$totalSteps}): Asking the Server the database and the files");
$content = url_get_contents($url, "", 3600, true);
_error_log("Clone: url_get_contents($url) respond: ($content)");
//var_dump($url, $content);exit;
$json = _json_decode($content);
if (empty($json)) {
$resp->msg = "Clone Server Unknow ERROR";
$log->add("Clone: Server Unknow ERROR");
die(json_encode($resp));
}
if (!empty($json->error)) {
$resp->msg = "Clone Server message: {$json->msg}";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$log->add("Clone: Good start! the server has answered");
// get dump file
$cmd = "wget -O {$clonesDir}{$json->sqlFile} {$objClone->cloneSiteURL}videos/cache/clones/{$json->sqlFile}";
$log->add("Clone (2 of {$totalSteps}): Geting MySQL Dump file");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone: Nice! we got the MySQL Dump file");
// remove the first warning line
$file = "{$clonesDir}{$json->sqlFile}";
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
$log->add("Clone (3 of {$totalSteps}): Overwriting our database with the server database");
// restore dump
$cmd = "mysql -u {$mysqlUser} -p{$mysqlPass} --host {$mysqlHost} {$mysqlDatabase} < {$clonesDir}{$json->sqlFile}";
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone: Great! we overwrite it with success.");
if (empty($objClone->useRsync)) {
$videoFiles = getCloneFilesInfo($videosDir);
$newVideoFiles = detectNewFiles($json->videoFiles, $videoFiles);
$photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
$newPhotoFiles = detectNewFiles($json->photoFiles, $photoFiles);
$total = count($newVideoFiles);
$count = 0;
if (!empty($total)) {
$log->add("Clone (4 of {$totalSteps}): Now we will copy {$total} new video files, usually this takes a while.");
// copy videos
foreach ($newVideoFiles as $value) {
$query = parse_url($value->url, PHP_URL_QUERY);
if ($query) {
$value->url .= '&ignoreXsendfilePreVideoPlay=1';
} else {
$value->url .= '?ignoreXsendfilePreVideoPlay=1';
}
$count++;
$log->add("Clone: Copying Videos {$count} of {$total} {$value->url}");
file_put_contents("{$videosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying video files done.");
} else {
$log->add("Clone (4 of {$totalSteps}): There is no new video file to copy.");
}
$total2 = count($newPhotoFiles);
$count2 = 0;
if (!empty($total2)) {
$log->add("Clone (5 of {$totalSteps}): Now we will copy {$total2} new user photo files.");
// copy Photos
foreach ($newPhotoFiles as $value) {
$count2++;
$log->add("Clone: Copying Photos {$count2} of {$total2} {$value->url}");
file_put_contents("{$photosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying user photo files done.");
} else {
$log->add("Clone (5 of {$totalSteps}): There is no new user photo file to copy.");
}
} else {
// decrypt the password now
$objClone = Plugin::decryptIfNeed($objClone);
$port = intval($objClone->cloneSiteSSHPort);
if(empty($port)){
$port = 22;
}
$rsync = "sshpass -p '{password}' rsync -av -e 'ssh -p {$port} -o StrictHostKeyChecking=no' --exclude '*.php' --exclude 'cache' --exclude '*.sql' --exclude '*.log' {$objClone->cloneSiteSSHUser}@{$objClone->cloneSiteSSHIP}:{$json->videosDir} ". Video::getStoragePath()." --log-file='{$log->file}' ";
$cmd = str_replace("{password}", $objClone->cloneSiteSSHPassword->value, $rsync);
$log->add("Clone (4 of {$totalSteps}): execute rsync ({$rsync})");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
//$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone (5 of {$totalSteps}): rsync finished");
}
// notify to delete dump
$url = $url . "&deleteDump={$json->sqlFile}";
// check if it respond
$log->add("Clone (6 of {$totalSteps}): Notify Server to Delete Dump");
$content2 = url_get_contents($url);
//var_dump($url, $content);exit;
$json2 = _json_decode($content);
if (!empty($json2->error)) {
$log->add("Clone: Dump NOT deleted");
} else {
$log->add("Clone: Dump DELETED");
}
$log->add("Clone (7 of {$totalSteps}): Resotre the Clone Configuration");
// restore clone plugin configuration
$plugin = new CloneSite();
$p = new Plugin(0);
$p->loadFromUUID($plugin->getUUID());
$p->setObject_data(addcslashes(json_encode($objCloneOriginal),'\\'));
$p->setStatus('active');
$p->save();
echo json_encode($json);
$log->add("Clone: Complete, Database, {$total} Videos and {$total2} Photos");
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start);
$timeStr = "Seconds";
if ($execution_time > 60) {
$execution_time = $execution_time / 60;
$timeStr = "Minutes";
}
//execution time of the script
$log->add('Total Execution Time: ' . $execution_time . ' ' . $timeStr);
<?php
$time_start = microtime(true);
$config = '../../videos/configuration.php';
session_write_close();
if (!file_exists($config)) {
[$scriptPath] = get_included_files();
$path = pathinfo($scriptPath);
$config = $path['dirname'] . "/" . $config;
}
header('Content-Type: application/json');
require_once $config;
set_time_limit(0);
require_once $global['systemRootPath'] . 'objects/plugin.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneSite.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/CloneLog.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
$totalSteps = 7;
$total2 = $total = 0;
$resp = new stdClass();
$resp->error = true;
$resp->msg = "";
$log = new CloneLog();
$log->add("Clone: Clone Start");
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if (empty($objClone)) {
$resp->msg = "Your Clone Site Plugin is not enabled";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
if (empty($objClone->cloneSiteURL)) {
$resp->msg = "Your Clone Site URL is empty, please click on the Edit parameters buttons and place an AVideo URL";
_error_log("{$resp->msg} (".json_encode($objClone).")");
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$objClone->cloneSiteURL = rtrim($objClone->cloneSiteURL, "/").'/';
$objCloneOriginal = $objClone;
$argv[1] = preg_replace("/[^A-Za-z0-9 ]/", '', @$argv[1]);
if (empty($objClone) || empty($argv[1]) || $objClone->myKey !== $argv[1]) {
if (!User::isAdmin()) {
$resp->msg = "You can't do this";
$log->add("Clone: {$resp->msg}");
echo "$objClone->myKey !== $argv[1]";
die(json_encode($resp));
}
}
$videosSite = "{$objClone->cloneSiteURL}videos/";
$videosDir = Video::getStoragePath()."";
$clonesDir = "{$videosDir}cache/clones/";
$photosDir = "{$videosDir}userPhoto/";
$photosSite = "{$videosSite}userPhoto/";
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir . "index.html", '');
}
if (!file_exists($photosDir)) {
mkdir($photosDir, 0777, true);
}
$url = $objClone->cloneSiteURL . "plugin/CloneSite/cloneServer.json.php?url=" . urlencode($global['webSiteRootURL']) . "&key={$objClone->myKey}&useRsync=" . intval($objClone->useRsync);
// check if it respond
$log->add("Clone (1 of {$totalSteps}): Asking the Server the database and the files");
$content = url_get_contents($url, "", 3600, true);
_error_log("Clone: url_get_contents($url) respond: ($content)");
//var_dump($url, $content);exit;
$json = _json_decode($content);
if (empty($json)) {
$resp->msg = "Clone Server Unknow ERROR";
$log->add("Clone: Server Unknow ERROR");
die(json_encode($resp));
}
if (!empty($json->error)) {
$resp->msg = "Clone Server message: {$json->msg}";
$log->add("Clone: {$resp->msg}");
die(json_encode($resp));
}
$log->add("Clone: Good start! the server has answered");
// get dump file
$cmd = "wget -O {$clonesDir}{$json->sqlFile} {$objClone->cloneSiteURL}videos/cache/clones/{$json->sqlFile}";
$log->add("Clone (2 of {$totalSteps}): Geting MySQL Dump file");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone: Nice! we got the MySQL Dump file");
// remove the first warning line
$file = "{$clonesDir}{$json->sqlFile}";
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
$log->add("Clone (3 of {$totalSteps}): Overwriting our database with the server database");
// restore dump
$cmd = "mysql -u {$mysqlUser} -p{$mysqlPass} --host {$mysqlHost} {$mysqlDatabase} < {$clonesDir}{$json->sqlFile}";
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone: Great! we overwrite it with success.");
if (empty($objClone->useRsync)) {
$videoFiles = getCloneFilesInfo($videosDir);
$newVideoFiles = detectNewFiles($json->videoFiles, $videoFiles);
$photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
$newPhotoFiles = detectNewFiles($json->photoFiles, $photoFiles);
$total = count($newVideoFiles);
$count = 0;
if (!empty($total)) {
$log->add("Clone (4 of {$totalSteps}): Now we will copy {$total} new video files, usually this takes a while.");
// copy videos
foreach ($newVideoFiles as $value) {
$query = parse_url($value->url, PHP_URL_QUERY);
if ($query) {
$value->url .= '&ignoreXsendfilePreVideoPlay=1';
} else {
$value->url .= '?ignoreXsendfilePreVideoPlay=1';
}
$count++;
$log->add("Clone: Copying Videos {$count} of {$total} {$value->url}");
file_put_contents("{$videosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying video files done.");
} else {
$log->add("Clone (4 of {$totalSteps}): There is no new video file to copy.");
}
$total2 = count($newPhotoFiles);
$count2 = 0;
if (!empty($total2)) {
$log->add("Clone (5 of {$totalSteps}): Now we will copy {$total2} new user photo files.");
// copy Photos
foreach ($newPhotoFiles as $value) {
$count2++;
$log->add("Clone: Copying Photos {$count2} of {$total2} {$value->url}");
file_put_contents("{$photosDir}{$value->filename}", fopen("$value->url", 'r'));
}
$log->add("Clone: Copying user photo files done.");
} else {
$log->add("Clone (5 of {$totalSteps}): There is no new user photo file to copy.");
}
} else {
// decrypt the password now
$objClone = Plugin::decryptIfNeed($objClone);
$port = intval($objClone->cloneSiteSSHPort);
if (empty($port)) {
$port = 22;
}
$rsync = "sshpass -p '{password}' rsync -av -e 'ssh -p {$port} -o StrictHostKeyChecking=no' --exclude '*.php' --exclude 'cache' --exclude '*.sql' --exclude '*.log' {$objClone->cloneSiteSSHUser}@{$objClone->cloneSiteSSHIP}:{$json->videosDir} ". Video::getStoragePath()." --log-file='{$log->file}' ";
$cmd = str_replace("{password}", $objClone->cloneSiteSSHPassword->value, $rsync);
$log->add("Clone (4 of {$totalSteps}): execute rsync ({$rsync})");
exec($cmd . " 2>&1", $output, $return_val);
if ($return_val !== 0) {
//$log->add("Clone Error: " . print_r($output, true));
}
$log->add("Clone (5 of {$totalSteps}): rsync finished");
}
// notify to delete dump
$url = $url . "&deleteDump={$json->sqlFile}";
// check if it respond
$log->add("Clone (6 of {$totalSteps}): Notify Server to Delete Dump");
$content2 = url_get_contents($url);
//var_dump($url, $content);exit;
$json2 = _json_decode($content);
if (!empty($json2->error)) {
$log->add("Clone: Dump NOT deleted");
} else {
$log->add("Clone: Dump DELETED");
}
$log->add("Clone (7 of {$totalSteps}): Resotre the Clone Configuration");
// restore clone plugin configuration
$plugin = new CloneSite();
$p = new Plugin(0);
$p->loadFromUUID($plugin->getUUID());
$p->setObject_data(addcslashes(json_encode($objCloneOriginal), '\\'));
$p->setStatus('active');
$p->save();
echo json_encode($json);
$log->add("Clone: Complete, Database, {$total} Videos and {$total2} Photos");
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start);
$timeStr = "Seconds";
if ($execution_time > 60) {
$execution_time = $execution_time / 60;
$timeStr = "Minutes";
}
//execution time of the script
$log->add('Total Execution Time: ' . $execution_time . ' ' . $timeStr);

View file

@ -1,5 +1,4 @@
<?php
require_once '../../videos/configuration.php';
set_time_limit(0);
session_write_close();
@ -19,29 +18,29 @@ $resp->key = $_GET['key'];
$resp->useRsync = intval($_GET['useRsync']);
$resp->videosDir = Video::getStoragePath()."";
$resp->sqlFile = "";
$resp->videoFiles = array();
$resp->photoFiles = array();
$resp->videoFiles = [];
$resp->photoFiles = [];
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if(empty($objClone)){
if (empty($objClone)) {
$resp->msg = "CloneSite is not enabled on the Master site";
die(json_encode($resp));
}
if(empty($resp->key)){
if (empty($resp->key)) {
$resp->msg = "Key cannot be blank";
die(json_encode($resp));
}
// check if the url is allowed to clone it
$canClone = Clones::thisURLCanCloneMe($resp->url, $resp->key);
if(empty($canClone->canClone)){
if (empty($canClone->canClone)) {
$resp->msg = $canClone->msg;
die(json_encode($resp));
}
if(!empty($_GET['deleteDump'])){
if (!empty($_GET['deleteDump'])) {
$resp->error = !unlink("{$clonesDir}{$_GET['deleteDump']}");
$resp->msg = "Delete Dump {$_GET['deleteDump']}";
die(json_encode($resp));
@ -64,9 +63,9 @@ if ($return_val !== 0) {
_error_log("Clone Error: ". print_r($output, true));
}
if(empty($resp->useRsync)){
if (empty($resp->useRsync)) {
$resp->videoFiles = getCloneFilesInfo($videosDir);
$resp->photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
}
echo json_encode($resp);
echo json_encode($resp);

View file

@ -1,8 +1,8 @@
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
header('Content-Type: application/json');
$rows = Clones::getAll();
?>
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
header('Content-Type: application/json');
$rows = Clones::getAll();
?>
{"data": <?php echo json_encode($rows); ?>}

View file

@ -1,22 +1,22 @@
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('CloneSite');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new Clones($id);
if(User::isAdmin()){
$row->delete();
$obj->error = false;
}
die(json_encode($obj));
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('CloneSite');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new Clones($id);
if (User::isAdmin()) {
$row->delete();
$obj->error = false;
}
die(json_encode($obj));

View file

@ -1,56 +1,59 @@
<?php
function getCloneFilesInfo($dir, $subdir = "", $extensionsToCopy = array('mp4', 'webm', 'gif', 'jpg', 'png')) {
global $global;
$files = array();
// get video files
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !is_dir($dir . $entry)) {
$path_info = pathinfo($entry);
if (!in_array($path_info['extension'], $extensionsToCopy)) {
continue;
}
$url = Video::getURLToFile("{$subdir}{$entry}");
$f = new stdClass();
$f->filename = $entry;
$f->url = $url;
$f->filesize = filesize($dir . $entry);
$f->filemtime = filemtime($dir . $entry);
$files[] = $f;
}
}
closedir($handle);
}
return $files;
}
/**
*
* @param type $serverArray a Json with the server files retrieve from getCloneFilesInfo function
* @param type $clientArray a Json with the client files retrieve from getCloneFilesInfo function
* @return type a Json with the new files
*/
function detectNewFiles($serverArray, $clientArray){
foreach ($serverArray as $key => $value) {
foreach ($clientArray as $key2 => $value2) {
if(
$value->filename===$value2->filename &&
$value->filesize===$value2->filesize &&
$value->filemtime<=$value2->filemtime
){
unset($serverArray[$key]);
unset($clientArray[$key2]);
}
}
}
return $serverArray;
}
function isRsync() {
return trim(shell_exec('which rsync'));
}
function isSshpass() {
return trim(shell_exec('which sshpass'));
}
<?php
function getCloneFilesInfo($dir, $subdir = "", $extensionsToCopy = ['mp4', 'webm', 'gif', 'jpg', 'png'])
{
global $global;
$files = [];
// get video files
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !is_dir($dir . $entry)) {
$path_info = pathinfo($entry);
if (!in_array($path_info['extension'], $extensionsToCopy)) {
continue;
}
$url = Video::getURLToFile("{$subdir}{$entry}");
$f = new stdClass();
$f->filename = $entry;
$f->url = $url;
$f->filesize = filesize($dir . $entry);
$f->filemtime = filemtime($dir . $entry);
$files[] = $f;
}
}
closedir($handle);
}
return $files;
}
/**
*
* @param type $serverArray a Json with the server files retrieve from getCloneFilesInfo function
* @param type $clientArray a Json with the client files retrieve from getCloneFilesInfo function
* @return type a Json with the new files
*/
function detectNewFiles($serverArray, $clientArray)
{
foreach ($serverArray as $key => $value) {
foreach ($clientArray as $key2 => $value2) {
if (
$value->filename===$value2->filename &&
$value->filesize===$value2->filesize &&
$value->filemtime<=$value2->filemtime
) {
unset($serverArray[$key]);
unset($clientArray[$key2]);
}
}
}
return $serverArray;
}
function isRsync()
{
return trim(shell_exec('which rsync'));
}
function isSshpass()
{
return trim(shell_exec('which sshpass'));
}

View file

@ -14,8 +14,8 @@ if (!User::isAdmin()) {
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle( __("Clone Site"));
<?php
echo getHTMLTitle(__("Clone Site"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';

View file

@ -1,40 +1,46 @@
<?php
global $global;
if (empty($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
class CustomizeUser extends PluginAbstract {
public function getTags() {
return array(
class CustomizeUser extends PluginAbstract
{
public function getTags()
{
return [
PluginTags::$RECOMMENDED,
PluginTags::$FREE
);
PluginTags::$FREE,
];
}
public function getDescription() {
public function getDescription()
{
$txt = "Fine Tuning User Profile";
return $txt;
}
public function getName() {
public function getName()
{
return "CustomizeUser";
}
public function getUUID() {
public function getUUID()
{
return "55a4fa56-8a30-48d4-a0fb-8aa6b3fuser3";
}
public function getPluginVersion() {
public function getPluginVersion()
{
return "3.0";
}
public function getEmptyDataObject() {
public function getEmptyDataObject()
{
global $advancedCustom;
$obj = new stdClass();
$obj->nonAdminCannotDownload = false;
@ -51,7 +57,7 @@ class CustomizeUser extends PluginAbstract {
$obj->userCanNotChangeUserGroup = false;
$o = new stdClass();
$o->type = array(0 => __("Default")) + UserGroups::getAllUsersGroupsArray();
$o->type = [0 => __("Default")] + UserGroups::getAllUsersGroupsArray();
$o->value = 0;
$obj->userDefaultUserGroup = $o;
$obj->userMustBeLoggedIn = !isset($advancedCustom->userMustBeLoggedIn) ? false : $advancedCustom->userMustBeLoggedIn;
@ -89,7 +95,7 @@ class CustomizeUser extends PluginAbstract {
$o = new stdClass();
$o->type = array(0 => '-- ' . __("None"), 1 => '-- ' . __("Random")) + self::getBGAnimationArray();
$o->type = [0 => '-- ' . __("None"), 1 => '-- ' . __("Random")] + self::getBGAnimationArray();
$o->value = 1;
$obj->loginBackgroundAnimation = $o;
@ -153,16 +159,18 @@ class CustomizeUser extends PluginAbstract {
return $obj;
}
static function autoIncludeBGAnimationFile() {
public static function autoIncludeBGAnimationFile()
{
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
$obj = AVideoPlugin::getObjectData('CustomizeUser');
Layout::includeBGAnimationFile($obj->loginBackgroundAnimation->value);
//Layout::includeBGAnimationFile('Animated3');
}
public function getUserOptions() {
public function getUserOptions()
{
$obj = $this->getDataObject();
$userOptions = array();
$userOptions = [];
if ($obj->Checkmark1Enabled) {
$userOptions["Checkmark 1"] = "checkmark1";
}
@ -175,19 +183,21 @@ class CustomizeUser extends PluginAbstract {
return $userOptions;
}
static function getBGAnimationArray() {
public static function getBGAnimationArray()
{
if (!class_exists('Layout')) {
$avideoLayout = AVideoPlugin::getObjectData('Layout');
}
$files = Layout::getBGAnimationFiles();
$response = array();
$response = [];
foreach ($files as $key => $value) {
$response[$value['name']] = ucfirst($value['name']);
}
return $response;
}
static function canDownloadVideosFromUser($users_id) {
public static function canDownloadVideosFromUser($users_id)
{
global $config;
$obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser");
if (!empty($obj->nonAdminCannotDownload) && !User::isAdmin()) {
@ -200,7 +210,8 @@ class CustomizeUser extends PluginAbstract {
return !empty($user->getExternalOption('userCanAllowFilesDownload'));
}
static function canDownloadVideos() {
public static function canDownloadVideos()
{
global $config;
$obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser");
if (!empty($obj->nonAdminCannotDownload) && !User::isAdmin()) {
@ -209,7 +220,8 @@ class CustomizeUser extends PluginAbstract {
return !empty($config->getAllow_download());
}
static function setCanDownloadVideosFromUser($users_id, $value = true) {
public static function setCanDownloadVideosFromUser($users_id, $value = true)
{
$obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser");
if (empty($obj) || empty($obj->userCanAllowFilesDownload)) {
return false;
@ -218,7 +230,8 @@ class CustomizeUser extends PluginAbstract {
return $user->addExternalOptions('userCanAllowFilesDownload', $value);
}
static function canShareVideosFromUser($users_id) {
public static function canShareVideosFromUser($users_id)
{
global $advancedCustom;
if (!empty($advancedCustom->disableShareOnly)) {
@ -239,7 +252,8 @@ class CustomizeUser extends PluginAbstract {
return !empty($user->getExternalOption('userCanAllowFilesShare'));
}
static function setCanShareVideosFromUser($users_id, $value = true) {
public static function setCanShareVideosFromUser($users_id, $value = true)
{
$obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser");
if (empty($obj) || empty($obj->userCanAllowFilesShare)) {
return false;
@ -248,18 +262,20 @@ class CustomizeUser extends PluginAbstract {
return $user->addExternalOptions('userCanAllowFilesShare', $value);
}
static function getSwitchUserCanAllowFilesDownload($users_id) {
public static function getSwitchUserCanAllowFilesDownload($users_id)
{
global $global;
include $global['systemRootPath'] . 'plugin/CustomizeUser/switchUserCanAllowFilesDownload.php';
}
static function getSwitchUserCanAllowFilesShare($users_id) {
public static function getSwitchUserCanAllowFilesShare($users_id)
{
global $global;
include $global['systemRootPath'] . 'plugin/CustomizeUser/switchUserCanAllowFilesShare.php';
}
public function getMyAccount($users_id) {
public function getMyAccount($users_id)
{
$objcu = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser");
if (!empty($objcu) && !empty($objcu->userCanAllowFilesDownload)) {
@ -278,7 +294,8 @@ class CustomizeUser extends PluginAbstract {
}
}
public function getChannelButton() {
public function getChannelButton()
{
global $global, $isMyChannel;
if (!$isMyChannel) {
return "";
@ -302,13 +319,15 @@ class CustomizeUser extends PluginAbstract {
echo "</div>";
}
public function getVideoManagerButton() {
public function getVideoManagerButton()
{
global $isMyChannel;
$isMyChannel = true;
return self::getChannelButton();
}
static function canDownloadVideosFromVideo($videos_id) {
public static function canDownloadVideosFromVideo($videos_id)
{
if (!CustomizeUser::canDownloadVideos()) {
return false;
}
@ -333,7 +352,8 @@ class CustomizeUser extends PluginAbstract {
return true;
}
static function canShareVideosFromVideo($videos_id) {
public static function canShareVideosFromVideo($videos_id)
{
$video = new Video("", "", $videos_id);
if (empty($video)) {
_error_log("CustomizeUser::canShareVideosFromVideo video not found");
@ -354,7 +374,8 @@ class CustomizeUser extends PluginAbstract {
return true;
}
public function onUserSignup($users_id) {
public function onUserSignup($users_id)
{
global $global;
$obj = $this->getDataObject();
@ -363,7 +384,8 @@ class CustomizeUser extends PluginAbstract {
}
}
public function getWatchActionButton($videos_id) {
public function getWatchActionButton($videos_id)
{
global $global, $video;
if (!empty($videos_id) && empty($video)) {
$video = Video::getVideo($videos_id);
@ -372,7 +394,8 @@ class CustomizeUser extends PluginAbstract {
include $global['systemRootPath'] . 'plugin/CustomizeUser/actionButton.php';
}
public function getHTMLMenuRight() {
public function getHTMLMenuRight()
{
global $global;
$obj = $this->getDataObject();
if ($obj->keepViewerOnChannel) {
@ -380,7 +403,8 @@ class CustomizeUser extends PluginAbstract {
}
}
public function getModeYouTube($videos_id) {
public function getModeYouTube($videos_id)
{
global $global, $config;
if (empty($videos_id)) {
return false;
@ -404,7 +428,7 @@ class CustomizeUser extends PluginAbstract {
exit;
*
*/
} else if ($obj->userCanProtectVideosWithPassword) {
} elseif ($obj->userCanProtectVideosWithPassword) {
if (!$this->videoPasswordIsGood($videos_id)) {
$video = Video::getVideoLight($videos_id);
include "{$global['systemRootPath']}plugin/CustomizeUser/confirmVideoPassword.php";
@ -413,7 +437,8 @@ class CustomizeUser extends PluginAbstract {
}
}
public static function videoPasswordIsGood($videos_id) {
public static function videoPasswordIsGood($videos_id)
{
$video = new Video("", "", $videos_id);
$videoPassword = $video->getVideo_password();
if (empty($videoPassword)) {
@ -430,11 +455,13 @@ class CustomizeUser extends PluginAbstract {
return true;
}
public function getEmbed($videos_id) {
public function getEmbed($videos_id)
{
$this->getModeYouTube($videos_id);
}
public function getStart() {
public function getStart()
{
global $global;
$obj = $this->getDataObject();
$thisScriptFile = pathinfo($_SERVER["SCRIPT_FILENAME"]);
@ -451,12 +478,14 @@ class CustomizeUser extends PluginAbstract {
}
}
public function getPluginMenu() {
public function getPluginMenu()
{
global $global;
return '<button onclick="avideoModalIframe(webSiteRootURL +\'plugin/CustomizeUser/View/editor.php\');" class="btn btn-primary btn-sm btn-xs btn-block"><i class="fa fa-edit"></i> Edit</button>';
}
public static function profileTabName($users_id) {
public static function profileTabName($users_id)
{
$p = AVideoPlugin::loadPlugin("CustomizeUser");
$obj = $p->getDataObject();
if (empty($obj->enableExtraInfo)) {
@ -465,7 +494,8 @@ class CustomizeUser extends PluginAbstract {
return '<li><a data-toggle="tab" href="#tabExtraInfo' . $p->getUUID() . '">' . __('Extra Info') . '</a></li>';
}
public static function profileTabContent($users_id) {
public static function profileTabContent($users_id)
{
global $global;
$p = AVideoPlugin::loadPlugin("CustomizeUser");
$obj = $p->getDataObject();
@ -477,7 +507,8 @@ class CustomizeUser extends PluginAbstract {
return "";
}
public function getUsersManagerListButton() {
public function getUsersManagerListButton()
{
global $global;
$p = AVideoPlugin::loadPlugin("CustomizeUser");
$obj = $p->getDataObject();
@ -495,13 +526,14 @@ class CustomizeUser extends PluginAbstract {
return $btn;
}
public function afterNewVideo($videos_id) {
public function afterNewVideo($videos_id)
{
$obj = $this->getDataObject();
if (!empty($obj->autoSaveUsersOnCategorySelectedGroups)) {
$video = new Video("", "", $videos_id);
$categories_id = $video->getCategories_id();
$rows = Categories_has_users_groups::getAllFromCategory($categories_id);
$userGroups = array();
$userGroups = [];
foreach ($rows as $value) {
$userGroups[] = $value['users_groups_id'];
}
@ -516,5 +548,4 @@ class CustomizeUser extends PluginAbstract {
return false;
}
}

View file

@ -2,19 +2,25 @@
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Categories_has_users_groups extends ObjectYPT {
class Categories_has_users_groups extends ObjectYPT
{
protected $id;
protected $categories_id;
protected $users_groups_id;
protected $status;
protected $id,$categories_id,$users_groups_id,$status;
static function getSearchFieldsNames() {
return array();
public static function getSearchFieldsNames()
{
return [];
}
static function getTableName() {
public static function getTableName()
{
return 'categories_has_users_groups';
}
static function getAllCategories() {
public static function getAllCategories()
{
global $global;
$table = "categories";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
@ -23,7 +29,7 @@ class Categories_has_users_groups extends ObjectYPT {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -33,7 +39,8 @@ class Categories_has_users_groups extends ObjectYPT {
}
return $rows;
}
static function getAllUsers_groups() {
public static function getAllUsers_groups()
{
global $global;
$table = "users_groups";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
@ -42,7 +49,7 @@ static function getAllUsers_groups() {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -52,43 +59,52 @@ static function getAllUsers_groups() {
}
return $rows;
}
function setId($id) {
public function setId($id)
{
$this->id = intval($id);
}
function setCategories_id($categories_id) {
}
public function setCategories_id($categories_id)
{
$this->categories_id = intval($categories_id);
}
function setUsers_groups_id($users_groups_id) {
}
public function setUsers_groups_id($users_groups_id)
{
$this->users_groups_id = intval($users_groups_id);
}
function setStatus($status) {
}
public function setStatus($status)
{
$this->status = $status;
}
function getId() {
}
public function getId()
{
return intval($this->id);
}
function getCategories_id() {
}
public function getCategories_id()
{
return intval($this->categories_id);
}
function getUsers_groups_id() {
}
public function getUsers_groups_id()
{
return intval($this->users_groups_id);
}
function getStatus() {
}
public function getStatus()
{
return $this->status;
}
public static function getAll(){
}
public static function getAll()
{
global $global;
if (!static::isTableInstalled()) {
return false;
@ -102,7 +118,7 @@ static function getAllUsers_groups() {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -112,14 +128,15 @@ static function getAllUsers_groups() {
}
return $rows;
}
public static function getAllFromCategory($categories_id){
public static function getAllFromCategory($categories_id)
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if(empty($categories_id)){
if (empty($categories_id)) {
return false;
}
$sql = "SELECT c.*, ug.*, cug.* FROM " . static::getTableName() . " cug "
@ -130,7 +147,7 @@ static function getAllUsers_groups() {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -140,6 +157,4 @@ static function getAllUsers_groups() {
}
return $rows;
}
}

View file

@ -2,100 +2,127 @@
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Users_extra_info extends ObjectYPT {
class Users_extra_info extends ObjectYPT
{
protected $id;
protected $field_name;
protected $field_type;
protected $field_options;
protected $field_default_value;
protected $parameters;
protected $status;
protected $order;
protected $id, $field_name, $field_type, $field_options, $field_default_value, $parameters, $status, $order;
static function getSearchFieldsNames() {
return array('field_name', 'field_type', 'field_options', 'field_default_value', 'parameters');
public static function getSearchFieldsNames()
{
return ['field_name', 'field_type', 'field_options', 'field_default_value', 'parameters'];
}
static function getTableName() {
public static function getTableName()
{
return 'users_extra_info';
}
function setId($id) {
public function setId($id)
{
$this->id = intval($id);
}
function setField_name($field_name) {
public function setField_name($field_name)
{
$this->field_name = $field_name;
}
function setField_type($field_type) {
public function setField_type($field_type)
{
$this->field_type = $field_type;
}
function setField_options($field_options) {
public function setField_options($field_options)
{
$this->field_options = $field_options;
}
function setField_default_value($field_default_value) {
public function setField_default_value($field_default_value)
{
$this->field_default_value = $field_default_value;
}
function setParameters($parameters) {
public function setParameters($parameters)
{
$this->parameters = $parameters;
}
function setStatus($status) {
public function setStatus($status)
{
$this->status = $status;
}
function getId() {
public function getId()
{
return intval($this->id);
}
function getField_name() {
public function getField_name()
{
return $this->field_name;
}
function getField_type() {
public function getField_type()
{
return $this->field_type;
}
function getField_options() {
public function getField_options()
{
return $this->field_options;
}
function getField_default_value() {
public function getField_default_value()
{
return $this->field_default_value;
}
function getParameters() {
public function getParameters()
{
return $this->parameters;
}
function getStatus() {
public function getStatus()
{
return $this->status;
}
function getOrder() {
public function getOrder()
{
return $this->order;
}
function setOrder($order) {
public function setOrder($order)
{
$this->order = intval($order);
}
static function getTypesOptionArray() {
return array('input' => 'Text', 'number' => 'Number', 'select' => 'Predefined options (select one)', 'textarea' => 'Textarea');
public static function getTypesOptionArray()
{
return ['input' => 'Text', 'number' => 'Number', 'select' => 'Predefined options (select one)', 'textarea' => 'Textarea'];
}
static function typeToHTML($row) {
public static function typeToHTML($row)
{
$html = "";
if(isset($row['value'])){
if (isset($row['value'])) {
$row['field_default_value'] = $row['value'];
}
if ($row['field_type'] == 'input') {
$html .= "<label for=\"usersExtraInfo_{$row['id']}\">{$row['field_name']}:</label>";
$html .= "<input type=\"text\" id=\"usersExtraInfo_{$row['id']}\" name=\"usersExtraInfo[{$row['id']}]\" "
. "class=\"form-control input-sm usersExtraInfoInput\" placeholder=\"{$row['field_name']}\" value=\"{$row['field_default_value']}\">";
} else if ($row['field_type'] == 'number') {
} elseif ($row['field_type'] == 'number') {
$html .= "<label for=\"usersExtraInfo_{$row['id']}\">{$row['field_name']}:</label>";
$html .= "<input type=\"number\" id=\"usersExtraInfo_{$row['id']}\" name=\"usersExtraInfo[{$row['id']}]\" "
. "class=\"form-control input-sm usersExtraInfoInput\" placeholder=\"{$row['field_name']}\" value=\"{$row['field_default_value']}\">";
} else if ($row['field_type'] == 'select') {
} elseif ($row['field_type'] == 'select') {
$html = "<label for=\"usersExtraInfo_{$row['id']}\">{$row['field_name']}:</label>
<select class=\"form-control input-sm usersExtraInfoInput\" name=\"usersExtraInfo[{$row['id']}]\" id=\"usersExtraInfo_{$row['id']}\">";
foreach (preg_split("/((\r?\n)|(\r\n?))/", $row['field_options']) as $line) {
@ -110,7 +137,7 @@ class Users_extra_info extends ObjectYPT {
$html .= "<option {$selected}>" . htmlentities($line) . "</option>";
}
$html .= "</select>";
} else if ($row['field_type'] == 'textarea') {
} elseif ($row['field_type'] == 'textarea') {
$html .= "<label for=\"usersExtraInfo_{$row['id']}\">{$row['field_name']}:</label>";
$html .= "<textarea type=\"text\" id=\"usersExtraInfo_{$row['id']}\" name=\"usersExtraInfo[{$row['id']}]\" "
. "class=\"form-control input-sm usersExtraInfoInput\" placeholder=\"{$row['field_name']}\" rows=\"6\">{$row['field_default_value']}</textarea>";
@ -118,7 +145,8 @@ class Users_extra_info extends ObjectYPT {
return $html;
}
public static function getAllActive($users_id=0) {
public static function getAllActive($users_id=0)
{
global $global;
if (!static::isTableInstalled()) {
return false;
@ -127,16 +155,16 @@ class Users_extra_info extends ObjectYPT {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
if(!empty($users_id)){
if (!empty($users_id)) {
$extraInfo = self::getFromUser($users_id);
}
foreach ($fullData as $row) {
if(!empty($extraInfo) && !empty($extraInfo[$row['id']])){
if (!empty($extraInfo) && !empty($extraInfo[$row['id']])) {
$row['value'] = $extraInfo[$row['id']];
$row['current_value'] = $row['value'];
}else{
} else {
$row['current_value'] = $row['field_default_value'];
}
$rows[] = $row;
@ -147,9 +175,9 @@ class Users_extra_info extends ObjectYPT {
return $rows;
}
public static function getFromUser($users_id) {
public static function getFromUser($users_id)
{
$u = new User($users_id);
return object_to_array(_json_decode($u->getExtra_info()));
}
}

View file

@ -1,26 +1,27 @@
<?php
header('Content-Type: application/json');
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new Categories_has_users_groups(@$_POST['id']);
$o->setCategories_id($_POST['categories_id']);
$o->setUsers_groups_id($_POST['users_groups_id']);
$o->setStatus($_POST['status']);
if($id = $o->save()){
$obj->error = false;
}
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new Categories_has_users_groups(@$_POST['id']);
$o->setCategories_id($_POST['categories_id']);
$o->setUsers_groups_id($_POST['users_groups_id']);
$o->setStatus($_POST['status']);
if ($id = $o->save()) {
$obj->error = false;
}
echo json_encode($obj);

View file

@ -1,20 +1,20 @@
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new Categories_has_users_groups($id);
$obj->error = !$row->delete();
die(json_encode($obj));
?>
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new Categories_has_users_groups($id);
$obj->error = !$row->delete();
die(json_encode($obj));

View file

@ -1,8 +1,8 @@
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
header('Content-Type: application/json');
$rows = Categories_has_users_groups::getAll();
?>
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Categories_has_users_groups.php';
header('Content-Type: application/json');
$rows = Categories_has_users_groups::getAll();
?>
{"data": <?php echo json_encode($rows); ?>}

View file

@ -1,30 +1,31 @@
<?php
header('Content-Type: application/json');
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new Users_extra_info(@$_POST['id']);
$o->setField_name($_POST['field_name']);
$o->setField_type($_POST['field_type']);
$o->setField_options($_POST['field_options']);
$o->setField_default_value($_POST['field_default_value']);
$o->setParameters($_POST['parameters']);
$o->setStatus($_POST['status']);
$o->setOrder($_POST['order']);
if($id = $o->save()){
$obj->error = false;
}
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$o = new Users_extra_info(@$_POST['id']);
$o->setField_name($_POST['field_name']);
$o->setField_type($_POST['field_type']);
$o->setField_options($_POST['field_options']);
$o->setField_default_value($_POST['field_default_value']);
$o->setParameters($_POST['parameters']);
$o->setStatus($_POST['status']);
$o->setOrder($_POST['order']);
if ($id = $o->save()) {
$obj->error = false;
}
echo json_encode($obj);

View file

@ -1,20 +1,20 @@
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if(!User::isAdmin()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new Users_extra_info($id);
$obj->error = !$row->delete();
die(json_encode($obj));
?>
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if (!User::isAdmin()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
$id = intval($_POST['id']);
$row = new Users_extra_info($id);
$obj->error = !$row->delete();
die(json_encode($obj));

View file

@ -30,7 +30,7 @@ if (!User::isAdmin()) {
<label for="order"><?php echo __("order"); ?>:</label>
<select class="form-control input-sm" name="order" id="Users_extra_infoorder">
<?php
for($i=0;$i<20;$i++){
for ($i=0;$i<20;$i++) {
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>

View file

@ -1,8 +1,8 @@
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
header('Content-Type: application/json');
$rows = Users_extra_info::getAll();
?>
<?php
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
header('Content-Type: application/json');
$rows = Users_extra_info::getAll();
?>
{"data": <?php echo json_encode($rows); ?>}

View file

@ -1,26 +1,27 @@
<?php
header('Content-Type: application/json');
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$obj->id = 0;
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if(!User::isLogged()){
$obj->msg = "You can't do this";
die(json_encode($obj));
}
if(empty($_POST['usersExtraInfo'])){
$obj->msg = "Extra info is empty";
die(json_encode($obj));
}
$obj->id = User::saveExtraInfo(json_encode($_POST['usersExtraInfo']), User::getId());
$obj->error = empty($obj->id);
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/CustomizeUser/Objects/Users_extra_info.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$obj->id = 0;
$plugin = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if (!User::isLogged()) {
$obj->msg = "You can't do this";
die(json_encode($obj));
}
if (empty($_POST['usersExtraInfo'])) {
$obj->msg = "Extra info is empty";
die(json_encode($obj));
}
$obj->id = User::saveExtraInfo(json_encode($_POST['usersExtraInfo']), User::getId());
$obj->error = empty($obj->id);
echo json_encode($obj);

View file

@ -5,7 +5,7 @@ $rows = Users_extra_info::getAllActive(User::getId());
?>
<div id="<?php echo $tabId; ?>" class="tab-pane fade in" style="padding: 10px 0;">
<?php
if(User::isAdmin()){
if (User::isAdmin()) {
echo "<a href='{$global['webSiteRootURL']}plugin/CustomizeUser/View/editor.php' class='btn btn-default btn-block'>".__('Add more fields')."</a>";
}
?>
@ -15,12 +15,10 @@ $rows = Users_extra_info::getAllActive(User::getId());
$class = "col-sm-4";
if ($value['field_type'] == 'textarea') {
$class = "col-sm-12";
}
?>
} ?>
<div class="<?php echo $class; ?>">
<?php
echo Users_extra_info::typeToHTML($value);
?>
echo Users_extra_info::typeToHTML($value); ?>
</div>
<?php
}

View file

@ -17,11 +17,10 @@ if ($obj->allowWalletDirectTransferDonation && !empty($video['users_id']) && cla
<i class="fas fa-donate"></i> <small class="hidden-sm hidden-xs"><?php echo __("Please login to donate"); ?></small>
</a>
<?php
} else if (class_exists("YPTWallet")) {
} elseif (class_exists("YPTWallet")) {
$u = new User($video['users_id']);
$uid = uniqid();
$captcha = User::getCaptchaForm($uid);
?>
$captcha = User::getCaptchaForm($uid); ?>
<button class="btn btn-success no-outline" onclick="openDonationMoodal<?php echo $uid; ?>();">
<i class="fas fa-donate"></i> <small class="hidden-sm hidden-xs"><?php echo __($obj->donationWalletButtonLabel); ?></small>
</button>
@ -56,8 +55,7 @@ if ($obj->allowWalletDirectTransferDonation && !empty($video['users_id']) && cla
</div>
</div>
<?php
}
?>
} ?>
</form>
</div>
<div class="modal-footer">

View file

@ -1,21 +1,20 @@
<?php
if (!empty($_SESSION['channelName'])) {
unset($_GET['channelName']);
$params = array_merge($_GET, array('leaveChannel' => '1'));
$_GET['channelName'] = $_SESSION['channelName'];
$new_query_string = http_build_query($params);
$request_uri = explode("?", $_SERVER['REQUEST_URI']);
$leaveLink = $request_uri[0] . '?' . $new_query_string;
if(!empty($obj->showLeaveChannelButton)){
?>
<?php
if (!empty($_SESSION['channelName'])) {
unset($_GET['channelName']);
$params = array_merge($_GET, ['leaveChannel' => '1']);
$_GET['channelName'] = $_SESSION['channelName'];
$new_query_string = http_build_query($params);
$request_uri = explode("?", $_SERVER['REQUEST_URI']);
$leaveLink = $request_uri[0] . '?' . $new_query_string;
if (!empty($obj->showLeaveChannelButton)) {
?>
<li>
<a href="<?php echo $leaveLink; ?>" class="btn btn-default navbar-btn" data-toggle="tooltip" title="<?php echo __("Leave Channel"); ?>" data-placement="bottom" >
<span class="fa fa-times"></span> <span class="hidden-md hidden-sm hidden-mdx"><?php echo $_GET['channelName']; ?></span>
</a>
</li>
<?php
}
?>
<?php
} ?>
<script>
$('#mainNavbarLogo').on('click', function (e) {
e.preventDefault();
@ -23,6 +22,6 @@ if (!empty($_SESSION['channelName'])) {
document.location = url+'?leaveChannel=1';
});
</script>
<?php
}
<?php
}
?>

View file

@ -82,7 +82,7 @@ $imgh = 720;
<div class="form-group">
<label for="video_password"><?php echo __("This Video Requires a Password"); ?></label>
<?php
echo getInputPassword('video_password', 'class="form-control"', __("Password"));
echo getInputPassword('video_password', 'class="form-control"', __("Password"));
?>
</div>
<div class="row">

View file

@ -4,8 +4,8 @@ session_write_close();
header('Content-Type: application/json');
$name = "customizeUser.json.php";
$obj = ObjectYPT::getCache($name, 60);
if(empty($obj)){
if (empty($obj)) {
$obj = AVideoPlugin::getObjectData("CustomizeUser");
ObjectYPT::setCache($name, $obj);
}
echo json_encode($obj);
echo json_encode($obj);

View file

@ -1,4 +1,5 @@
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/captcha.php';
session_write_close();
@ -32,7 +33,7 @@ if (empty($wallet)) {
die(json_encode($obj));
}
if(empty($cu->disableCaptchaOnWalletDirectTransferDonation)){
if (empty($cu->disableCaptchaOnWalletDirectTransferDonation)) {
$valid = Captcha::validation(@$_POST['captcha']);
if (empty($valid)) {
@ -58,8 +59,7 @@ if (!empty($_POST['videos_id'])) {
$obj->error = false;
AVideoPlugin::afterDonation(User::getId(), $value, $videos_id, 0);
}
} else if (!empty($_POST['users_id'])) {
} elseif (!empty($_POST['users_id'])) {
$users_id = intval($_POST['users_id']);
if (empty($users_id)) {
$obj->msg = "User id is empty";

View file

@ -2,37 +2,38 @@
require_once '../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if(!User::isLogged()){
$obj->msg = "Not logged";
if (!User::isLogged()) {
$obj->msg = "Not logged";
die(json_encode($obj));
}
if(empty($_POST['type'])){
$obj->msg = "Type is empty";
if (empty($_POST['type'])) {
$obj->msg = "Type is empty";
die(json_encode($obj));
}
if(!isset($_POST['value'])){
$obj->msg = "value is empty";
if (!isset($_POST['value'])) {
$obj->msg = "value is empty";
die(json_encode($obj));
}
$cu = AVideoPlugin::loadPluginIfEnabled('CustomizeUser');
if(empty($cu)){
$obj->msg = "Plugin not enabled";
if (empty($cu)) {
$obj->msg = "Plugin not enabled";
die(json_encode($obj));
}
$obj->error = false;
switch ($_POST['type']) {
case 'userCanAllowFilesDownload':
CustomizeUser::setCanDownloadVideosFromUser(User::getId(), $_POST['value']=="true"?true:false);
CustomizeUser::setCanDownloadVideosFromUser(User::getId(), $_POST['value']=="true" ? true : false);
break;
case 'userCanAllowFilesShare':
CustomizeUser::setCanShareVideosFromUser(User::getId(), $_POST['value']=="true"?true:false);
CustomizeUser::setCanShareVideosFromUser(User::getId(), $_POST['value']=="true" ? true : false);
break;
}
die(json_encode($obj));
die(json_encode($obj));

View file

@ -1,16 +1,17 @@
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = '';
if(!User::isAdmin()){
if (!User::isAdmin()) {
$obj->msg = ('Must be admin');
die(json_encode($obj));
}
$users_id = intval(@$_REQUEST['users_id']);
if(empty($users_id)){
if (empty($users_id)) {
$obj->msg = ('Empty users_id');
die(json_encode($obj));
}
@ -22,4 +23,4 @@ $obj->response = User::setProfilePassword($users_id, $obj->ProfilePassword) ;
$obj->error = empty($obj->response);
die(json_encode($obj));
die(json_encode($obj));

View file

@ -3,6 +3,7 @@ require_once '../../videos/configuration.php';
if (!User::isAdmin()) {
forbiddenPage('Must be admin');
}
$users_id = intval(@$_REQUEST['users_id']);
if (empty($users_id)) {
forbiddenPage('Empty users_id');

View file

@ -1,16 +1,17 @@
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = '';
if(!User::isAdmin()){
if (!User::isAdmin()) {
$obj->msg = ('Must be admin');
die(json_encode($obj));
}
$users_id = intval(@$_REQUEST['users_id']);
if(empty($users_id)){
if (empty($users_id)) {
$obj->msg = ('Empty users_id');
die(json_encode($obj));
}
@ -22,4 +23,4 @@ $obj->response = User::setExtraSubscribers($users_id, $obj->ExtraSubscribers) ;
$obj->error = empty($obj->response);
die(json_encode($obj));
die(json_encode($obj));

View file

@ -1,5 +1,6 @@
<?php
require_once '../../videos/configuration.php';
if (!User::isAdmin()) {
forbiddenPage('Must be admin');
}

View file

@ -1,6 +1,6 @@
<?php
$uid = uniqid();
?>
<?php
$uid = uniqid();
?>
<div class="material-switch">
<input class="playerSwitchDefault" data-toggle="toggle" type="checkbox" value="" id="switch<?php echo $uid; ?>" <?php echo (CustomizeUser::canDownloadVideosFromUser($users_id)) ? "checked" : ""; ?>>
<label for="switch<?php echo $uid; ?>" class="label-primary"></label>

File diff suppressed because it is too large Load diff

View file

@ -1,392 +1,443 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/bootGrid.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
class LiveTransmition extends ObjectYPT {
protected $id, $title, $public, $saveTransmition, $users_id, $categories_id, $key, $description, $showOnTV, $password;
static function getSearchFieldsNames() {
return array('title');
}
static function getTableName() {
return 'live_transmitions';
}
function getId() {
return $this->id;
}
function getTitle() {
return $this->title;
}
function getPublic() {
return $this->public;
}
function getSaveTransmition() {
return $this->saveTransmition;
}
function getUsers_id() {
return $this->users_id;
}
function getCategories_id() {
return $this->categories_id;
}
function getKey() {
return $this->key;
}
function getDescription() {
return $this->description;
}
function setId($id) {
$this->id = $id;
}
function setTitle($title) {
global $global;
//$title = $global['mysqli']->real_escape_string($title);
$this->title = xss_esc($title);
}
function setPublic($public) {
$this->public = intval($public);
}
function setSaveTransmition($saveTransmition) {
$this->saveTransmition = $saveTransmition;
}
function setUsers_id($users_id) {
$this->users_id = $users_id;
}
function setCategories_id($categories_id) {
$this->categories_id = $categories_id;
}
function setKey($key) {
$this->key = $key;
}
function setDescription($description) {
global $global;
//$description = $global['mysqli']->real_escape_string($description);
$this->description = xss_esc($description);
}
function loadByUser($user_id) {
$user = self::getFromDbByUser($user_id);
if (empty($user))
return false;
foreach ($user as $key => $value) {
$this->$key = $value;
}
return true;
}
function loadByKey($uuid) {
$row = self::getFromKey($uuid);
if (empty($row))
return false;
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
static function getFromDbByUser($user_id) {
global $global;
$user_id = intval($user_id);
$sql = "SELECT * FROM " . static::getTableName() . " WHERE users_id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($user_id), true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
} else {
$user = false;
}
return $user;
}
static function createTransmitionIfNeed($user_id) {
if (empty($user_id)) {
return false;
}
$row = static::getFromDbByUser($user_id);
if ($row) {
return $row;
}
$l = new LiveTransmition(0);
$l->setTitle("Empty Title");
$l->setDescription("");
$l->setKey(uniqid());
$l->setCategories_id(1);
$l->setUsers_id($user_id);
$l->save();
return static::getFromDbByUser($user_id);
}
static function resetTransmitionKey($user_id) {
$row = static::getFromDbByUser($user_id);
$l = new LiveTransmition($row['id']);
$newKey = uniqid();
$l->setKey($newKey);
if($l->save()){
return $newKey;
}else{
return false;
}
}
static function getFromRequest() {
if(!empty($_REQUEST['live_schedule'])){
return LiveTransmition::getFromDbBySchedule($_REQUEST['live_schedule']);
}else if(!empty($_REQUEST['u'])){
return LiveTransmition::getFromDbByUserName($_REQUEST['u']);
}else if(!empty($_REQUEST['c'])){
return LiveTransmition::getFromDbByChannelName($_REQUEST['c']);
}
return false;
}
static function getFromDbByUserName($userName) {
global $global;
_mysql_connect();
$userName = $global['mysqli']->real_escape_string($userName);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($userName), true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
if(empty($user)){
return false;
}
return static::getFromDbByUser($user['id']);
} else {
return false;
}
}
static function getFromDbByChannelName($channelName) {
global $global;
_mysql_connect();
$channelName = $global['mysqli']->real_escape_string($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName), true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
if(empty($user)){
return false;
}
return static::getFromDbByUser($user['id']);
} else {
return false;
}
}
static function getFromDbBySchedule($live_schedule_id) {
global $global;
$live_schedule_id = intval($live_schedule_id);
$sql = "SELECT lt.*, ls.* FROM live_schedule ls "
. " LEFT JOIN " . static::getTableName() . " lt ON lt.users_id = ls.users_id "
. " WHERE ls.id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($live_schedule_id), true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
} else {
$user = false;
}
return $user;
}
static function keyExists($key, $checkSchedule = true) {
global $global;
if (!is_string($key)) {
return false;
}
if(Live::isAdaptiveTransmition($key)){
return false;
}
$key = Live::cleanUpKey($key);
$sql = "SELECT u.*, lt.*, lt.password as live_password FROM " . static::getTableName() . " lt "
. " LEFT JOIN users u ON u.id = users_id AND u.status='a' "
. " WHERE `key` = '$key' LIMIT 1";
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
if(!empty($row)){
$row['scheduled'] = 0;
}
if(!empty($row)){
$p = $row['live_password'];
$row = cleanUpRowFromDatabase($row);
$row['live_password'] = $p;
}
} else {
$row = false;
}
if($checkSchedule && empty($row)){
$row = Live_schedule::keyExists($key);
if(!empty($row)){
$row['scheduled'] = 1;
}
}
return $row;
}
function save() {
$this->public = intval($this->public);
$this->saveTransmition = intval($this->saveTransmition);
$this->showOnTV = intval($this->showOnTV);
if(empty($this->password)){
$this->password = '';
}
$id = parent::save();
Category::clearCacheCount();
Live::deleteStatsCache(true);
$socketObj = sendSocketMessageToAll(array('stats'=>getStatsNotifications()), "socketLiveONCallback");
return $id;
}
function deleteGroupsTrasmition() {
if (empty($this->id)) {
return false;
}
global $global;
$sql = "DELETE FROM live_transmitions_has_users_groups WHERE live_transmitions_id = ?";
return sqlDAL::writeSql($sql, "i", array($this->id));
}
function insertGroup($users_groups_id) {
global $global;
$sql = "INSERT INTO live_transmitions_has_users_groups (live_transmitions_id, users_groups_id) VALUES (?,?)";
return sqlDAL::writeSql($sql, "ii", array($this->id, $users_groups_id));
}
function isAPrivateLive(){
return !empty($this->getGroups());
}
function getGroups() {
$rows = array();
if (empty($this->id)) {
return $rows;
}
global $global;
$sql = "SELECT * FROM live_transmitions_has_users_groups WHERE live_transmitions_id = ?";
$res = sqlDAL::readSql($sql, "i", array($this->id));
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row["users_groups_id"];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
function userCanSeeTransmition() {
global $global;
require_once $global['systemRootPath'] . 'objects/userGroups.php';
require_once $global['systemRootPath'] . 'objects/user.php';
if (User::isAdmin()) {
return true;
}
/*
$password = $this->getPassword();
if(!empty($password) && !Live::passwordIsGood($this->getKey())){
return false;
}
*
*/
$transmitionGroups = $this->getGroups();
if (!empty($transmitionGroups)) {
if (empty($this->id)) {
return false;
}
if (!User::isLogged()) {
return false;
}
$userGroups = UserGroups::getUserGroups(User::getId());
if (empty($userGroups)) {
return false;
}
foreach ($userGroups as $ugvalue) {
foreach ($transmitionGroups as $tgvalue) {
if ($ugvalue['id'] == $tgvalue) {
return true;
}
}
}
return false;
} else {
return true;
}
}
static function getFromKey($key) {
global $global;
return self::keyExists($key);
}
static function keyNameFix($key){
$key = str_replace('/', '', $key);
if(!empty($_REQUEST['live_index']) && !preg_match("/.*-([0-9a-zA-Z]+)/", $key)){
if(!empty($_REQUEST['live_index']) && $_REQUEST['live_index']!=='false'){
$key .= "-{$_REQUEST['live_index']}";
}
}
if(!empty($_REQUEST['playlists_id_live']) && !preg_match("/.*_([0-9]+)/", $key)){
$key .= "_{$_REQUEST['playlists_id_live']}";
}
return $key;
}
function getShowOnTV() {
return $this->showOnTV;
}
function setShowOnTV($showOnTV) {
$this->showOnTV = $showOnTV;
}
function getPassword() {
return $this->password;
}
function setPassword($password): void {
$this->password = trim($password);
}
static function canSaveTransmition($users_id){
$lt = self::getFromDbByUser($users_id);
return !empty($lt['saveTransmition']);
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/bootGrid.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
class LiveTransmition extends ObjectYPT
{
protected $id;
protected $title;
protected $public;
protected $saveTransmition;
protected $users_id;
protected $categories_id;
protected $key;
protected $description;
protected $showOnTV;
protected $password;
public static function getSearchFieldsNames()
{
return ['title'];
}
public static function getTableName()
{
return 'live_transmitions';
}
public function getId()
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function getPublic()
{
return $this->public;
}
public function getSaveTransmition()
{
return $this->saveTransmition;
}
public function getUsers_id()
{
return $this->users_id;
}
public function getCategories_id()
{
return $this->categories_id;
}
public function getKey()
{
return $this->key;
}
public function getDescription()
{
return $this->description;
}
public function setId($id)
{
$this->id = $id;
}
public function setTitle($title)
{
global $global;
//$title = $global['mysqli']->real_escape_string($title);
$this->title = xss_esc($title);
}
public function setPublic($public)
{
$this->public = intval($public);
}
public function setSaveTransmition($saveTransmition)
{
$this->saveTransmition = $saveTransmition;
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function setCategories_id($categories_id)
{
$this->categories_id = $categories_id;
}
public function setKey($key)
{
$this->key = $key;
}
public function setDescription($description)
{
global $global;
//$description = $global['mysqli']->real_escape_string($description);
$this->description = xss_esc($description);
}
public function loadByUser($user_id)
{
$user = self::getFromDbByUser($user_id);
if (empty($user)) {
return false;
}
foreach ($user as $key => $value) {
$this->$key = $value;
}
return true;
}
public function loadByKey($uuid)
{
$row = self::getFromKey($uuid);
if (empty($row)) {
return false;
}
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
public static function getFromDbByUser($user_id)
{
global $global;
$user_id = intval($user_id);
$sql = "SELECT * FROM " . static::getTableName() . " WHERE users_id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", [$user_id], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
} else {
$user = false;
}
return $user;
}
public static function createTransmitionIfNeed($user_id)
{
if (empty($user_id)) {
return false;
}
$row = static::getFromDbByUser($user_id);
if ($row) {
return $row;
}
$l = new LiveTransmition(0);
$l->setTitle("Empty Title");
$l->setDescription("");
$l->setKey(uniqid());
$l->setCategories_id(1);
$l->setUsers_id($user_id);
$l->save();
return static::getFromDbByUser($user_id);
}
public static function resetTransmitionKey($user_id)
{
$row = static::getFromDbByUser($user_id);
$l = new LiveTransmition($row['id']);
$newKey = uniqid();
$l->setKey($newKey);
if ($l->save()) {
return $newKey;
} else {
return false;
}
}
public static function getFromRequest()
{
if (!empty($_REQUEST['live_schedule'])) {
return LiveTransmition::getFromDbBySchedule($_REQUEST['live_schedule']);
} elseif (!empty($_REQUEST['u'])) {
return LiveTransmition::getFromDbByUserName($_REQUEST['u']);
} elseif (!empty($_REQUEST['c'])) {
return LiveTransmition::getFromDbByChannelName($_REQUEST['c']);
}
return false;
}
public static function getFromDbByUserName($userName)
{
global $global;
_mysql_connect();
$userName = $global['mysqli']->real_escape_string($userName);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", [$userName], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
if (empty($user)) {
return false;
}
return static::getFromDbByUser($user['id']);
} else {
return false;
}
}
public static function getFromDbByChannelName($channelName)
{
global $global;
_mysql_connect();
$channelName = $global['mysqli']->real_escape_string($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", [$channelName], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
if (empty($user)) {
return false;
}
return static::getFromDbByUser($user['id']);
} else {
return false;
}
}
public static function getFromDbBySchedule($live_schedule_id)
{
global $global;
$live_schedule_id = intval($live_schedule_id);
$sql = "SELECT lt.*, ls.* FROM live_schedule ls "
. " LEFT JOIN " . static::getTableName() . " lt ON lt.users_id = ls.users_id "
. " WHERE ls.id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", [$live_schedule_id], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $data;
} else {
$user = false;
}
return $user;
}
public static function keyExists($key, $checkSchedule = true)
{
global $global;
if (!is_string($key)) {
return false;
}
if (Live::isAdaptiveTransmition($key)) {
return false;
}
$key = Live::cleanUpKey($key);
$sql = "SELECT u.*, lt.*, lt.password as live_password FROM " . static::getTableName() . " lt "
. " LEFT JOIN users u ON u.id = users_id AND u.status='a' "
. " WHERE `key` = '$key' LIMIT 1";
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
if (!empty($row)) {
$row['scheduled'] = 0;
}
if (!empty($row)) {
$p = $row['live_password'];
$row = cleanUpRowFromDatabase($row);
$row['live_password'] = $p;
}
} else {
$row = false;
}
if ($checkSchedule && empty($row)) {
$row = Live_schedule::keyExists($key);
if (!empty($row)) {
$row['scheduled'] = 1;
}
}
return $row;
}
public function save()
{
$this->public = intval($this->public);
$this->saveTransmition = intval($this->saveTransmition);
$this->showOnTV = intval($this->showOnTV);
if (empty($this->password)) {
$this->password = '';
}
$id = parent::save();
Category::clearCacheCount();
Live::deleteStatsCache(true);
$socketObj = sendSocketMessageToAll(['stats'=>getStatsNotifications()], "socketLiveONCallback");
return $id;
}
public function deleteGroupsTrasmition()
{
if (empty($this->id)) {
return false;
}
global $global;
$sql = "DELETE FROM live_transmitions_has_users_groups WHERE live_transmitions_id = ?";
return sqlDAL::writeSql($sql, "i", [$this->id]);
}
public function insertGroup($users_groups_id)
{
global $global;
$sql = "INSERT INTO live_transmitions_has_users_groups (live_transmitions_id, users_groups_id) VALUES (?,?)";
return sqlDAL::writeSql($sql, "ii", [$this->id, $users_groups_id]);
}
public function isAPrivateLive()
{
return !empty($this->getGroups());
}
public function getGroups()
{
$rows = [];
if (empty($this->id)) {
return $rows;
}
global $global;
$sql = "SELECT * FROM live_transmitions_has_users_groups WHERE live_transmitions_id = ?";
$res = sqlDAL::readSql($sql, "i", [$this->id]);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row["users_groups_id"];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public function userCanSeeTransmition()
{
global $global;
require_once $global['systemRootPath'] . 'objects/userGroups.php';
require_once $global['systemRootPath'] . 'objects/user.php';
if (User::isAdmin()) {
return true;
}
/*
$password = $this->getPassword();
if(!empty($password) && !Live::passwordIsGood($this->getKey())){
return false;
}
*
*/
$transmitionGroups = $this->getGroups();
if (!empty($transmitionGroups)) {
if (empty($this->id)) {
return false;
}
if (!User::isLogged()) {
return false;
}
$userGroups = UserGroups::getUserGroups(User::getId());
if (empty($userGroups)) {
return false;
}
foreach ($userGroups as $ugvalue) {
foreach ($transmitionGroups as $tgvalue) {
if ($ugvalue['id'] == $tgvalue) {
return true;
}
}
}
return false;
} else {
return true;
}
}
public static function getFromKey($key)
{
global $global;
return self::keyExists($key);
}
public static function keyNameFix($key)
{
$key = str_replace('/', '', $key);
if (!empty($_REQUEST['live_index']) && !preg_match("/.*-([0-9a-zA-Z]+)/", $key)) {
if (!empty($_REQUEST['live_index']) && $_REQUEST['live_index']!=='false') {
$key .= "-{$_REQUEST['live_index']}";
}
}
if (!empty($_REQUEST['playlists_id_live']) && !preg_match("/.*_([0-9]+)/", $key)) {
$key .= "_{$_REQUEST['playlists_id_live']}";
}
return $key;
}
public function getShowOnTV()
{
return $this->showOnTV;
}
public function setShowOnTV($showOnTV)
{
$this->showOnTV = $showOnTV;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password): void
{
$this->password = trim($password);
}
public static function canSaveTransmition($users_id)
{
$lt = self::getFromDbByUser($users_id);
return !empty($lt['saveTransmition']);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,110 +1,124 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/bootGrid.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
class LiveTransmitionHistoryLog extends ObjectYPT {
protected $id, $live_transmitions_history_id, $users_id, $session_id;
static function getSearchFieldsNames() {
return array();
}
static function getTableName() {
return 'live_transmition_history_log';
}
function getLive_transmitions_history_id() {
return $this->live_transmitions_history_id;
}
function getUsers_id() {
return $this->users_id;
}
function getSession_id() {
return $this->session_id;
}
function setLive_transmitions_history_id($live_transmitions_history_id) {
$this->live_transmitions_history_id = $live_transmitions_history_id;
}
function setUsers_id($users_id) {
$this->users_id = $users_id;
}
function setSession_id($session_id) {
$this->session_id = $session_id;
}
static function addLog($live_transmitions_history_id){
$session_id = session_id();
$users_id = intval(User::getId());
$log = new LiveTransmitionHistoryLog(0);
$log->setLive_transmitions_history_id($live_transmitions_history_id);
$log->setUsers_id($users_id);
$log->setSession_id($session_id);
$log->save();
}
function getFromHistoryAndSession($live_transmitions_history_id, $session_id){
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE live_transmitions_history_id = ? AND session_id = ? ORDER BY created 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,"is",array($live_transmitions_history_id, $session_id));
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
static function getAllFromHistory($live_transmitions_history_id) {
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE live_transmitions_history_id={$live_transmitions_history_id} ";
$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;
}
function save() {
$row = $this->getFromHistoryAndSession($this->live_transmitions_history_id, $this->session_id);
if(!empty($row)){
$this->id = $row['id'];
}
return parent::save();
}
static function deleteAllFromHistory($live_transmitions_history_id) {
global $global;
$live_transmitions_history_id = intval($live_transmitions_history_id);
if (!empty($live_transmitions_history_id)) {
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE live_transmitions_history_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", array($live_transmitions_history_id));
}
return false;
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once dirname(__FILE__) . '/../../../objects/bootGrid.php';
require_once dirname(__FILE__) . '/../../../objects/user.php';
class LiveTransmitionHistoryLog extends ObjectYPT
{
protected $id;
protected $live_transmitions_history_id;
protected $users_id;
protected $session_id;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'live_transmition_history_log';
}
public function getLive_transmitions_history_id()
{
return $this->live_transmitions_history_id;
}
public function getUsers_id()
{
return $this->users_id;
}
public function getSession_id()
{
return $this->session_id;
}
public function setLive_transmitions_history_id($live_transmitions_history_id)
{
$this->live_transmitions_history_id = $live_transmitions_history_id;
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function setSession_id($session_id)
{
$this->session_id = $session_id;
}
public static function addLog($live_transmitions_history_id)
{
$session_id = session_id();
$users_id = intval(User::getId());
$log = new LiveTransmitionHistoryLog(0);
$log->setLive_transmitions_history_id($live_transmitions_history_id);
$log->setUsers_id($users_id);
$log->setSession_id($session_id);
$log->save();
}
public function getFromHistoryAndSession($live_transmitions_history_id, $session_id)
{
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE live_transmitions_history_id = ? AND session_id = ? ORDER BY created 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, "is", [$live_transmitions_history_id, $session_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function getAllFromHistory($live_transmitions_history_id)
{
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE live_transmitions_history_id={$live_transmitions_history_id} ";
$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 function save()
{
$row = $this->getFromHistoryAndSession($this->live_transmitions_history_id, $this->session_id);
if (!empty($row)) {
$this->id = $row['id'];
}
return parent::save();
}
public static function deleteAllFromHistory($live_transmitions_history_id)
{
global $global;
$live_transmitions_history_id = intval($live_transmitions_history_id);
if (!empty($live_transmitions_history_id)) {
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE live_transmitions_history_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", [$live_transmitions_history_id]);
}
return false;
}
}

View file

@ -2,98 +2,121 @@
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Live_restreams extends ObjectYPT {
class Live_restreams extends ObjectYPT
{
protected $id;
protected $name;
protected $stream_url;
protected $stream_key;
protected $status;
protected $parameters;
protected $users_id;
protected $id,$name,$stream_url,$stream_key,$status,$parameters,$users_id;
static function getSearchFieldsNames() {
return array('name','stream_url','stream_key','parameters');
public static function getSearchFieldsNames()
{
return ['name','stream_url','stream_key','parameters'];
}
static function getTableName() {
public static function getTableName()
{
return 'live_restreams';
}
function setId($id) {
public function setId($id)
{
$this->id = intval($id);
}
function setName($name) {
}
public function setName($name)
{
$this->name = $name;
}
function setStream_url($stream_url) {
}
public function setStream_url($stream_url)
{
$this->stream_url = $stream_url;
}
function setStream_key($stream_key) {
}
public function setStream_key($stream_key)
{
$this->stream_key = $stream_key;
}
function setStatus($status) {
}
public function setStatus($status)
{
$this->status = $status;
}
function setParameters($parameters) {
}
public function setParameters($parameters)
{
$this->parameters = $parameters;
}
function setUsers_id($users_id) {
}
public function setUsers_id($users_id)
{
$this->users_id = intval($users_id);
}
function getId() {
}
public function getId()
{
return intval($this->id);
}
function getName() {
}
public function getName()
{
return $this->name;
}
function getStream_url() {
}
public function getStream_url()
{
return $this->stream_url;
}
function getStream_key() {
}
public function getStream_key()
{
return $this->stream_key;
}
function getStatus() {
}
public function getStatus()
{
return $this->status;
}
function getParameters() {
}
public function getParameters()
{
return $this->parameters;
}
function getUsers_id() {
}
public function getUsers_id()
{
return intval($this->users_id);
}
}
static function getAllFromUser($users_id, $status = 'a') {
public static function getAllFromUser($users_id, $status = 'a')
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$users_id = intval($users_id);
if(empty($users_id)){
if (empty($users_id)) {
return false;
}
$sql = "SELECT * FROM " . static::getTableName() . " WHERE users_id = $users_id ";
if(!empty($status)){
$sql .= " AND status = '$status' " ;
if (!empty($status)) {
$sql .= " AND status = '$status' " ;
}
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -103,5 +126,4 @@ class Live_restreams extends ObjectYPT {
}
return $rows;
}
}

View file

@ -2,19 +2,34 @@
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Live_schedule extends ObjectYPT {
class Live_schedule extends ObjectYPT
{
protected $id;
protected $title;
protected $description;
protected $key;
protected $users_id;
protected $live_servers_id;
protected $scheduled_time;
protected $timezone;
protected $status;
protected $poster;
protected $public;
protected $saveTransmition;
protected $showOnTV;
protected $id, $title, $description, $key, $users_id, $live_servers_id, $scheduled_time, $timezone, $status, $poster, $public, $saveTransmition, $showOnTV;
static function getSearchFieldsNames() {
return array('title', 'description', 'key', 'timezone', 'poster');
public static function getSearchFieldsNames()
{
return ['title', 'description', 'key', 'timezone', 'poster'];
}
static function getTableName() {
public static function getTableName()
{
return 'live_schedule';
}
static function getAllUsers() {
public static function getAllUsers()
{
global $global;
$table = "users";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
@ -23,7 +38,7 @@ class Live_schedule extends ObjectYPT {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -34,7 +49,8 @@ class Live_schedule extends ObjectYPT {
return $rows;
}
static function getAllLive_servers() {
public static function getAllLive_servers()
{
global $global;
$table = "live_servers";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
@ -43,7 +59,7 @@ class Live_schedule extends ObjectYPT {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -54,7 +70,8 @@ class Live_schedule extends ObjectYPT {
return $rows;
}
static function getPosterPaths($live_schedule_id) {
public static function getPosterPaths($live_schedule_id)
{
$live_schedule_id = intval($live_schedule_id);
if (empty($live_schedule_id)) {
return false;
@ -62,7 +79,7 @@ class Live_schedule extends ObjectYPT {
$subdir = "live_schedule_posters";
$array = array();
$array = [];
$array['path'] = getVideosDir() . $subdir . DIRECTORY_SEPARATOR;
@ -79,7 +96,8 @@ class Live_schedule extends ObjectYPT {
return $array;
}
static function getPosterURL($live_schedule_id) {
public static function getPosterURL($live_schedule_id)
{
$paths = self::getPosterPaths($live_schedule_id);
if (file_exists($paths['path'])) {
return $paths['url'];
@ -88,24 +106,25 @@ class Live_schedule extends ObjectYPT {
}
}
static function getAll($users_id=0, $activeHoursAgo=false) {
public static function getAll($users_id=0, $activeHoursAgo=false)
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$users_id = intval($users_id);
$sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 ";
if(!empty($users_id)){
if (!empty($users_id)) {
$sql .= " AND users_id = $users_id ";
}
if($activeHoursAgo){
if ($activeHoursAgo) {
$sql .= " AND scheduled_time > DATE_SUB(NOW(), INTERVAL {$activeHoursAgo} HOUR) ";
}
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$row['future'] = isTimeForFuture($row['scheduled_time'], $row['timezone']);
@ -122,13 +141,14 @@ class Live_schedule extends ObjectYPT {
return $rows;
}
public static function getAllActiveLimit($limit = 10) {
public static function getAllActiveLimit($limit = 10)
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
// to convert time must load time zone table into mysql
$sql = "SELECT * FROM " . static::getTableName() . " WHERE status='a' "
. " AND (CONVERT_TZ(scheduled_time, timezone, @@session.time_zone ) > NOW() || scheduled_time > NOW()) "
. " ORDER BY scheduled_time ASC LIMIT {$limit} ";
@ -136,7 +156,7 @@ class Live_schedule extends ObjectYPT {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -147,128 +167,154 @@ class Live_schedule extends ObjectYPT {
return $rows;
}
function setId($id) {
public function setId($id)
{
$this->id = intval($id);
}
function setTitle($title) {
public function setTitle($title)
{
$this->title = $title;
}
function setDescription($description) {
public function setDescription($description)
{
$this->description = $description;
}
function setKey($key) {
public function setKey($key)
{
$this->key = $key;
}
function setUsers_id($users_id) {
public function setUsers_id($users_id)
{
$this->users_id = intval($users_id);
}
function setLive_servers_id($live_servers_id) {
public function setLive_servers_id($live_servers_id)
{
$this->live_servers_id = intval($live_servers_id);
}
function setScheduled_time($scheduled_time) {
public function setScheduled_time($scheduled_time)
{
$this->scheduled_time = $scheduled_time;
}
private function _setTimezone($timezone) {
private function _setTimezone($timezone)
{
$this->timezone = $timezone;
}
function setStatus($status) {
public function setStatus($status)
{
$this->status = $status;
}
function setPoster($poster) {
public function setPoster($poster)
{
$this->poster = $poster;
}
function setPublic($public) {
public function setPublic($public)
{
$this->public = intval($public);
}
function setSaveTransmition($saveTransmition) {
public function setSaveTransmition($saveTransmition)
{
$this->saveTransmition = intval($saveTransmition);
}
function setShowOnTV($showOnTV) {
public function setShowOnTV($showOnTV)
{
$this->showOnTV = intval($showOnTV);
}
function getId() {
public function getId()
{
return intval($this->id);
}
function getTitle() {
public function getTitle()
{
return $this->title;
}
function getDescription() {
public function getDescription()
{
return $this->description;
}
function getKey() {
public function getKey()
{
return $this->key;
}
function getUsers_id() {
public function getUsers_id()
{
return intval($this->users_id);
}
function getLive_servers_id() {
public function getLive_servers_id()
{
return intval($this->live_servers_id);
}
function getScheduled_time() {
public function getScheduled_time()
{
return $this->scheduled_time;
}
function getTimezone() {
public function getTimezone()
{
return $this->timezone;
}
function getStatus() {
public function getStatus()
{
return $this->status;
}
function getPoster() {
public function getPoster()
{
return $this->poster;
}
function getPublic() {
public function getPublic()
{
return intval($this->public);
}
function getSaveTransmition() {
public function getSaveTransmition()
{
return intval($this->saveTransmition);
}
function getShowOnTV() {
public function getShowOnTV()
{
return intval($this->showOnTV);
}
function save() {
public function save()
{
if (empty($this->live_servers_id)) {
$this->live_servers_id = 'NULL';
}
if (empty($this->public)) {
$this->public = 'NULL';
}
if (empty($this->saveTransmition)) {
$this->saveTransmition = 'NULL';
}
if (empty($this->showOnTV)) {
$this->showOnTV = 'NULL';
}
if (empty($this->key)) {
$this->key = uniqid();
}
@ -281,7 +327,7 @@ class Live_schedule extends ObjectYPT {
$id = parent::save();
if (!empty($id)) {
$array = array();
$array = [];
$array['users_id'] = $this->users_id;
$array['stats'] = getStatsNotifications(true);
$array['key'] = $this->key;
@ -292,27 +338,30 @@ class Live_schedule extends ObjectYPT {
}
return $id;
}
public function delete() {
$t = new Live_schedule($this->id);
$array = setLiveKey($t->key, $t->live_servers_id);
$id = parent::delete();
public function delete()
{
$t = new Live_schedule($this->id);
$array = setLiveKey($t->key, $t->live_servers_id);
$id = parent::delete();
if (!empty($id)) {
$array['stats'] = getStatsNotifications(true);
Live::notifySocketStats("socketLiveOFFCallback", $array);
self::clearScheduleCache();
}
}
return $id;
}
static function clearScheduleCache(){
public static function clearScheduleCache()
{
clearCache(true);
deleteStatsNotifications();
//ObjectYPT::deleteAllSessionCache();
ObjectYPT::deleteALLCache();
}
static function keyExists($key) {
public static function keyExists($key)
{
global $global;
if (!is_string($key)) {
return false;

View file

@ -2,146 +2,193 @@
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Live_servers extends ObjectYPT {
class Live_servers extends ObjectYPT
{
protected $id;
protected $name;
protected $url;
protected $status;
protected $rtmp_server;
protected $playerServer;
protected $stats_url;
protected $disableDVR;
protected $disableGifThumbs;
protected $useAadaptiveMode;
protected $protectLive;
protected $getRemoteFile;
protected $restreamerURL;
protected $controlURL;
protected $webRTC_server;
protected $id, $name, $url, $status, $rtmp_server, $playerServer, $stats_url, $disableDVR, $disableGifThumbs, $useAadaptiveMode, $protectLive, $getRemoteFile, $restreamerURL, $controlURL, $webRTC_server;
static function getSearchFieldsNames() {
return array('name', 'url', 'rtmp_server', 'playerServer', 'stats_url', 'getRemoteFile');
public static function getSearchFieldsNames()
{
return ['name', 'url', 'rtmp_server', 'playerServer', 'stats_url', 'getRemoteFile'];
}
static function getTableName() {
public static function getTableName()
{
return 'live_servers';
}
function setId($id) {
public function setId($id)
{
$this->id = intval($id);
}
function setName($name) {
public function setName($name)
{
$this->name = $name;
}
function setUrl($url) {
public function setUrl($url)
{
$this->url = $url;
}
function setStatus($status) {
public function setStatus($status)
{
$this->status = $status;
}
function setRtmp_server($rtmp_server) {
public function setRtmp_server($rtmp_server)
{
$this->rtmp_server = $rtmp_server;
}
function setPlayerServer($playerServer) {
public function setPlayerServer($playerServer)
{
$this->playerServer = $playerServer;
}
function setStats_url($stats_url) {
public function setStats_url($stats_url)
{
$this->stats_url = $stats_url;
}
function setDisableDVR($disableDVR) {
public function setDisableDVR($disableDVR)
{
$this->disableDVR = intval($disableDVR);
}
function setDisableGifThumbs($disableGifThumbs) {
public function setDisableGifThumbs($disableGifThumbs)
{
$this->disableGifThumbs = intval($disableGifThumbs);
}
function setUseAadaptiveMode($useAadaptiveMode) {
public function setUseAadaptiveMode($useAadaptiveMode)
{
$this->useAadaptiveMode = intval($useAadaptiveMode);
}
function setProtectLive($protectLive) {
public function setProtectLive($protectLive)
{
$this->protectLive = intval($protectLive);
}
function setGetRemoteFile($getRemoteFile) {
public function setGetRemoteFile($getRemoteFile)
{
$this->getRemoteFile = $getRemoteFile;
}
function getId() {
public function getId()
{
return intval($this->id);
}
function getName() {
public function getName()
{
return $this->name;
}
function getUrl() {
public function getUrl()
{
return $this->url;
}
function getStatus() {
public function getStatus()
{
return $this->status;
}
function getRtmp_server() {
public function getRtmp_server()
{
return trim($this->rtmp_server);
}
function getPlayerServer() {
public function getPlayerServer()
{
return $this->playerServer;
}
function getStats_url() {
public function getStats_url()
{
return $this->stats_url;
}
function getDisableDVR() {
public function getDisableDVR()
{
return intval($this->disableDVR);
}
function getDisableGifThumbs() {
public function getDisableGifThumbs()
{
return intval($this->disableGifThumbs);
}
function getUseAadaptiveMode() {
public function getUseAadaptiveMode()
{
return intval($this->useAadaptiveMode);
}
function getProtectLive() {
public function getProtectLive()
{
return intval($this->protectLive);
}
function getGetRemoteFile() {
public function getGetRemoteFile()
{
return $this->getRemoteFile;
}
function getRestreamerURL() {
public function getRestreamerURL()
{
return $this->restreamerURL;
}
function setRestreamerURL($restreamerURL) {
public function setRestreamerURL($restreamerURL)
{
$this->restreamerURL = $restreamerURL;
}
function getControlURL() {
public function getControlURL()
{
return $this->controlURL;
}
function setControlURL($controlURL) {
public function setControlURL($controlURL)
{
$this->controlURL = $controlURL;
}
function getwebRTC_server() {
public function getwebRTC_server()
{
return $this->webRTC_server;
}
function setwebRTC_server($webRTC_server) {
public function setwebRTC_server($webRTC_server)
{
$this->webRTC_server = addLastSlash($webRTC_server);
}
static function getStatsFromId($live_servers_id, $force_recreate = false) {
public static function getStatsFromId($live_servers_id, $force_recreate = false)
{
global $_getStatsFromId;
if(empty($force_recreate)){
if(!isset($_getStatsFromId)){
$_getStatsFromId = array();
if (empty($force_recreate)) {
if (!isset($_getStatsFromId)) {
$_getStatsFromId = [];
}
if(isset($_getStatsFromId[$live_servers_id])){
if (isset($_getStatsFromId[$live_servers_id])) {
return $_getStatsFromId[$live_servers_id];
}
}
@ -149,15 +196,16 @@ class Live_servers extends ObjectYPT {
if (empty($ls->getStatus()) || $ls->getStatus()=='i') {
_error_log("Live_servers:: getStatsFromId ERROR ".json_encode($ls));
$_getStatsFromId[$live_servers_id] = false;
}else{
} else {
$_getStatsFromId[$live_servers_id] = Live::_getStats($live_servers_id, $force_recreate);
}
return $_getStatsFromId[$live_servers_id];
}
static function getAllActive() {
public static function getAllActive()
{
global $global, $liveServersgetAllActive;
if(isset($liveServersgetAllActive)){
if (isset($liveServersgetAllActive)) {
return $liveServersgetAllActive;
}
if (!static::isTableInstalled()) {
@ -169,7 +217,7 @@ class Live_servers extends ObjectYPT {
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
@ -181,9 +229,10 @@ class Live_servers extends ObjectYPT {
return $rows;
}
static function getServerFromRTMPHost($rtmpHostURI) {
public static function getServerFromRTMPHost($rtmpHostURI)
{
$obj = AVideoPlugin::getObjectData('Live');
if(empty($obj->useLiveServers)){
if (empty($obj->useLiveServers)) {
return 0;
}
global $global;
@ -203,7 +252,8 @@ class Live_servers extends ObjectYPT {
return $row;
}
static function getServerIdFromRTMPHost($rtmpHostURI) {
public static function getServerIdFromRTMPHost($rtmpHostURI)
{
$data = self::getServerFromRTMPHost($rtmpHostURI);
if ($data) {
$row = $data['id'];
@ -213,23 +263,23 @@ class Live_servers extends ObjectYPT {
return intval($row);
}
public function save() {
public function save()
{
$id = parent::save();
if($id){
if ($id) {
_session_start();
$_SESSION['useAadaptiveMode'] = array();
$_SESSION['playerServer'] = array();
$_SESSION['useAadaptiveMode'] = [];
$_SESSION['playerServer'] = [];
}
return $id;
}
public function delete() {
if(!empty($this->id)){
public function delete()
{
if (!empty($this->id)) {
LiveTransmitionHistory::deleteAllFromLiveServer($this->id);
}
return parent::delete();
}
}

View file

@ -1,4 +1,5 @@
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
if (!isset($global['systemRootPath'])) {
$configFile = '../../videos/configuration.php';
@ -31,4 +32,4 @@ if (!file_exists($lockFile)) {
} else {
_error_log("Live:asyncGetStats: {$url} is already processing");
}
unlink($lockFile);
unlink($lockFile);

View file

@ -19,12 +19,12 @@ foreach ($files as $file) {
preg_match($pattern, $file, $matches);
if (!empty($matches[1])) {
$filePath = $file;
$postFields = array(
$postFields = [
"app" => "live",
"tcurl" => "rtmp://$liveServerURL:1935/live",
"name" => $matches[1],
"path" => $filePath
);
"path" => $filePath,
];
$target = $streamerServerURL . "plugin/Live/on_record_done.php?secretRecorderKey={$secretRecorderKey}";
echo "Sending to $target filesize=". humanFileSize(filesize($filePath))." ". json_encode($postFields).PHP_EOL;
$curl = curl_init();
@ -33,8 +33,8 @@ foreach ($files as $file) {
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);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$r = curl_exec($curl);
if ($errno = curl_errno($curl)) {
$error_message = curl_strerror($errno);
@ -44,12 +44,13 @@ foreach ($files as $file) {
echo " **** Success ".$r.PHP_EOL;
}
curl_close($curl);
}else{
} else {
echo "ERROR pattern does not match ".PHP_EOL;
}
}
function humanFileSize($size, $unit = "") {
function humanFileSize($size, $unit = "")
{
if ((!$unit && $size >= 1 << 30) || $unit == "GB") {
return number_format($size / (1 << 30), 2) . "GB";
}
@ -63,4 +64,4 @@ function humanFileSize($size, $unit = "") {
}
return number_format($size) . " bytes";
}
}

View file

@ -3,7 +3,7 @@ require_once '../../videos/configuration.php';
$key = @$_REQUEST['key'];
if(empty($key)){
if (empty($key)) {
forbiddenPage('Key is undefined');
}
@ -94,7 +94,7 @@ $imgh = 360;
<div class="form-group">
<label for="live_password"><?php echo __("This Live Requires a Password"); ?></label>
<?php
echo getInputPassword('live_password', 'class="form-control"', __("Password"));
echo getInputPassword('live_password', 'class="form-control"', __("Password"));
?>
</div>
<div class="row">

View file

@ -77,6 +77,7 @@ switch ($obj->command) {
break;
case "drop_publisher_reset_key":
$obj->newkey = LiveTransmition::resetTransmitionKey($l->getUsers_id());
// no break
case "drop_publisher":
//http://server.com/control/drop/publisher|subscriber|client?srv=SRV&app=APP&name=NAME&addr=ADDR&clientid=CLIENTID
$obj->commandURL = Live::getDropURL($obj->key, $obj->live_servers_id);

View file

@ -12,4 +12,4 @@ $key = $argv[1];
$live_servers_id = intval(@$argv[2]);
$start = intval(@$argv[3]);
Live::controlRecording($key, $live_servers_id, $start);
Live::controlRecording($key, $live_servers_id, $start);

View file

@ -1,15 +1,16 @@
<?php
$lifetime = 300;
if (empty($_REQUEST['format'])) {
$_REQUEST['format'] = "png";
header('Content-Type: image/x-png');
} else if ($_REQUEST['format'] === 'jpg') {
} elseif ($_REQUEST['format'] === 'jpg') {
header('Content-Type: image/jpg');
} else if ($_REQUEST['format'] === 'gif') {
} elseif ($_REQUEST['format'] === 'gif') {
header('Content-Type: image/gif');
$lifetime *= 3;
} else if ($_REQUEST['format'] === 'webp') {
} elseif ($_REQUEST['format'] === 'webp') {
header('Content-Type: image/webp');
$lifetime *= 3;
} else {
@ -23,10 +24,10 @@ $f = md5(@$_REQUEST['u'] . @$_REQUEST['live_servers_id'] . @$_REQUEST['live_inde
$cacheFileImageName = dirname(__FILE__) . "/../../videos/cache/liveImage_{$f}.{$_REQUEST['format']}";
if (file_exists($cacheFileImageName) && (time() - $lifetime <= filemtime($cacheFileImageName))) {
$content = file_get_contents($cacheFileImageName);
if(!empty($content)){
if (!empty($content)) {
echo $content;
exit;
}
}
}
require_once dirname(__FILE__) . '/../../videos/configuration.php';
@ -41,7 +42,7 @@ if (!empty($_GET['c'])) {
}
$livet = LiveTransmition::getFromRequest();
//header('Content-Type: text/plain');var_dump($livet);exit;
if(!empty($_REQUEST['live_schedule']) && !empty($livet['scheduled_time']) && isTimeForFuture($livet['scheduled_time'], $livet['timezone'])){
if (!empty($_REQUEST['live_schedule']) && !empty($livet['scheduled_time']) && isTimeForFuture($livet['scheduled_time'], $livet['timezone'])) {
$array = Live_schedule::getPosterPaths($_REQUEST['live_schedule']);
$uploadedPoster = $array['path'];
header('Content-Type: image/jpg');
@ -61,7 +62,7 @@ if (empty($livet)) {
} else {
_error_log('getImage: File NOT exists 1 ' . $uploadedPoster);
}
} else if (!Live::isLive($livet['users_id'])) {
} elseif (!Live::isLive($livet['users_id'])) {
$uploadedPoster = $global['systemRootPath'] . Live::getPoster($livet['users_id'], $_REQUEST['live_servers_id']);
//var_dump($livet['users_id'], $_REQUEST['live_servers_id'],$uploadedPoster, empty($livet), Live::isLive($livet['users_id']) );exit;
if (file_exists($uploadedPoster)) {
@ -95,7 +96,7 @@ if (!empty($_REQUEST['live_index']) && $_REQUEST['live_index'] !== 'false') {
$name = "getLiveImage_{$uuid}_{$_REQUEST['format']}";
$result = ObjectYPT::getCache($name, $lifetime, true);
$socketMessage = array();
$socketMessage = [];
$socketMessage['cacheName1'] = $name;
$socketMessage['iscache'] = !empty($result);
$socketMessage['src'] = getSelfURI();
@ -121,7 +122,7 @@ if (!empty($result) && !Live::isDefaultImage($result)) {
$url = "{$encoderURL}objects/getImage.php";
$url = addQueryStringParameter($url, 'base64Url', base64_encode($video));
$url = addQueryStringParameter($url, 'format', $_REQUEST['format']);
//_error_log("Live:getImage $url");
//header('Content-Type: text/plain');var_dump($url);exit;
session_write_close();
@ -131,7 +132,6 @@ if (!empty($result) && !Live::isDefaultImage($result)) {
if (empty($content)) {
echo file_get_contents($filename);
} else {
}
ob_end_clean();
@ -150,12 +150,11 @@ if (!empty($result) && !Live::isDefaultImage($result)) {
//$socketObj = sendSocketMessageToAll($socketMessage, 'socketLiveImageUpdateCallback');
}
} else {
$result = file_get_contents($filename);
if(!Live::isDefaultImage($result)){
if (!Live::isDefaultImage($result)) {
copy($filename, $cacheFileImageName);
}
echo $result;
//_error_log("Live:getImage Get default image ");
}
}
}

View file

@ -1,6 +1,6 @@
<li>
<a href="#" onclick="avideoModalIframeFull(webSiteRootURL+'plugin/Live');return false;" data-toggle="tooltip" title="<?php echo __($buttonTitle); ?>" data-placement="left"
class="faa-parent animated-hover">
<i class="fas fa-circle faa-flash" style="color: red;" ></i> <?php echo $buttonTitle; ?>
<i class="fas fa-circle faa-flash" style="color: red;" ></i> <?php echo $buttonTitle; ?>
</a>
</li>

View file

@ -21,16 +21,16 @@ if (!empty($_GET['c'])) {
if (!empty($_GET['u']) && !empty($_GET['embedv2'])) {
include $global['systemRootPath'] . 'plugin/Live/view/videoEmbededV2.php';
exit;
} else if (!empty($_GET['u']) && !empty($_GET['embed'])) {
} elseif (!empty($_GET['u']) && !empty($_GET['embed'])) {
include $global['systemRootPath'] . 'plugin/Live/view/videoEmbeded.php';
exit;
} else if (!empty($_GET['u'])) {
} elseif (!empty($_GET['u'])) {
include $global['systemRootPath'] . 'plugin/Live/view/modeYoutubeLive.php';
exit;
} else if (!User::isLogged()) {
} elseif (!User::isLogged()) {
gotToLoginAndComeBackHere("");
exit;
} else if (!User::canStream()) {
} elseif (!User::canStream()) {
forbiddenPage(__($obj->streamDeniedMsg));
}
@ -45,7 +45,7 @@ if (!empty($_GET['users_id']) && User::isAdmin()) {
// if user already have a key
$trasnmition = LiveTransmition::createTransmitionIfNeed($users_id);
$getLiveKey = array('key' => $trasnmition['key'], 'live_servers_id' => Live::getLiveServersIdRequest());
$getLiveKey = ['key' => $trasnmition['key'], 'live_servers_id' => Live::getLiveServersIdRequest()];
setLiveKey($trasnmition['key'], Live::getLiveServersIdRequest(), @$_REQUEST['live_index']);
if (!empty($_GET['resetKey'])) {
LiveTransmition::resetTransmitionKey($users_id);
@ -127,8 +127,7 @@ if (!empty($chat2) && !empty($chat2->useStaticLayout)) {
$liveStreamObject = new LiveStreamObject($trasnmition['key'], 0, @$_REQUEST['live_index'], 0);
$key = $liveStreamObject->getKeyWithIndex(true);
$activeServerFound = true;
$_REQUEST['live_servers_id'] = 0;
?>
$_REQUEST['live_servers_id'] = 0; ?>
<li class="active <?php echo getCSSAnimationClassAndStyle('animate__fadeInLeft', 'menu'); ?>">
<a href="<?php echo $global['webSiteRootURL']; ?>plugin/Live/?live_servers_id=0">
<i class="fas fa-broadcast-tower"></i> <?php echo __("Local Server"); ?>
@ -147,12 +146,11 @@ if (!empty($chat2) && !empty($chat2->useStaticLayout)) {
$activeServerFound = true;
$active = "active";
}
} else if ($index == 0) {
} elseif ($index == 0) {
$_REQUEST['live_servers_id'] = $value['id'];
$activeServerFound = true;
$active = "active";
}
?>
} ?>
<li class="<?php echo $active; ?> <?php echo getCSSAnimationClassAndStyle('animate__fadeInLeft', 'menu'); ?>">
<a href="<?php echo $global['webSiteRootURL']; ?>plugin/Live/?live_servers_id=<?php echo $value['id']; ?>">
<i class="fas fa-broadcast-tower"></i> <?php echo $value['name']; ?>
@ -167,12 +165,12 @@ if (!empty($chat2) && !empty($chat2->useStaticLayout)) {
}
}
if (Live::canStreamWithMeet()) {
?>
?>
<button onclick="avideoModalIframeFullScreen(webSiteRootURL + 'plugin/Meet/');" class="btn btn-default pull-right"><i class="fas fa-comments"></i> <?php echo __("Meet"); ?></button>
<?php
}
if (Live::canStreamWithWebRTC()) {
?>
?>
<button onclick="avideoModalIframeFullScreen(webSiteRootURL + 'plugin/Live/webcamFullscreen.php?avideoIframe=1');" class="btn btn-default pull-right"><i class="fas fa-camera"></i> <?php echo __("Webcam"); ?></button>
<?php
}

View file

@ -1,3 +1,3 @@
<?php
include $global['systemRootPath'] . 'plugin/Live/tabs/tabStreamSettings.php';
?>

Some files were not shown because too many files have changed in this diff Show more