1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-03 01:39:24 +02:00

Fix git update

This commit is contained in:
Daniel 2022-03-14 14:44:06 -03:00
parent af5622a4e9
commit 24a25e4f41
714 changed files with 179203 additions and 179203 deletions

View file

@ -1,78 +1,78 @@
<div id="adsFormModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<?php echo __("Ad Overlay Code"); ?>
<span class="label label-success adsStatus">Ads Active</span>
<span class="label label-danger adsStatus">Ads Inacitive</span>
</h4>
</div>
<div class="modal-body">
<textarea class="form-control" rows="10" id="addOverlayCode"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal"><i class="fas fa-times"></i> <?php echo __("Close"); ?></button>
<button class="btn btn-success " type="button" onclick="saveCode(true, false)"><?php echo __("Approve Ad Code") ?></button>
<button class="btn btn-warning" type="button" onclick="saveCode(false, false)"><?php echo __("Disapprove Ad Code") ?></button>
<button class="btn btn-danger" type="button" onclick="saveCode(false, true)"><?php echo __("Disapprove and Delete Ad Code") ?></button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
var ad_overlay_users_id
function adsUser(users_id){
modal.showPleaseWait();
$('.adsStatus').hide();
$( "#addOverlayCode" ).text('');
ad_overlay_users_id = users_id;
$('#adsFormModal').modal();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/AD_Overlay/getCode.json.php?users_id=' + users_id,
success: function (response) {
$( "#addOverlayCode" ).text(response.msg);
if(response.status == 'a'){
$('.adsStatus.label-success').fadeIn();
}else{
$('.adsStatus.label-danger').fadeIn();
}
modal.hidePleaseWait();
}
});
}
function saveCode(approveAd, deleteAd) {
modal.showPleaseWait();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/AD_Overlay/saveCode.json.php',
data: {
"addOverlayCode": $('#addOverlayCode').val(),
"users_id": ad_overlay_users_id,
"approveAd": approveAd,
"deleteAd": deleteAd
},
type: 'post',
success: function (response) {
if (response.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", response.error, "error");
modal.hidePleaseWait();
} else {
avideoAlert("<?php echo __("Congratulations!"); ?>", "<?php echo __("Your code has been saved!"); ?>", "success");
adsUser(ad_overlay_users_id);
}
//modal.hidePleaseWait();
}
});
}
$(document).ready(function () {
});
<div id="adsFormModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">
<?php echo __("Ad Overlay Code"); ?>
<span class="label label-success adsStatus">Ads Active</span>
<span class="label label-danger adsStatus">Ads Inacitive</span>
</h4>
</div>
<div class="modal-body">
<textarea class="form-control" rows="10" id="addOverlayCode"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal"><i class="fas fa-times"></i> <?php echo __("Close"); ?></button>
<button class="btn btn-success " type="button" onclick="saveCode(true, false)"><?php echo __("Approve Ad Code") ?></button>
<button class="btn btn-warning" type="button" onclick="saveCode(false, false)"><?php echo __("Disapprove Ad Code") ?></button>
<button class="btn btn-danger" type="button" onclick="saveCode(false, true)"><?php echo __("Disapprove and Delete Ad Code") ?></button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
var ad_overlay_users_id
function adsUser(users_id){
modal.showPleaseWait();
$('.adsStatus').hide();
$( "#addOverlayCode" ).text('');
ad_overlay_users_id = users_id;
$('#adsFormModal').modal();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/AD_Overlay/getCode.json.php?users_id=' + users_id,
success: function (response) {
$( "#addOverlayCode" ).text(response.msg);
if(response.status == 'a'){
$('.adsStatus.label-success').fadeIn();
}else{
$('.adsStatus.label-danger').fadeIn();
}
modal.hidePleaseWait();
}
});
}
function saveCode(approveAd, deleteAd) {
modal.showPleaseWait();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/AD_Overlay/saveCode.json.php',
data: {
"addOverlayCode": $('#addOverlayCode').val(),
"users_id": ad_overlay_users_id,
"approveAd": approveAd,
"deleteAd": deleteAd
},
type: 'post',
success: function (response) {
if (response.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", response.error, "error");
modal.hidePleaseWait();
} else {
avideoAlert("<?php echo __("Congratulations!"); ?>", "<?php echo __("Your code has been saved!"); ?>", "success");
adsUser(ad_overlay_users_id);
}
//modal.hidePleaseWait();
}
});
}
$(document).ready(function () {
});
</script>

View file

@ -1,39 +1,39 @@
<?php
$obj = AVideoPlugin::getObjectDataIfEnabled('AD_Overlay');
$ad = new AD_Overlay_Code(0);
$ad->loadFromUser(User::getId());
?>
<div id="adOverlay" class="tab-pane fade" style="padding: 10px 0;">
<div class="panel panel-default">
<div class="panel-heading">
AD Code
</div>
<div class="panel-body">
<textarea class="form-control" rows="10" id="addOverlayCode"><?php echo $ad->getCode(); ?></textarea>
<button class="btn btn-success btn-block" type="button" onclick="saveCode()"><?php echo __("Save Ad Code") ?></button>
</div>
</div>
</div>
<script>
function saveCode() {
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/AD_Overlay/saveCode.json.php',
data: {
"addOverlayCode": $('#addOverlayCode').val()
},
type: 'post',
success: function (response) {
if (response.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", response.error, "error");
} else {
avideoAlert("<?php echo __("Congratulations!"); ?>", "<?php echo __("Your code has been saved!"); ?>", "success");
}
modal.hidePleaseWait();
}
});
}
$(document).ready(function () {
});
<?php
$obj = AVideoPlugin::getObjectDataIfEnabled('AD_Overlay');
$ad = new AD_Overlay_Code(0);
$ad->loadFromUser(User::getId());
?>
<div id="adOverlay" class="tab-pane fade" style="padding: 10px 0;">
<div class="panel panel-default">
<div class="panel-heading">
AD Code
</div>
<div class="panel-body">
<textarea class="form-control" rows="10" id="addOverlayCode"><?php echo $ad->getCode(); ?></textarea>
<button class="btn btn-success btn-block" type="button" onclick="saveCode()"><?php echo __("Save Ad Code") ?></button>
</div>
</div>
</div>
<script>
function saveCode() {
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/AD_Overlay/saveCode.json.php',
data: {
"addOverlayCode": $('#addOverlayCode').val()
},
type: 'post',
success: function (response) {
if (response.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", response.error, "error");
} else {
avideoAlert("<?php echo __("Congratulations!"); ?>", "<?php echo __("Your code has been saved!"); ?>", "success");
}
modal.hidePleaseWait();
}
});
}
$(document).ready(function () {
});
</script>

View file

@ -1,386 +1,386 @@
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var videojs = _interopDefault(require('video.js'));
var window = _interopDefault(require('global/window'));
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var version = "2.1.4";
var defaults = {
align: 'top-left',
class: '',
content: 'This overlay will show up while the video is playing',
debug: false,
showBackground: true,
attachToControlBar: false,
overlays: [{
start: 'playing',
end: 'paused'
}]
};
var Component = videojs.getComponent('Component');
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin;
/**
* Whether the value is a `Number`.
*
* Both `Infinity` and `-Infinity` are accepted, but `NaN` is not.
*
* @param {Number} n
* @return {Boolean}
*/
/* eslint-disable no-self-compare */
var isNumber = function isNumber(n) {
return typeof n === 'number' && n === n;
};
/* eslint-enable no-self-compare */
/**
* Whether a value is a string with no whitespace.
*
* @param {String} s
* @return {Boolean}
*/
var hasNoWhitespace = function hasNoWhitespace(s) {
return typeof s === 'string' && /^\S+$/.test(s);
};
/**
* Overlay component.
*
* @class Overlay
* @extends {videojs.Component}
*/
var Overlay =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Overlay, _Component);
function Overlay(player, options) {
var _this;
_this = _Component.call(this, player, options) || this;
['start', 'end'].forEach(function (key) {
var value = _this.options_[key];
if (isNumber(value)) {
_this[key + 'Event_'] = 'timeupdate';
} else if (hasNoWhitespace(value)) {
_this[key + 'Event_'] = value; // An overlay MUST have a start option. Otherwise, it's pointless.
} else if (key === 'start') {
throw new Error('invalid "start" option; expected number or string');
}
}); // video.js does not like components with multiple instances binding
// events to the player because it tracks them at the player level,
// not at the level of the object doing the binding. This could also be
// solved with Function.prototype.bind (but not videojs.bind because of
// its GUID magic), but the anonymous function approach avoids any issues
// caused by crappy libraries clobbering Function.prototype.bind.
// - https://github.com/videojs/video.js/issues/3097
['endListener_', 'rewindListener_', 'startListener_'].forEach(function (name$$1) {
_this[name$$1] = function (e) {
return Overlay.prototype[name$$1].call(_assertThisInitialized(_assertThisInitialized(_this)), e);
};
}); // If the start event is a timeupdate, we need to watch for rewinds (i.e.,
// when the user seeks backward).
if (_this.startEvent_ === 'timeupdate') {
_this.on(player, 'timeupdate', _this.rewindListener_);
}
_this.debug("created, listening to \"" + _this.startEvent_ + "\" for \"start\" and \"" + (_this.endEvent_ || 'nothing') + "\" for \"end\"");
_this.hide();
return _this;
}
var _proto = Overlay.prototype;
_proto.createEl = function createEl() {
var options = this.options_;
var content = options.content;
var background = options.showBackground ? 'vjs-overlay-background' : 'vjs-overlay-no-background';
var el = dom.createEl('div', {
className: "\n vjs-overlay\n vjs-overlay-" + options.align + "\n " + options.class + "\n " + background + "\n vjs-hidden\n "
});
if (typeof content === 'string') {
el.innerHTML = content;
} else if (content instanceof window.DocumentFragment) {
el.appendChild(content);
} else {
dom.appendContent(el, content);
}
return el;
};
/**
* Logs debug errors
* @param {...[type]} args [description]
* @return {[type]} [description]
*/
_proto.debug = function debug() {
if (!this.options_.debug) {
return;
}
var log = videojs.log;
var fn = log; // Support `videojs.log.foo` calls.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (log.hasOwnProperty(args[0]) && typeof log[args[0]] === 'function') {
fn = log[args.shift()];
}
fn.apply(void 0, ["overlay#" + this.id() + ": "].concat(args));
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.hide = function hide() {
_Component.prototype.hide.call(this);
this.debug('hidden');
this.debug("bound `startListener_` to \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("unbound `endListener_` from \"" + this.endEvent_ + "\"");
this.off(this.player(), this.endEvent_, this.endListener_);
}
this.on(this.player(), this.startEvent_, this.startListener_);
return this;
};
/**
* Determine whether or not the overlay should hide.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldHide_ = function shouldHide_(time, type) {
var end = this.options_.end;
return isNumber(end) ? time >= end : end === type;
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.show = function show() {
_Component.prototype.show.call(this);
this.off(this.player(), this.startEvent_, this.startListener_);
this.debug('shown');
this.debug("unbound `startListener_` from \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("bound `endListener_` to \"" + this.endEvent_ + "\"");
this.on(this.player(), this.endEvent_, this.endListener_);
}
return this;
};
/**
* Determine whether or not the overlay should show.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldShow_ = function shouldShow_(time, type) {
var start = this.options_.start;
var end = this.options_.end;
if (isNumber(start)) {
if (isNumber(end)) {
return time >= start && time < end; // In this case, the start is a number and the end is a string. We need
// to check whether or not the overlay has shown since the last seek.
} else if (!this.hasShownSinceSeek_) {
this.hasShownSinceSeek_ = true;
return time >= start;
} // In this case, the start is a number and the end is a string, but
// the overlay has shown since the last seek. This means that we need
// to be sure we aren't re-showing it at a later time than it is
// scheduled to appear.
return Math.floor(time) === start;
}
return start === type;
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.startListener_ = function startListener_(e) {
var time = this.player().currentTime();
if (this.shouldShow_(time, e.type)) {
this.show();
}
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.endListener_ = function endListener_(e) {
var time = this.player().currentTime();
if (this.shouldHide_(time, e.type)) {
this.hide();
}
};
/**
* Event listener that can looks for rewinds - that is, backward seeks
* and may hide the overlay as needed.
*
* @param {Event} e
*/
_proto.rewindListener_ = function rewindListener_(e) {
var time = this.player().currentTime();
var previous = this.previousTime_;
var start = this.options_.start;
var end = this.options_.end; // Did we seek backward?
if (time < previous) {
this.debug('rewind detected'); // The overlay remains visible if two conditions are met: the end value
// MUST be an integer and the the current time indicates that the
// overlay should NOT be visible.
if (isNumber(end) && !this.shouldShow_(time)) {
this.debug("hiding; " + end + " is an integer and overlay should not show at this time");
this.hasShownSinceSeek_ = false;
this.hide(); // If the end value is an event name, we cannot reliably decide if the
// overlay should still be displayed based solely on time; so, we can
// only queue it up for showing if the seek took us to a point before
// the start time.
} else if (hasNoWhitespace(end) && time < start) {
this.debug("hiding; show point (" + start + ") is before now (" + time + ") and end point (" + end + ") is an event");
this.hasShownSinceSeek_ = false;
this.hide();
}
}
this.previousTime_ = time;
};
return Overlay;
}(Component);
videojs.registerComponent('Overlay', Overlay);
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
var plugin = function plugin(options) {
var _this2 = this;
var settings = videojs.mergeOptions(defaults, options); // De-initialize the plugin if it already has an array of overlays.
if (Array.isArray(this.overlays_)) {
this.overlays_.forEach(function (overlay) {
_this2.removeChild(overlay);
if (_this2.controlBar) {
_this2.controlBar.removeChild(overlay);
}
overlay.dispose();
});
}
var overlays = settings.overlays; // We don't want to keep the original array of overlay options around
// because it doesn't make sense to pass it to each Overlay component.
delete settings.overlays;
this.overlays_ = overlays.map(function (o) {
var mergeOptions = videojs.mergeOptions(settings, o);
var attachToControlBar = typeof mergeOptions.attachToControlBar === 'string' || mergeOptions.attachToControlBar === true;
if (!_this2.controls() || !_this2.controlBar) {
return _this2.addChild('overlay', mergeOptions);
}
if (attachToControlBar && mergeOptions.align.indexOf('bottom') !== -1) {
var referenceChild = _this2.controlBar.children()[0];
if (_this2.controlBar.getChild(mergeOptions.attachToControlBar) !== undefined) {
referenceChild = _this2.controlBar.getChild(mergeOptions.attachToControlBar);
}
if (referenceChild) {
var controlBarChild = _this2.controlBar.addChild('overlay', mergeOptions);
_this2.controlBar.el().insertBefore(controlBarChild.el(), referenceChild.el());
return controlBarChild;
}
}
var playerChild = _this2.addChild('overlay', mergeOptions);
_this2.el().insertBefore(playerChild.el(), _this2.controlBar.el());
return playerChild;
});
};
plugin.VERSION = version;
registerPlugin('overlay', plugin);
module.exports = plugin;
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var videojs = _interopDefault(require('video.js'));
var window = _interopDefault(require('global/window'));
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var version = "2.1.4";
var defaults = {
align: 'top-left',
class: '',
content: 'This overlay will show up while the video is playing',
debug: false,
showBackground: true,
attachToControlBar: false,
overlays: [{
start: 'playing',
end: 'paused'
}]
};
var Component = videojs.getComponent('Component');
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin;
/**
* Whether the value is a `Number`.
*
* Both `Infinity` and `-Infinity` are accepted, but `NaN` is not.
*
* @param {Number} n
* @return {Boolean}
*/
/* eslint-disable no-self-compare */
var isNumber = function isNumber(n) {
return typeof n === 'number' && n === n;
};
/* eslint-enable no-self-compare */
/**
* Whether a value is a string with no whitespace.
*
* @param {String} s
* @return {Boolean}
*/
var hasNoWhitespace = function hasNoWhitespace(s) {
return typeof s === 'string' && /^\S+$/.test(s);
};
/**
* Overlay component.
*
* @class Overlay
* @extends {videojs.Component}
*/
var Overlay =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Overlay, _Component);
function Overlay(player, options) {
var _this;
_this = _Component.call(this, player, options) || this;
['start', 'end'].forEach(function (key) {
var value = _this.options_[key];
if (isNumber(value)) {
_this[key + 'Event_'] = 'timeupdate';
} else if (hasNoWhitespace(value)) {
_this[key + 'Event_'] = value; // An overlay MUST have a start option. Otherwise, it's pointless.
} else if (key === 'start') {
throw new Error('invalid "start" option; expected number or string');
}
}); // video.js does not like components with multiple instances binding
// events to the player because it tracks them at the player level,
// not at the level of the object doing the binding. This could also be
// solved with Function.prototype.bind (but not videojs.bind because of
// its GUID magic), but the anonymous function approach avoids any issues
// caused by crappy libraries clobbering Function.prototype.bind.
// - https://github.com/videojs/video.js/issues/3097
['endListener_', 'rewindListener_', 'startListener_'].forEach(function (name$$1) {
_this[name$$1] = function (e) {
return Overlay.prototype[name$$1].call(_assertThisInitialized(_assertThisInitialized(_this)), e);
};
}); // If the start event is a timeupdate, we need to watch for rewinds (i.e.,
// when the user seeks backward).
if (_this.startEvent_ === 'timeupdate') {
_this.on(player, 'timeupdate', _this.rewindListener_);
}
_this.debug("created, listening to \"" + _this.startEvent_ + "\" for \"start\" and \"" + (_this.endEvent_ || 'nothing') + "\" for \"end\"");
_this.hide();
return _this;
}
var _proto = Overlay.prototype;
_proto.createEl = function createEl() {
var options = this.options_;
var content = options.content;
var background = options.showBackground ? 'vjs-overlay-background' : 'vjs-overlay-no-background';
var el = dom.createEl('div', {
className: "\n vjs-overlay\n vjs-overlay-" + options.align + "\n " + options.class + "\n " + background + "\n vjs-hidden\n "
});
if (typeof content === 'string') {
el.innerHTML = content;
} else if (content instanceof window.DocumentFragment) {
el.appendChild(content);
} else {
dom.appendContent(el, content);
}
return el;
};
/**
* Logs debug errors
* @param {...[type]} args [description]
* @return {[type]} [description]
*/
_proto.debug = function debug() {
if (!this.options_.debug) {
return;
}
var log = videojs.log;
var fn = log; // Support `videojs.log.foo` calls.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (log.hasOwnProperty(args[0]) && typeof log[args[0]] === 'function') {
fn = log[args.shift()];
}
fn.apply(void 0, ["overlay#" + this.id() + ": "].concat(args));
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.hide = function hide() {
_Component.prototype.hide.call(this);
this.debug('hidden');
this.debug("bound `startListener_` to \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("unbound `endListener_` from \"" + this.endEvent_ + "\"");
this.off(this.player(), this.endEvent_, this.endListener_);
}
this.on(this.player(), this.startEvent_, this.startListener_);
return this;
};
/**
* Determine whether or not the overlay should hide.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldHide_ = function shouldHide_(time, type) {
var end = this.options_.end;
return isNumber(end) ? time >= end : end === type;
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.show = function show() {
_Component.prototype.show.call(this);
this.off(this.player(), this.startEvent_, this.startListener_);
this.debug('shown');
this.debug("unbound `startListener_` from \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("bound `endListener_` to \"" + this.endEvent_ + "\"");
this.on(this.player(), this.endEvent_, this.endListener_);
}
return this;
};
/**
* Determine whether or not the overlay should show.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldShow_ = function shouldShow_(time, type) {
var start = this.options_.start;
var end = this.options_.end;
if (isNumber(start)) {
if (isNumber(end)) {
return time >= start && time < end; // In this case, the start is a number and the end is a string. We need
// to check whether or not the overlay has shown since the last seek.
} else if (!this.hasShownSinceSeek_) {
this.hasShownSinceSeek_ = true;
return time >= start;
} // In this case, the start is a number and the end is a string, but
// the overlay has shown since the last seek. This means that we need
// to be sure we aren't re-showing it at a later time than it is
// scheduled to appear.
return Math.floor(time) === start;
}
return start === type;
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.startListener_ = function startListener_(e) {
var time = this.player().currentTime();
if (this.shouldShow_(time, e.type)) {
this.show();
}
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.endListener_ = function endListener_(e) {
var time = this.player().currentTime();
if (this.shouldHide_(time, e.type)) {
this.hide();
}
};
/**
* Event listener that can looks for rewinds - that is, backward seeks
* and may hide the overlay as needed.
*
* @param {Event} e
*/
_proto.rewindListener_ = function rewindListener_(e) {
var time = this.player().currentTime();
var previous = this.previousTime_;
var start = this.options_.start;
var end = this.options_.end; // Did we seek backward?
if (time < previous) {
this.debug('rewind detected'); // The overlay remains visible if two conditions are met: the end value
// MUST be an integer and the the current time indicates that the
// overlay should NOT be visible.
if (isNumber(end) && !this.shouldShow_(time)) {
this.debug("hiding; " + end + " is an integer and overlay should not show at this time");
this.hasShownSinceSeek_ = false;
this.hide(); // If the end value is an event name, we cannot reliably decide if the
// overlay should still be displayed based solely on time; so, we can
// only queue it up for showing if the seek took us to a point before
// the start time.
} else if (hasNoWhitespace(end) && time < start) {
this.debug("hiding; show point (" + start + ") is before now (" + time + ") and end point (" + end + ") is an event");
this.hasShownSinceSeek_ = false;
this.hide();
}
}
this.previousTime_ = time;
};
return Overlay;
}(Component);
videojs.registerComponent('Overlay', Overlay);
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
var plugin = function plugin(options) {
var _this2 = this;
var settings = videojs.mergeOptions(defaults, options); // De-initialize the plugin if it already has an array of overlays.
if (Array.isArray(this.overlays_)) {
this.overlays_.forEach(function (overlay) {
_this2.removeChild(overlay);
if (_this2.controlBar) {
_this2.controlBar.removeChild(overlay);
}
overlay.dispose();
});
}
var overlays = settings.overlays; // We don't want to keep the original array of overlay options around
// because it doesn't make sense to pass it to each Overlay component.
delete settings.overlays;
this.overlays_ = overlays.map(function (o) {
var mergeOptions = videojs.mergeOptions(settings, o);
var attachToControlBar = typeof mergeOptions.attachToControlBar === 'string' || mergeOptions.attachToControlBar === true;
if (!_this2.controls() || !_this2.controlBar) {
return _this2.addChild('overlay', mergeOptions);
}
if (attachToControlBar && mergeOptions.align.indexOf('bottom') !== -1) {
var referenceChild = _this2.controlBar.children()[0];
if (_this2.controlBar.getChild(mergeOptions.attachToControlBar) !== undefined) {
referenceChild = _this2.controlBar.getChild(mergeOptions.attachToControlBar);
}
if (referenceChild) {
var controlBarChild = _this2.controlBar.addChild('overlay', mergeOptions);
_this2.controlBar.el().insertBefore(controlBarChild.el(), referenceChild.el());
return controlBarChild;
}
}
var playerChild = _this2.addChild('overlay', mergeOptions);
_this2.el().insertBefore(playerChild.el(), _this2.controlBar.el());
return playerChild;
});
};
plugin.VERSION = version;
registerPlugin('overlay', plugin);
module.exports = plugin;

View file

@ -1 +1 @@
.video-js .vjs-overlay{color:#fff;position:absolute;text-align:center}.video-js .vjs-overlay-no-background{max-width:33%}.video-js .vjs-overlay-background{background-color:#646464;background-color:rgba(255,255,255,0.4);border-radius:3px;padding:10px;width:33%}.video-js .vjs-overlay-top-left{top:5px;left:5px}.video-js .vjs-overlay-top{left:50%;margin-left:-16.5%;top:5px}.video-js .vjs-overlay-top-right{right:5px;top:5px}.video-js .vjs-overlay-right{right:5px;top:50%;transform:translateY(-50%)}.video-js .vjs-overlay-bottom-right{bottom:3.5em;right:5px}.video-js .vjs-overlay-bottom{bottom:3.5em;left:50%;margin-left:-16.5%}.video-js .vjs-overlay-bottom-left{bottom:3.5em;left:5px}.video-js .vjs-overlay-left{left:5px;top:50%;transform:translateY(-50%)}.video-js .vjs-overlay-center{left:50%;margin-left:-16.5%;top:50%;transform:translateY(-50%)}.video-js .vjs-no-flex .vjs-overlay-left,.video-js .vjs-no-flex .vjs-overlay-center,.video-js .vjs-no-flex .vjs-overlay-right{margin-top:-15px}
.video-js .vjs-overlay{color:#fff;position:absolute;text-align:center}.video-js .vjs-overlay-no-background{max-width:33%}.video-js .vjs-overlay-background{background-color:#646464;background-color:rgba(255,255,255,0.4);border-radius:3px;padding:10px;width:33%}.video-js .vjs-overlay-top-left{top:5px;left:5px}.video-js .vjs-overlay-top{left:50%;margin-left:-16.5%;top:5px}.video-js .vjs-overlay-top-right{right:5px;top:5px}.video-js .vjs-overlay-right{right:5px;top:50%;transform:translateY(-50%)}.video-js .vjs-overlay-bottom-right{bottom:3.5em;right:5px}.video-js .vjs-overlay-bottom{bottom:3.5em;left:50%;margin-left:-16.5%}.video-js .vjs-overlay-bottom-left{bottom:3.5em;left:5px}.video-js .vjs-overlay-left{left:5px;top:50%;transform:translateY(-50%)}.video-js .vjs-overlay-center{left:50%;margin-left:-16.5%;top:50%;transform:translateY(-50%)}.video-js .vjs-no-flex .vjs-overlay-left,.video-js .vjs-no-flex .vjs-overlay-center,.video-js .vjs-no-flex .vjs-overlay-right{margin-top:-15px}

View file

@ -1,382 +1,382 @@
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
import videojs from 'video.js';
import window from 'global/window';
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var version = "2.1.4";
var defaults = {
align: 'top-left',
class: '',
content: 'This overlay will show up while the video is playing',
debug: false,
showBackground: true,
attachToControlBar: false,
overlays: [{
start: 'playing',
end: 'paused'
}]
};
var Component = videojs.getComponent('Component');
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin;
/**
* Whether the value is a `Number`.
*
* Both `Infinity` and `-Infinity` are accepted, but `NaN` is not.
*
* @param {Number} n
* @return {Boolean}
*/
/* eslint-disable no-self-compare */
var isNumber = function isNumber(n) {
return typeof n === 'number' && n === n;
};
/* eslint-enable no-self-compare */
/**
* Whether a value is a string with no whitespace.
*
* @param {String} s
* @return {Boolean}
*/
var hasNoWhitespace = function hasNoWhitespace(s) {
return typeof s === 'string' && /^\S+$/.test(s);
};
/**
* Overlay component.
*
* @class Overlay
* @extends {videojs.Component}
*/
var Overlay =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Overlay, _Component);
function Overlay(player, options) {
var _this;
_this = _Component.call(this, player, options) || this;
['start', 'end'].forEach(function (key) {
var value = _this.options_[key];
if (isNumber(value)) {
_this[key + 'Event_'] = 'timeupdate';
} else if (hasNoWhitespace(value)) {
_this[key + 'Event_'] = value; // An overlay MUST have a start option. Otherwise, it's pointless.
} else if (key === 'start') {
throw new Error('invalid "start" option; expected number or string');
}
}); // video.js does not like components with multiple instances binding
// events to the player because it tracks them at the player level,
// not at the level of the object doing the binding. This could also be
// solved with Function.prototype.bind (but not videojs.bind because of
// its GUID magic), but the anonymous function approach avoids any issues
// caused by crappy libraries clobbering Function.prototype.bind.
// - https://github.com/videojs/video.js/issues/3097
['endListener_', 'rewindListener_', 'startListener_'].forEach(function (name$$1) {
_this[name$$1] = function (e) {
return Overlay.prototype[name$$1].call(_assertThisInitialized(_assertThisInitialized(_this)), e);
};
}); // If the start event is a timeupdate, we need to watch for rewinds (i.e.,
// when the user seeks backward).
if (_this.startEvent_ === 'timeupdate') {
_this.on(player, 'timeupdate', _this.rewindListener_);
}
_this.debug("created, listening to \"" + _this.startEvent_ + "\" for \"start\" and \"" + (_this.endEvent_ || 'nothing') + "\" for \"end\"");
_this.hide();
return _this;
}
var _proto = Overlay.prototype;
_proto.createEl = function createEl() {
var options = this.options_;
var content = options.content;
var background = options.showBackground ? 'vjs-overlay-background' : 'vjs-overlay-no-background';
var el = dom.createEl('div', {
className: "\n vjs-overlay\n vjs-overlay-" + options.align + "\n " + options.class + "\n " + background + "\n vjs-hidden\n "
});
if (typeof content === 'string') {
el.innerHTML = content;
} else if (content instanceof window.DocumentFragment) {
el.appendChild(content);
} else {
dom.appendContent(el, content);
}
return el;
};
/**
* Logs debug errors
* @param {...[type]} args [description]
* @return {[type]} [description]
*/
_proto.debug = function debug() {
if (!this.options_.debug) {
return;
}
var log = videojs.log;
var fn = log; // Support `videojs.log.foo` calls.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (log.hasOwnProperty(args[0]) && typeof log[args[0]] === 'function') {
fn = log[args.shift()];
}
fn.apply(void 0, ["overlay#" + this.id() + ": "].concat(args));
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.hide = function hide() {
_Component.prototype.hide.call(this);
this.debug('hidden');
this.debug("bound `startListener_` to \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("unbound `endListener_` from \"" + this.endEvent_ + "\"");
this.off(this.player(), this.endEvent_, this.endListener_);
}
this.on(this.player(), this.startEvent_, this.startListener_);
return this;
};
/**
* Determine whether or not the overlay should hide.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldHide_ = function shouldHide_(time, type) {
var end = this.options_.end;
return isNumber(end) ? time >= end : end === type;
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.show = function show() {
_Component.prototype.show.call(this);
this.off(this.player(), this.startEvent_, this.startListener_);
this.debug('shown');
this.debug("unbound `startListener_` from \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("bound `endListener_` to \"" + this.endEvent_ + "\"");
this.on(this.player(), this.endEvent_, this.endListener_);
}
return this;
};
/**
* Determine whether or not the overlay should show.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldShow_ = function shouldShow_(time, type) {
var start = this.options_.start;
var end = this.options_.end;
if (isNumber(start)) {
if (isNumber(end)) {
return time >= start && time < end; // In this case, the start is a number and the end is a string. We need
// to check whether or not the overlay has shown since the last seek.
} else if (!this.hasShownSinceSeek_) {
this.hasShownSinceSeek_ = true;
return time >= start;
} // In this case, the start is a number and the end is a string, but
// the overlay has shown since the last seek. This means that we need
// to be sure we aren't re-showing it at a later time than it is
// scheduled to appear.
return Math.floor(time) === start;
}
return start === type;
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.startListener_ = function startListener_(e) {
var time = this.player().currentTime();
if (this.shouldShow_(time, e.type)) {
this.show();
}
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.endListener_ = function endListener_(e) {
var time = this.player().currentTime();
if (this.shouldHide_(time, e.type)) {
this.hide();
}
};
/**
* Event listener that can looks for rewinds - that is, backward seeks
* and may hide the overlay as needed.
*
* @param {Event} e
*/
_proto.rewindListener_ = function rewindListener_(e) {
var time = this.player().currentTime();
var previous = this.previousTime_;
var start = this.options_.start;
var end = this.options_.end; // Did we seek backward?
if (time < previous) {
this.debug('rewind detected'); // The overlay remains visible if two conditions are met: the end value
// MUST be an integer and the the current time indicates that the
// overlay should NOT be visible.
if (isNumber(end) && !this.shouldShow_(time)) {
this.debug("hiding; " + end + " is an integer and overlay should not show at this time");
this.hasShownSinceSeek_ = false;
this.hide(); // If the end value is an event name, we cannot reliably decide if the
// overlay should still be displayed based solely on time; so, we can
// only queue it up for showing if the seek took us to a point before
// the start time.
} else if (hasNoWhitespace(end) && time < start) {
this.debug("hiding; show point (" + start + ") is before now (" + time + ") and end point (" + end + ") is an event");
this.hasShownSinceSeek_ = false;
this.hide();
}
}
this.previousTime_ = time;
};
return Overlay;
}(Component);
videojs.registerComponent('Overlay', Overlay);
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
var plugin = function plugin(options) {
var _this2 = this;
var settings = videojs.mergeOptions(defaults, options); // De-initialize the plugin if it already has an array of overlays.
if (Array.isArray(this.overlays_)) {
this.overlays_.forEach(function (overlay) {
_this2.removeChild(overlay);
if (_this2.controlBar) {
_this2.controlBar.removeChild(overlay);
}
overlay.dispose();
});
}
var overlays = settings.overlays; // We don't want to keep the original array of overlay options around
// because it doesn't make sense to pass it to each Overlay component.
delete settings.overlays;
this.overlays_ = overlays.map(function (o) {
var mergeOptions = videojs.mergeOptions(settings, o);
var attachToControlBar = typeof mergeOptions.attachToControlBar === 'string' || mergeOptions.attachToControlBar === true;
if (!_this2.controls() || !_this2.controlBar) {
return _this2.addChild('overlay', mergeOptions);
}
if (attachToControlBar && mergeOptions.align.indexOf('bottom') !== -1) {
var referenceChild = _this2.controlBar.children()[0];
if (_this2.controlBar.getChild(mergeOptions.attachToControlBar) !== undefined) {
referenceChild = _this2.controlBar.getChild(mergeOptions.attachToControlBar);
}
if (referenceChild) {
var controlBarChild = _this2.controlBar.addChild('overlay', mergeOptions);
_this2.controlBar.el().insertBefore(controlBarChild.el(), referenceChild.el());
return controlBarChild;
}
}
var playerChild = _this2.addChild('overlay', mergeOptions);
_this2.el().insertBefore(playerChild.el(), _this2.controlBar.el());
return playerChild;
});
};
plugin.VERSION = version;
registerPlugin('overlay', plugin);
export default plugin;
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
import videojs from 'video.js';
import window from 'global/window';
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var version = "2.1.4";
var defaults = {
align: 'top-left',
class: '',
content: 'This overlay will show up while the video is playing',
debug: false,
showBackground: true,
attachToControlBar: false,
overlays: [{
start: 'playing',
end: 'paused'
}]
};
var Component = videojs.getComponent('Component');
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin;
/**
* Whether the value is a `Number`.
*
* Both `Infinity` and `-Infinity` are accepted, but `NaN` is not.
*
* @param {Number} n
* @return {Boolean}
*/
/* eslint-disable no-self-compare */
var isNumber = function isNumber(n) {
return typeof n === 'number' && n === n;
};
/* eslint-enable no-self-compare */
/**
* Whether a value is a string with no whitespace.
*
* @param {String} s
* @return {Boolean}
*/
var hasNoWhitespace = function hasNoWhitespace(s) {
return typeof s === 'string' && /^\S+$/.test(s);
};
/**
* Overlay component.
*
* @class Overlay
* @extends {videojs.Component}
*/
var Overlay =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Overlay, _Component);
function Overlay(player, options) {
var _this;
_this = _Component.call(this, player, options) || this;
['start', 'end'].forEach(function (key) {
var value = _this.options_[key];
if (isNumber(value)) {
_this[key + 'Event_'] = 'timeupdate';
} else if (hasNoWhitespace(value)) {
_this[key + 'Event_'] = value; // An overlay MUST have a start option. Otherwise, it's pointless.
} else if (key === 'start') {
throw new Error('invalid "start" option; expected number or string');
}
}); // video.js does not like components with multiple instances binding
// events to the player because it tracks them at the player level,
// not at the level of the object doing the binding. This could also be
// solved with Function.prototype.bind (but not videojs.bind because of
// its GUID magic), but the anonymous function approach avoids any issues
// caused by crappy libraries clobbering Function.prototype.bind.
// - https://github.com/videojs/video.js/issues/3097
['endListener_', 'rewindListener_', 'startListener_'].forEach(function (name$$1) {
_this[name$$1] = function (e) {
return Overlay.prototype[name$$1].call(_assertThisInitialized(_assertThisInitialized(_this)), e);
};
}); // If the start event is a timeupdate, we need to watch for rewinds (i.e.,
// when the user seeks backward).
if (_this.startEvent_ === 'timeupdate') {
_this.on(player, 'timeupdate', _this.rewindListener_);
}
_this.debug("created, listening to \"" + _this.startEvent_ + "\" for \"start\" and \"" + (_this.endEvent_ || 'nothing') + "\" for \"end\"");
_this.hide();
return _this;
}
var _proto = Overlay.prototype;
_proto.createEl = function createEl() {
var options = this.options_;
var content = options.content;
var background = options.showBackground ? 'vjs-overlay-background' : 'vjs-overlay-no-background';
var el = dom.createEl('div', {
className: "\n vjs-overlay\n vjs-overlay-" + options.align + "\n " + options.class + "\n " + background + "\n vjs-hidden\n "
});
if (typeof content === 'string') {
el.innerHTML = content;
} else if (content instanceof window.DocumentFragment) {
el.appendChild(content);
} else {
dom.appendContent(el, content);
}
return el;
};
/**
* Logs debug errors
* @param {...[type]} args [description]
* @return {[type]} [description]
*/
_proto.debug = function debug() {
if (!this.options_.debug) {
return;
}
var log = videojs.log;
var fn = log; // Support `videojs.log.foo` calls.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (log.hasOwnProperty(args[0]) && typeof log[args[0]] === 'function') {
fn = log[args.shift()];
}
fn.apply(void 0, ["overlay#" + this.id() + ": "].concat(args));
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.hide = function hide() {
_Component.prototype.hide.call(this);
this.debug('hidden');
this.debug("bound `startListener_` to \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("unbound `endListener_` from \"" + this.endEvent_ + "\"");
this.off(this.player(), this.endEvent_, this.endListener_);
}
this.on(this.player(), this.startEvent_, this.startListener_);
return this;
};
/**
* Determine whether or not the overlay should hide.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldHide_ = function shouldHide_(time, type) {
var end = this.options_.end;
return isNumber(end) ? time >= end : end === type;
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.show = function show() {
_Component.prototype.show.call(this);
this.off(this.player(), this.startEvent_, this.startListener_);
this.debug('shown');
this.debug("unbound `startListener_` from \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("bound `endListener_` to \"" + this.endEvent_ + "\"");
this.on(this.player(), this.endEvent_, this.endListener_);
}
return this;
};
/**
* Determine whether or not the overlay should show.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldShow_ = function shouldShow_(time, type) {
var start = this.options_.start;
var end = this.options_.end;
if (isNumber(start)) {
if (isNumber(end)) {
return time >= start && time < end; // In this case, the start is a number and the end is a string. We need
// to check whether or not the overlay has shown since the last seek.
} else if (!this.hasShownSinceSeek_) {
this.hasShownSinceSeek_ = true;
return time >= start;
} // In this case, the start is a number and the end is a string, but
// the overlay has shown since the last seek. This means that we need
// to be sure we aren't re-showing it at a later time than it is
// scheduled to appear.
return Math.floor(time) === start;
}
return start === type;
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.startListener_ = function startListener_(e) {
var time = this.player().currentTime();
if (this.shouldShow_(time, e.type)) {
this.show();
}
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.endListener_ = function endListener_(e) {
var time = this.player().currentTime();
if (this.shouldHide_(time, e.type)) {
this.hide();
}
};
/**
* Event listener that can looks for rewinds - that is, backward seeks
* and may hide the overlay as needed.
*
* @param {Event} e
*/
_proto.rewindListener_ = function rewindListener_(e) {
var time = this.player().currentTime();
var previous = this.previousTime_;
var start = this.options_.start;
var end = this.options_.end; // Did we seek backward?
if (time < previous) {
this.debug('rewind detected'); // The overlay remains visible if two conditions are met: the end value
// MUST be an integer and the the current time indicates that the
// overlay should NOT be visible.
if (isNumber(end) && !this.shouldShow_(time)) {
this.debug("hiding; " + end + " is an integer and overlay should not show at this time");
this.hasShownSinceSeek_ = false;
this.hide(); // If the end value is an event name, we cannot reliably decide if the
// overlay should still be displayed based solely on time; so, we can
// only queue it up for showing if the seek took us to a point before
// the start time.
} else if (hasNoWhitespace(end) && time < start) {
this.debug("hiding; show point (" + start + ") is before now (" + time + ") and end point (" + end + ") is an event");
this.hasShownSinceSeek_ = false;
this.hide();
}
}
this.previousTime_ = time;
};
return Overlay;
}(Component);
videojs.registerComponent('Overlay', Overlay);
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
var plugin = function plugin(options) {
var _this2 = this;
var settings = videojs.mergeOptions(defaults, options); // De-initialize the plugin if it already has an array of overlays.
if (Array.isArray(this.overlays_)) {
this.overlays_.forEach(function (overlay) {
_this2.removeChild(overlay);
if (_this2.controlBar) {
_this2.controlBar.removeChild(overlay);
}
overlay.dispose();
});
}
var overlays = settings.overlays; // We don't want to keep the original array of overlay options around
// because it doesn't make sense to pass it to each Overlay component.
delete settings.overlays;
this.overlays_ = overlays.map(function (o) {
var mergeOptions = videojs.mergeOptions(settings, o);
var attachToControlBar = typeof mergeOptions.attachToControlBar === 'string' || mergeOptions.attachToControlBar === true;
if (!_this2.controls() || !_this2.controlBar) {
return _this2.addChild('overlay', mergeOptions);
}
if (attachToControlBar && mergeOptions.align.indexOf('bottom') !== -1) {
var referenceChild = _this2.controlBar.children()[0];
if (_this2.controlBar.getChild(mergeOptions.attachToControlBar) !== undefined) {
referenceChild = _this2.controlBar.getChild(mergeOptions.attachToControlBar);
}
if (referenceChild) {
var controlBarChild = _this2.controlBar.addChild('overlay', mergeOptions);
_this2.controlBar.el().insertBefore(controlBarChild.el(), referenceChild.el());
return controlBarChild;
}
}
var playerChild = _this2.addChild('overlay', mergeOptions);
_this2.el().insertBefore(playerChild.el(), _this2.controlBar.el());
return playerChild;
});
};
plugin.VERSION = version;
registerPlugin('overlay', plugin);
export default plugin;

View file

@ -1,390 +1,390 @@
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('video.js'), require('global/window')) :
typeof define === 'function' && define.amd ? define(['video.js', 'global/window'], factory) :
(global.videojsOverlay = factory(global.videojs,global.window));
}(this, (function (videojs,window) { 'use strict';
videojs = videojs && videojs.hasOwnProperty('default') ? videojs['default'] : videojs;
window = window && window.hasOwnProperty('default') ? window['default'] : window;
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var version = "2.1.4";
var defaults = {
align: 'top-left',
class: '',
content: 'This overlay will show up while the video is playing',
debug: false,
showBackground: true,
attachToControlBar: false,
overlays: [{
start: 'playing',
end: 'paused'
}]
};
var Component = videojs.getComponent('Component');
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin;
/**
* Whether the value is a `Number`.
*
* Both `Infinity` and `-Infinity` are accepted, but `NaN` is not.
*
* @param {Number} n
* @return {Boolean}
*/
/* eslint-disable no-self-compare */
var isNumber = function isNumber(n) {
return typeof n === 'number' && n === n;
};
/* eslint-enable no-self-compare */
/**
* Whether a value is a string with no whitespace.
*
* @param {String} s
* @return {Boolean}
*/
var hasNoWhitespace = function hasNoWhitespace(s) {
return typeof s === 'string' && /^\S+$/.test(s);
};
/**
* Overlay component.
*
* @class Overlay
* @extends {videojs.Component}
*/
var Overlay =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Overlay, _Component);
function Overlay(player, options) {
var _this;
_this = _Component.call(this, player, options) || this;
['start', 'end'].forEach(function (key) {
var value = _this.options_[key];
if (isNumber(value)) {
_this[key + 'Event_'] = 'timeupdate';
} else if (hasNoWhitespace(value)) {
_this[key + 'Event_'] = value; // An overlay MUST have a start option. Otherwise, it's pointless.
} else if (key === 'start') {
throw new Error('invalid "start" option; expected number or string');
}
}); // video.js does not like components with multiple instances binding
// events to the player because it tracks them at the player level,
// not at the level of the object doing the binding. This could also be
// solved with Function.prototype.bind (but not videojs.bind because of
// its GUID magic), but the anonymous function approach avoids any issues
// caused by crappy libraries clobbering Function.prototype.bind.
// - https://github.com/videojs/video.js/issues/3097
['endListener_', 'rewindListener_', 'startListener_'].forEach(function (name$$1) {
_this[name$$1] = function (e) {
return Overlay.prototype[name$$1].call(_assertThisInitialized(_assertThisInitialized(_this)), e);
};
}); // If the start event is a timeupdate, we need to watch for rewinds (i.e.,
// when the user seeks backward).
if (_this.startEvent_ === 'timeupdate') {
_this.on(player, 'timeupdate', _this.rewindListener_);
}
_this.debug("created, listening to \"" + _this.startEvent_ + "\" for \"start\" and \"" + (_this.endEvent_ || 'nothing') + "\" for \"end\"");
_this.hide();
return _this;
}
var _proto = Overlay.prototype;
_proto.createEl = function createEl() {
var options = this.options_;
var content = options.content;
var background = options.showBackground ? 'vjs-overlay-background' : 'vjs-overlay-no-background';
var el = dom.createEl('div', {
className: "\n vjs-overlay\n vjs-overlay-" + options.align + "\n " + options.class + "\n " + background + "\n vjs-hidden\n "
});
if (typeof content === 'string') {
el.innerHTML = content;
} else if (content instanceof window.DocumentFragment) {
el.appendChild(content);
} else {
dom.appendContent(el, content);
}
return el;
};
/**
* Logs debug errors
* @param {...[type]} args [description]
* @return {[type]} [description]
*/
_proto.debug = function debug() {
if (!this.options_.debug) {
return;
}
var log = videojs.log;
var fn = log; // Support `videojs.log.foo` calls.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (log.hasOwnProperty(args[0]) && typeof log[args[0]] === 'function') {
fn = log[args.shift()];
}
fn.apply(void 0, ["overlay#" + this.id() + ": "].concat(args));
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.hide = function hide() {
_Component.prototype.hide.call(this);
this.debug('hidden');
this.debug("bound `startListener_` to \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("unbound `endListener_` from \"" + this.endEvent_ + "\"");
this.off(this.player(), this.endEvent_, this.endListener_);
}
this.on(this.player(), this.startEvent_, this.startListener_);
return this;
};
/**
* Determine whether or not the overlay should hide.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldHide_ = function shouldHide_(time, type) {
var end = this.options_.end;
return isNumber(end) ? time >= end : end === type;
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.show = function show() {
_Component.prototype.show.call(this);
this.off(this.player(), this.startEvent_, this.startListener_);
this.debug('shown');
this.debug("unbound `startListener_` from \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("bound `endListener_` to \"" + this.endEvent_ + "\"");
this.on(this.player(), this.endEvent_, this.endListener_);
}
return this;
};
/**
* Determine whether or not the overlay should show.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldShow_ = function shouldShow_(time, type) {
var start = this.options_.start;
var end = this.options_.end;
if (isNumber(start)) {
if (isNumber(end)) {
return time >= start && time < end; // In this case, the start is a number and the end is a string. We need
// to check whether or not the overlay has shown since the last seek.
} else if (!this.hasShownSinceSeek_) {
this.hasShownSinceSeek_ = true;
return time >= start;
} // In this case, the start is a number and the end is a string, but
// the overlay has shown since the last seek. This means that we need
// to be sure we aren't re-showing it at a later time than it is
// scheduled to appear.
return Math.floor(time) === start;
}
return start === type;
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.startListener_ = function startListener_(e) {
var time = this.player().currentTime();
if (this.shouldShow_(time, e.type)) {
this.show();
}
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.endListener_ = function endListener_(e) {
var time = this.player().currentTime();
if (this.shouldHide_(time, e.type)) {
this.hide();
}
};
/**
* Event listener that can looks for rewinds - that is, backward seeks
* and may hide the overlay as needed.
*
* @param {Event} e
*/
_proto.rewindListener_ = function rewindListener_(e) {
var time = this.player().currentTime();
var previous = this.previousTime_;
var start = this.options_.start;
var end = this.options_.end; // Did we seek backward?
if (time < previous) {
this.debug('rewind detected'); // The overlay remains visible if two conditions are met: the end value
// MUST be an integer and the the current time indicates that the
// overlay should NOT be visible.
if (isNumber(end) && !this.shouldShow_(time)) {
this.debug("hiding; " + end + " is an integer and overlay should not show at this time");
this.hasShownSinceSeek_ = false;
this.hide(); // If the end value is an event name, we cannot reliably decide if the
// overlay should still be displayed based solely on time; so, we can
// only queue it up for showing if the seek took us to a point before
// the start time.
} else if (hasNoWhitespace(end) && time < start) {
this.debug("hiding; show point (" + start + ") is before now (" + time + ") and end point (" + end + ") is an event");
this.hasShownSinceSeek_ = false;
this.hide();
}
}
this.previousTime_ = time;
};
return Overlay;
}(Component);
videojs.registerComponent('Overlay', Overlay);
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
var plugin = function plugin(options) {
var _this2 = this;
var settings = videojs.mergeOptions(defaults, options); // De-initialize the plugin if it already has an array of overlays.
if (Array.isArray(this.overlays_)) {
this.overlays_.forEach(function (overlay) {
_this2.removeChild(overlay);
if (_this2.controlBar) {
_this2.controlBar.removeChild(overlay);
}
overlay.dispose();
});
}
var overlays = settings.overlays; // We don't want to keep the original array of overlay options around
// because it doesn't make sense to pass it to each Overlay component.
delete settings.overlays;
this.overlays_ = overlays.map(function (o) {
var mergeOptions = videojs.mergeOptions(settings, o);
var attachToControlBar = typeof mergeOptions.attachToControlBar === 'string' || mergeOptions.attachToControlBar === true;
if (!_this2.controls() || !_this2.controlBar) {
return _this2.addChild('overlay', mergeOptions);
}
if (attachToControlBar && mergeOptions.align.indexOf('bottom') !== -1) {
var referenceChild = _this2.controlBar.children()[0];
if (_this2.controlBar.getChild(mergeOptions.attachToControlBar) !== undefined) {
referenceChild = _this2.controlBar.getChild(mergeOptions.attachToControlBar);
}
if (referenceChild) {
var controlBarChild = _this2.controlBar.addChild('overlay', mergeOptions);
_this2.controlBar.el().insertBefore(controlBarChild.el(), referenceChild.el());
return controlBarChild;
}
}
var playerChild = _this2.addChild('overlay', mergeOptions);
_this2.el().insertBefore(playerChild.el(), _this2.controlBar.el());
return playerChild;
});
};
plugin.VERSION = version;
registerPlugin('overlay', plugin);
return plugin;
})));
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('video.js'), require('global/window')) :
typeof define === 'function' && define.amd ? define(['video.js', 'global/window'], factory) :
(global.videojsOverlay = factory(global.videojs,global.window));
}(this, (function (videojs,window) { 'use strict';
videojs = videojs && videojs.hasOwnProperty('default') ? videojs['default'] : videojs;
window = window && window.hasOwnProperty('default') ? window['default'] : window;
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var version = "2.1.4";
var defaults = {
align: 'top-left',
class: '',
content: 'This overlay will show up while the video is playing',
debug: false,
showBackground: true,
attachToControlBar: false,
overlays: [{
start: 'playing',
end: 'paused'
}]
};
var Component = videojs.getComponent('Component');
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin;
/**
* Whether the value is a `Number`.
*
* Both `Infinity` and `-Infinity` are accepted, but `NaN` is not.
*
* @param {Number} n
* @return {Boolean}
*/
/* eslint-disable no-self-compare */
var isNumber = function isNumber(n) {
return typeof n === 'number' && n === n;
};
/* eslint-enable no-self-compare */
/**
* Whether a value is a string with no whitespace.
*
* @param {String} s
* @return {Boolean}
*/
var hasNoWhitespace = function hasNoWhitespace(s) {
return typeof s === 'string' && /^\S+$/.test(s);
};
/**
* Overlay component.
*
* @class Overlay
* @extends {videojs.Component}
*/
var Overlay =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Overlay, _Component);
function Overlay(player, options) {
var _this;
_this = _Component.call(this, player, options) || this;
['start', 'end'].forEach(function (key) {
var value = _this.options_[key];
if (isNumber(value)) {
_this[key + 'Event_'] = 'timeupdate';
} else if (hasNoWhitespace(value)) {
_this[key + 'Event_'] = value; // An overlay MUST have a start option. Otherwise, it's pointless.
} else if (key === 'start') {
throw new Error('invalid "start" option; expected number or string');
}
}); // video.js does not like components with multiple instances binding
// events to the player because it tracks them at the player level,
// not at the level of the object doing the binding. This could also be
// solved with Function.prototype.bind (but not videojs.bind because of
// its GUID magic), but the anonymous function approach avoids any issues
// caused by crappy libraries clobbering Function.prototype.bind.
// - https://github.com/videojs/video.js/issues/3097
['endListener_', 'rewindListener_', 'startListener_'].forEach(function (name$$1) {
_this[name$$1] = function (e) {
return Overlay.prototype[name$$1].call(_assertThisInitialized(_assertThisInitialized(_this)), e);
};
}); // If the start event is a timeupdate, we need to watch for rewinds (i.e.,
// when the user seeks backward).
if (_this.startEvent_ === 'timeupdate') {
_this.on(player, 'timeupdate', _this.rewindListener_);
}
_this.debug("created, listening to \"" + _this.startEvent_ + "\" for \"start\" and \"" + (_this.endEvent_ || 'nothing') + "\" for \"end\"");
_this.hide();
return _this;
}
var _proto = Overlay.prototype;
_proto.createEl = function createEl() {
var options = this.options_;
var content = options.content;
var background = options.showBackground ? 'vjs-overlay-background' : 'vjs-overlay-no-background';
var el = dom.createEl('div', {
className: "\n vjs-overlay\n vjs-overlay-" + options.align + "\n " + options.class + "\n " + background + "\n vjs-hidden\n "
});
if (typeof content === 'string') {
el.innerHTML = content;
} else if (content instanceof window.DocumentFragment) {
el.appendChild(content);
} else {
dom.appendContent(el, content);
}
return el;
};
/**
* Logs debug errors
* @param {...[type]} args [description]
* @return {[type]} [description]
*/
_proto.debug = function debug() {
if (!this.options_.debug) {
return;
}
var log = videojs.log;
var fn = log; // Support `videojs.log.foo` calls.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (log.hasOwnProperty(args[0]) && typeof log[args[0]] === 'function') {
fn = log[args.shift()];
}
fn.apply(void 0, ["overlay#" + this.id() + ": "].concat(args));
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.hide = function hide() {
_Component.prototype.hide.call(this);
this.debug('hidden');
this.debug("bound `startListener_` to \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("unbound `endListener_` from \"" + this.endEvent_ + "\"");
this.off(this.player(), this.endEvent_, this.endListener_);
}
this.on(this.player(), this.startEvent_, this.startListener_);
return this;
};
/**
* Determine whether or not the overlay should hide.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldHide_ = function shouldHide_(time, type) {
var end = this.options_.end;
return isNumber(end) ? time >= end : end === type;
};
/**
* Overrides the inherited method to perform some event binding
*
* @return {Overlay}
*/
_proto.show = function show() {
_Component.prototype.show.call(this);
this.off(this.player(), this.startEvent_, this.startListener_);
this.debug('shown');
this.debug("unbound `startListener_` from \"" + this.startEvent_ + "\""); // Overlays without an "end" are valid.
if (this.endEvent_) {
this.debug("bound `endListener_` to \"" + this.endEvent_ + "\"");
this.on(this.player(), this.endEvent_, this.endListener_);
}
return this;
};
/**
* Determine whether or not the overlay should show.
*
* @param {Number} time
* The current time reported by the player.
* @param {String} type
* An event type.
* @return {Boolean}
*/
_proto.shouldShow_ = function shouldShow_(time, type) {
var start = this.options_.start;
var end = this.options_.end;
if (isNumber(start)) {
if (isNumber(end)) {
return time >= start && time < end; // In this case, the start is a number and the end is a string. We need
// to check whether or not the overlay has shown since the last seek.
} else if (!this.hasShownSinceSeek_) {
this.hasShownSinceSeek_ = true;
return time >= start;
} // In this case, the start is a number and the end is a string, but
// the overlay has shown since the last seek. This means that we need
// to be sure we aren't re-showing it at a later time than it is
// scheduled to appear.
return Math.floor(time) === start;
}
return start === type;
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.startListener_ = function startListener_(e) {
var time = this.player().currentTime();
if (this.shouldShow_(time, e.type)) {
this.show();
}
};
/**
* Event listener that can trigger the overlay to show.
*
* @param {Event} e
*/
_proto.endListener_ = function endListener_(e) {
var time = this.player().currentTime();
if (this.shouldHide_(time, e.type)) {
this.hide();
}
};
/**
* Event listener that can looks for rewinds - that is, backward seeks
* and may hide the overlay as needed.
*
* @param {Event} e
*/
_proto.rewindListener_ = function rewindListener_(e) {
var time = this.player().currentTime();
var previous = this.previousTime_;
var start = this.options_.start;
var end = this.options_.end; // Did we seek backward?
if (time < previous) {
this.debug('rewind detected'); // The overlay remains visible if two conditions are met: the end value
// MUST be an integer and the the current time indicates that the
// overlay should NOT be visible.
if (isNumber(end) && !this.shouldShow_(time)) {
this.debug("hiding; " + end + " is an integer and overlay should not show at this time");
this.hasShownSinceSeek_ = false;
this.hide(); // If the end value is an event name, we cannot reliably decide if the
// overlay should still be displayed based solely on time; so, we can
// only queue it up for showing if the seek took us to a point before
// the start time.
} else if (hasNoWhitespace(end) && time < start) {
this.debug("hiding; show point (" + start + ") is before now (" + time + ") and end point (" + end + ") is an event");
this.hasShownSinceSeek_ = false;
this.hide();
}
}
this.previousTime_ = time;
};
return Overlay;
}(Component);
videojs.registerComponent('Overlay', Overlay);
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
var plugin = function plugin(options) {
var _this2 = this;
var settings = videojs.mergeOptions(defaults, options); // De-initialize the plugin if it already has an array of overlays.
if (Array.isArray(this.overlays_)) {
this.overlays_.forEach(function (overlay) {
_this2.removeChild(overlay);
if (_this2.controlBar) {
_this2.controlBar.removeChild(overlay);
}
overlay.dispose();
});
}
var overlays = settings.overlays; // We don't want to keep the original array of overlay options around
// because it doesn't make sense to pass it to each Overlay component.
delete settings.overlays;
this.overlays_ = overlays.map(function (o) {
var mergeOptions = videojs.mergeOptions(settings, o);
var attachToControlBar = typeof mergeOptions.attachToControlBar === 'string' || mergeOptions.attachToControlBar === true;
if (!_this2.controls() || !_this2.controlBar) {
return _this2.addChild('overlay', mergeOptions);
}
if (attachToControlBar && mergeOptions.align.indexOf('bottom') !== -1) {
var referenceChild = _this2.controlBar.children()[0];
if (_this2.controlBar.getChild(mergeOptions.attachToControlBar) !== undefined) {
referenceChild = _this2.controlBar.getChild(mergeOptions.attachToControlBar);
}
if (referenceChild) {
var controlBarChild = _this2.controlBar.addChild('overlay', mergeOptions);
_this2.controlBar.el().insertBefore(controlBarChild.el(), referenceChild.el());
return controlBarChild;
}
}
var playerChild = _this2.addChild('overlay', mergeOptions);
_this2.el().insertBefore(playerChild.el(), _this2.controlBar.el());
return playerChild;
});
};
plugin.VERSION = version;
registerPlugin('overlay', plugin);
return plugin;
})));

View file

@ -1,2 +1,2 @@
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("video.js"),require("global/window")):"function"==typeof define&&define.amd?define(["video.js","global/window"],e):t.videojsOverlay=e(t.videojs,t.window)}(this,function(t,e){"use strict";function n(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}t=t&&t.hasOwnProperty("default")?t.default:t,e=e&&e.hasOwnProperty("default")?e.default:e;var r={align:"top-left",class:"",content:"This overlay will show up while the video is playing",debug:!1,showBackground:!0,attachToControlBar:!1,overlays:[{start:"playing",end:"paused"}]},i=t.getComponent("Component"),o=t.dom||t,s=t.registerPlugin||t.plugin,a=function(t){return"number"==typeof t&&t==t},h=function(t){return"string"==typeof t&&/^\S+$/.test(t)},d=function(r){var i,s;function d(t,e){var i;return i=r.call(this,t,e)||this,["start","end"].forEach(function(t){var e=i.options_[t];if(a(e))i[t+"Event_"]="timeupdate";else if(h(e))i[t+"Event_"]=e;else if("start"===t)throw new Error('invalid "start" option; expected number or string')}),["endListener_","rewindListener_","startListener_"].forEach(function(t){i[t]=function(e){return d.prototype[t].call(n(n(i)),e)}}),"timeupdate"===i.startEvent_&&i.on(t,"timeupdate",i.rewindListener_),i.debug('created, listening to "'+i.startEvent_+'" for "start" and "'+(i.endEvent_||"nothing")+'" for "end"'),i.hide(),i}s=r,(i=d).prototype=Object.create(s.prototype),i.prototype.constructor=i,i.__proto__=s;var l=d.prototype;return l.createEl=function(){var t=this.options_,n=t.content,r=t.showBackground?"vjs-overlay-background":"vjs-overlay-no-background",i=o.createEl("div",{className:"\n vjs-overlay\n vjs-overlay-"+t.align+"\n "+t.class+"\n "+r+"\n vjs-hidden\n "});return"string"==typeof n?i.innerHTML=n:n instanceof e.DocumentFragment?i.appendChild(n):o.appendContent(i,n),i},l.debug=function(){if(this.options_.debug){for(var e=t.log,n=e,r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];e.hasOwnProperty(i[0])&&"function"==typeof e[i[0]]&&(n=e[i.shift()]),n.apply(void 0,["overlay#"+this.id()+": "].concat(i))}},l.hide=function(){return r.prototype.hide.call(this),this.debug("hidden"),this.debug('bound `startListener_` to "'+this.startEvent_+'"'),this.endEvent_&&(this.debug('unbound `endListener_` from "'+this.endEvent_+'"'),this.off(this.player(),this.endEvent_,this.endListener_)),this.on(this.player(),this.startEvent_,this.startListener_),this},l.shouldHide_=function(t,e){var n=this.options_.end;return a(n)?t>=n:n===e},l.show=function(){return r.prototype.show.call(this),this.off(this.player(),this.startEvent_,this.startListener_),this.debug("shown"),this.debug('unbound `startListener_` from "'+this.startEvent_+'"'),this.endEvent_&&(this.debug('bound `endListener_` to "'+this.endEvent_+'"'),this.on(this.player(),this.endEvent_,this.endListener_)),this},l.shouldShow_=function(t,e){var n=this.options_.start,r=this.options_.end;return a(n)?a(r)?t>=n&&t<r:this.hasShownSinceSeek_?Math.floor(t)===n:(this.hasShownSinceSeek_=!0,t>=n):n===e},l.startListener_=function(t){var e=this.player().currentTime();this.shouldShow_(e,t.type)&&this.show()},l.endListener_=function(t){var e=this.player().currentTime();this.shouldHide_(e,t.type)&&this.hide()},l.rewindListener_=function(t){var e=this.player().currentTime(),n=this.previousTime_,r=this.options_.start,i=this.options_.end;e<n&&(this.debug("rewind detected"),a(i)&&!this.shouldShow_(e)?(this.debug("hiding; "+i+" is an integer and overlay should not show at this time"),this.hasShownSinceSeek_=!1,this.hide()):h(i)&&e<r&&(this.debug("hiding; show point ("+r+") is before now ("+e+") and end point ("+i+") is an event"),this.hasShownSinceSeek_=!1,this.hide())),this.previousTime_=e},d}(i);t.registerComponent("Overlay",d);var l=function(e){var n=this,i=t.mergeOptions(r,e);Array.isArray(this.overlays_)&&this.overlays_.forEach(function(t){n.removeChild(t),n.controlBar&&n.controlBar.removeChild(t),t.dispose()});var o=i.overlays;delete i.overlays,this.overlays_=o.map(function(e){var r=t.mergeOptions(i,e),o="string"==typeof r.attachToControlBar||!0===r.attachToControlBar;if(!n.controls()||!n.controlBar)return n.addChild("overlay",r);if(o&&-1!==r.align.indexOf("bottom")){var s=n.controlBar.children()[0];if(void 0!==n.controlBar.getChild(r.attachToControlBar)&&(s=n.controlBar.getChild(r.attachToControlBar)),s){var a=n.controlBar.addChild("overlay",r);return n.controlBar.el().insertBefore(a.el(),s.el()),a}}var h=n.addChild("overlay",r);return n.el().insertBefore(h.el(),n.controlBar.el()),h})};return l.VERSION="2.1.4",s("overlay",l),l});
/*! @name videojs-overlay @version 2.1.4 @license Apache-2.0 */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("video.js"),require("global/window")):"function"==typeof define&&define.amd?define(["video.js","global/window"],e):t.videojsOverlay=e(t.videojs,t.window)}(this,function(t,e){"use strict";function n(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}t=t&&t.hasOwnProperty("default")?t.default:t,e=e&&e.hasOwnProperty("default")?e.default:e;var r={align:"top-left",class:"",content:"This overlay will show up while the video is playing",debug:!1,showBackground:!0,attachToControlBar:!1,overlays:[{start:"playing",end:"paused"}]},i=t.getComponent("Component"),o=t.dom||t,s=t.registerPlugin||t.plugin,a=function(t){return"number"==typeof t&&t==t},h=function(t){return"string"==typeof t&&/^\S+$/.test(t)},d=function(r){var i,s;function d(t,e){var i;return i=r.call(this,t,e)||this,["start","end"].forEach(function(t){var e=i.options_[t];if(a(e))i[t+"Event_"]="timeupdate";else if(h(e))i[t+"Event_"]=e;else if("start"===t)throw new Error('invalid "start" option; expected number or string')}),["endListener_","rewindListener_","startListener_"].forEach(function(t){i[t]=function(e){return d.prototype[t].call(n(n(i)),e)}}),"timeupdate"===i.startEvent_&&i.on(t,"timeupdate",i.rewindListener_),i.debug('created, listening to "'+i.startEvent_+'" for "start" and "'+(i.endEvent_||"nothing")+'" for "end"'),i.hide(),i}s=r,(i=d).prototype=Object.create(s.prototype),i.prototype.constructor=i,i.__proto__=s;var l=d.prototype;return l.createEl=function(){var t=this.options_,n=t.content,r=t.showBackground?"vjs-overlay-background":"vjs-overlay-no-background",i=o.createEl("div",{className:"\n vjs-overlay\n vjs-overlay-"+t.align+"\n "+t.class+"\n "+r+"\n vjs-hidden\n "});return"string"==typeof n?i.innerHTML=n:n instanceof e.DocumentFragment?i.appendChild(n):o.appendContent(i,n),i},l.debug=function(){if(this.options_.debug){for(var e=t.log,n=e,r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];e.hasOwnProperty(i[0])&&"function"==typeof e[i[0]]&&(n=e[i.shift()]),n.apply(void 0,["overlay#"+this.id()+": "].concat(i))}},l.hide=function(){return r.prototype.hide.call(this),this.debug("hidden"),this.debug('bound `startListener_` to "'+this.startEvent_+'"'),this.endEvent_&&(this.debug('unbound `endListener_` from "'+this.endEvent_+'"'),this.off(this.player(),this.endEvent_,this.endListener_)),this.on(this.player(),this.startEvent_,this.startListener_),this},l.shouldHide_=function(t,e){var n=this.options_.end;return a(n)?t>=n:n===e},l.show=function(){return r.prototype.show.call(this),this.off(this.player(),this.startEvent_,this.startListener_),this.debug("shown"),this.debug('unbound `startListener_` from "'+this.startEvent_+'"'),this.endEvent_&&(this.debug('bound `endListener_` to "'+this.endEvent_+'"'),this.on(this.player(),this.endEvent_,this.endListener_)),this},l.shouldShow_=function(t,e){var n=this.options_.start,r=this.options_.end;return a(n)?a(r)?t>=n&&t<r:this.hasShownSinceSeek_?Math.floor(t)===n:(this.hasShownSinceSeek_=!0,t>=n):n===e},l.startListener_=function(t){var e=this.player().currentTime();this.shouldShow_(e,t.type)&&this.show()},l.endListener_=function(t){var e=this.player().currentTime();this.shouldHide_(e,t.type)&&this.hide()},l.rewindListener_=function(t){var e=this.player().currentTime(),n=this.previousTime_,r=this.options_.start,i=this.options_.end;e<n&&(this.debug("rewind detected"),a(i)&&!this.shouldShow_(e)?(this.debug("hiding; "+i+" is an integer and overlay should not show at this time"),this.hasShownSinceSeek_=!1,this.hide()):h(i)&&e<r&&(this.debug("hiding; show point ("+r+") is before now ("+e+") and end point ("+i+") is an event"),this.hasShownSinceSeek_=!1,this.hide())),this.previousTime_=e},d}(i);t.registerComponent("Overlay",d);var l=function(e){var n=this,i=t.mergeOptions(r,e);Array.isArray(this.overlays_)&&this.overlays_.forEach(function(t){n.removeChild(t),n.controlBar&&n.controlBar.removeChild(t),t.dispose()});var o=i.overlays;delete i.overlays,this.overlays_=o.map(function(e){var r=t.mergeOptions(i,e),o="string"==typeof r.attachToControlBar||!0===r.attachToControlBar;if(!n.controls()||!n.controlBar)return n.addChild("overlay",r);if(o&&-1!==r.align.indexOf("bottom")){var s=n.controlBar.children()[0];if(void 0!==n.controlBar.getChild(r.attachToControlBar)&&(s=n.controlBar.getChild(r.attachToControlBar)),s){var a=n.controlBar.addChild("overlay",r);return n.controlBar.el().insertBefore(a.el(),s.el()),a}}var h=n.addChild("overlay",r);return n.el().insertBefore(h.el(),n.controlBar.el()),h})};return l.VERSION="2.1.4",s("overlay",l),l});

View file

@ -1,494 +1,494 @@
<?php
/**
* https://support.google.com/adsense/answer/4455881
* https://support.google.com/adsense/answer/1705822
* AdSense for video: Publisher Approval Form
* https://services.google.com/fb/forms/afvapproval/
*/
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 [
PluginTags::$MONETIZATION,
PluginTags::$ADS,
PluginTags::$FREE,
PluginTags::$PLAYER,
];
}
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()
{
return "AD_Server";
}
public function getUUID()
{
return "3f2a707f-3c06-4b78-90f9-a22f2fda92ef";
}
public function getPluginVersion()
{
return "1.0";
}
public function getEmptyDataObject()
{
$obj = new stdClass();
$obj->start = true;
self::addDataObjectHelper('start', 'Show Pre-Roll ads');
$obj->mid25Percent = true;
self::addDataObjectHelper('mid25Percent', 'Show Mid-Roll ads at 25%');
$obj->mid50Percent = true;
self::addDataObjectHelper('mid50Percent', 'Show Mid-Roll ads at 50%');
$obj->mid75Percent = true;
self::addDataObjectHelper('mid75Percent', 'Show Mid-Roll ads at 75%');
$obj->end = true;
self::addDataObjectHelper('end', 'Show Post-Roll ads');
$o = new stdClass();
$o->type = [];
for ($i = 0; $i <= 100; $i++) {
$o->type[$i . '%'] = "The skip button will appear when you watch {$i}% of the video";
}
$o->value = '10%';
$obj->skipoffset = $o;
self::addDataObjectHelper('skipoffset', 'Skip Offset', 'This is the percentage where the skip button should appear');
$obj->showMarkers = true;
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 = [1 => 'Every video'];
for ($i = 2; $i < 10; $i++) {
$o->type[$i] = "Show ads on each {$i} videos";
}
$o->value = 1;
$obj->showAdsOnEachVideoView = $o;
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 = [0 => 'All positions'];
for ($i = 1; $i < 5; $i++) {
$o->type[$i] = "Show ads on {$i} random positions";
}
$o->value = 2;
$obj->showAdsOnRandomPositions = $o;
self::addDataObjectHelper('showAdsOnRandomPositions', 'Show Ads On Positions', 'This will pick random positions to display the ads, but it will pic only the positions you have checked above. For example, if you want to have 2 random positions, but do not want to have videos on the start position, you must uncheck the start video position checkbox;');
$o = new stdClass();
$o->type = [0 => 'Do not auto add new videos on campaign'];
$rows = VastCampaigns::getAllActive();
if (!is_array($rows)) {
$o->value = 0;
$obj->autoAddNewVideosInCampaignId = $o;
return $obj;
}
foreach ($rows as $row) {
$o->type[$row['id']] = '- ' . $row['name'];
}
$o->value = 0;
$obj->autoAddNewVideosInCampaignId = $o;
self::addDataObjectHelper('autoAddNewVideosInCampaignId', 'Auto Add New Videos In Campaign');
return $obj;
}
public function afterNewVideo($videos_id)
{
_error_log("AD_Server:afterNewVideo start");
$obj = $this->getDataObject();
if (!empty($obj->autoAddNewVideosInCampaignId)) {
$vc = new VastCampaigns($obj->autoAddNewVideosInCampaignId);
if (!empty($vc->getName())) {
$video = new Video("", "", $videos_id);
if (!empty($video->getTitle()) && !empty($obj->autoAddNewVideosInCampaignId->value)) {
_error_log("AD_Server:afterNewVideo saving");
$o = new VastCampaignsVideos(0);
$o->setVast_campaigns_id($obj->autoAddNewVideosInCampaignId->value);
$o->setVideos_id($videos_id);
$o->setLink("");
$o->setAd_title($video->getTitle());
$o->setStatus('a');
$id = $o->save();
_error_log("AD_Server:afterNewVideo saved {$id}");
} else {
_error_log("AD_Server:afterNewVideo videos_id NOT found {$videos_id}");
}
} else {
_error_log("AD_Server:afterNewVideo autoAddNewVideosInCampaignId NOT found ". json_encode($obj->autoAddNewVideosInCampaignId));
}
} else {
_error_log("AD_Server:afterNewVideo is disabled");
}
return true;
}
public function canLoadAds()
{
//if (empty($_GET['videoName']) && empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
return false;
}
}
if (empty($_GET['videoName'])) {
return false;
}
// count it each 2 seconds
if (empty($_SESSION['lastAdShowed']) || $_SESSION['lastAdShowed'] + 2 <= time()) {
_session_start();
$_SESSION['lastAdShowed'] = time();
if (!isset($_SESSION['showAdsCount'])) {
//_error_log("Show Ads Count started");
$_SESSION['showAdsCount'] = 1;
} else {
$_SESSION['showAdsCount']++;
}
}
//_error_log("Show Ads Count {$_SESSION['showAdsCount']}");
$obj = $this->getDataObject();
if (!empty($obj->showAdsOnEachVideoView->value) && $_SESSION['showAdsCount'] % $obj->showAdsOnEachVideoView->value === 0) {
return true;
}
return false;
}
public function getHeadCode()
{
$obj = $this->getDataObject();
if (!$this->canLoadAds()) {
return "";
}
global $global;
$_GET['vmap_id'] = session_id();
$css = '<link href="' . getURL('node_modules/videojs-contrib-ads/dist/videojs.ads.css') . '" rel="stylesheet" type="text/css"/>'
. '<link href="' . getURL('node_modules/videojs-ima/dist/videojs.ima.css') . '" rel="stylesheet" type="text/css"/>';
if (!empty($obj->showMarkers)) {
$css .= '<link href="' . getCDN() . 'plugin/AD_Server/videojs-markers/videojs.markers.css" rel="stylesheet" type="text/css"/>';
}
$css .= '<style>.ima-ad-container{z-index:1000 !important;}</style>';
return $css;
}
private static function getVideoLength()
{
$video_length = 3600; // 1 hour
$videos_id = getVideos_id();
$video = new Video('', '', $videos_id);
$duration = $video->getDuration();
if (!empty($duration)) {
$video_length = parseDurationToSeconds($duration);
}
return $video_length;
}
public static function getVMAPSFromRequest()
{
if (!empty($_REQUEST['vmaps'])) {
$vmaps = _json_decode(base64_decode($_REQUEST['vmaps']));
} else {
$video_length = self::getVideoLength();
$ad_server = AVideoPlugin::loadPlugin('AD_Server');
$vmaps = $ad_server->getVMAPs($video_length);
}
return object_to_array($vmaps);
}
public static function addVMAPS($url, $vmaps)
{
if (empty($vmaps)) {
$vmaps = self::getVMAPSFromRequest();
}
$base64 = base64_encode(_json_encode($vmaps));
$vmapURL = addQueryStringParameter($url, 'vmaps', $base64);
return $vmapURL;
}
public function afterVideoJS()
{
$obj = $this->getDataObject();
if (!$this->canLoadAds() || empty($_GET['vmap_id'])) {
return "";
}
global $global;
$vmap_id = @$_GET['vmap_id'];
$vmaps = self::getVMAPSFromRequest();
$video_length = self::getVideoLength();
$vmapURL = "{$global['webSiteRootURL']}plugin/AD_Server/VMAP.php";
$vmapURL = addQueryStringParameter($vmapURL, 'video_length', $video_length);
$vmapURL = addQueryStringParameter($vmapURL, 'vmap_id', $vmap_id);
$vmapURL = addQueryStringParameter($vmapURL, 'random', uniqid());
$vmapURL = self::addVMAPS($vmapURL, $vmaps);
//var_dump($vmapURL, $vmaps);exit;
PlayerSkins::setIMAADTag($vmapURL);
$onPlayerReady = "";
if (!empty($obj->showMarkers)) {
$onPlayerReady .= "
player.markers({
markerStyle: {
'width': '5px',
'background-color': 'yellow'
},
markerTip: {
display: true,
text: function (marker) {
return marker.text;
}
},
markers: [";
foreach ($vmaps as $value) {
$vastCampaingVideos = new VastCampaignsVideos($value['VAST']['campaing']);
$video = new Video("", "", $vastCampaingVideos->getVideos_id());
if (!empty($video_length) && $value['timeOffsetSeconds'] >= $video_length) {
$value['timeOffsetSeconds'] = $video_length-5;
}
$onPlayerReady .= "{time: {$value['timeOffsetSeconds']}, text: \"" . addcslashes($video->getTitle(), '"') . "\"},";
}
$onPlayerReady .= "]});";
}
PlayerSkins::getStartPlayerJS($onPlayerReady);
$js = '';
$js .= '<script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-contrib-ads/dist/videojs.ads.min.js') . '" type="text/javascript"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-ima/dist/videojs.ima.min.js') . '" type="text/javascript"></script>';
if (!empty($obj->showMarkers)) {
$js .= '<script src="' . getCDN() . 'plugin/AD_Server/videojs-markers/videojs-markers.js"></script>';
}
return $js;
}
private function getRandomPositions()
{
if (empty($_GET['vmap_id'])) {
return "";
}
$obj = $this->getDataObject();
$oldId = session_id();
if (session_status() !== PHP_SESSION_NONE) {
session_write_close();
}
session_id($_GET['vmap_id']);
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$options = [];
if (!empty($obj->start)) {
$options[] = 1;
}
if (!empty($obj->mid25Percent)) {
$options[] = 2;
}
if (!empty($obj->mid50Percent)) {
$options[] = 3;
}
if (!empty($obj->mid75Percent)) {
$options[] = 4;
}
if (!empty($obj->end)) {
$options[] = 5;
}
$selectedOptions = [];
if (empty($_SESSION['lastAdRandomPositions']) || $_SESSION['lastAdRandomPositions'] + 20 <= time()) {
$_SESSION['lastAdRandomPositions'] = time();
if (empty($obj->showAdsOnRandomPositions->value)) {
$selectedOptions = $options;
} else {
for ($i = 0; $i < $obj->showAdsOnRandomPositions->value; $i++) {
shuffle($options);
$selectedOptions[] = array_pop($options);
}
}
$_SESSION['adRandomPositions'] = $selectedOptions;
}
$adRandomPositions = $_SESSION['adRandomPositions'];
if (session_status() !== PHP_SESSION_NONE) {
session_write_close();
}
session_id($oldId);
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
//_error_log("VMAP select those options: " . print_r($adRandomPositions, true));
return $adRandomPositions;
}
public function getVMAPs($video_length)
{
$vmaps = [];
$obj = $this->getDataObject();
$selectedOptions = $this->getRandomPositions();
if (!empty($obj->start) && in_array(1, $selectedOptions)) {
$vmaps[] = new VMAP("start", new VAST(1));
}
if (!empty($obj->mid25Percent) && in_array(2, $selectedOptions)) {
$val = $video_length * (25 / 100);
$vmaps[] = new VMAP($val, new VAST(2));
}
if (!empty($obj->mid50Percent) && in_array(3, $selectedOptions)) {
$val = $video_length * (50 / 100);
$vmaps[] = new VMAP($val, new VAST(3));
}
if (!empty($obj->mid75Percent) && in_array(4, $selectedOptions)) {
$val = $video_length * (75 / 100);
$vmaps[] = new VMAP($val, new VAST(4));
}
if (!empty($obj->end) && in_array(5, $selectedOptions)) {
$vmaps[] = new VMAP("end", new VAST(5), $video_length);
}
return $vmaps;
}
public function VMAPsHasVideos()
{
$vmaps = $this->getVMAPs(100);
//var_dump($vmaps);exit;
foreach ($vmaps as $value) {
if (empty($value->VAST->campaing)) {
return false;
}
}
return true;
}
public function showAdsNow()
{
if (!$this->VMAPsHasVideos()) {
return false;
}
}
public static function getVideos()
{
$campaings = VastCampaigns::getValidCampaigns();
//var_dump($campaings);
$videos = [];
foreach ($campaings as $key => $value) {
$v = VastCampaignsVideos::getValidVideos($value['id']);
$videos = array_merge($videos, $v);
$campaings[$key]['videos'] = $v;
}
return ['campaigns' => $campaings, 'videos' => $videos];
}
public static function getRandomVideo()
{
$result = static::getVideos();
$videos = $result['videos'];
shuffle($videos);
return array_pop($videos);
}
public static function getRandomCampaign()
{
$result = static::getVideos();
$campaing = $result['campaigns'];
shuffle($campaing);
return array_pop($campaing);
}
public function getPluginMenu()
{
global $global;
$filename = $global['systemRootPath'] . 'plugin/AD_Server/pluginMenu.html';
return file_get_contents($filename);
}
public function getValidCampaignsFromVideo($videos_id)
{
return VastCampaigns::getValidCampaignsFromVideo($videos_id);
}
}
class VMAP
{
public $timeOffset;
public $timeOffsetSeconds;
public $VAST;
public $idTag = "preroll-ad";
public function __construct($time, VAST $VAST, $video_length = 0)
{
if ($time === 'start') {
$this->timeOffsetSeconds = 0;
} elseif ($time === 'end') {
$this->timeOffsetSeconds = $video_length;
} else {
$this->timeOffsetSeconds = $time;
}
$this->VAST = $VAST;
$this->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;
} elseif ($time == "end") {
$this->idTag = "postroll-ad-" . $this->VAST->id;
} elseif (is_numeric($time)) {
$time = $this->format($time);
$this->idTag = "midroll-" . $this->VAST->id;
}
// format to 00:00:15.000
$this->timeOffset = $time;
}
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
{
public $id;
public $campaing;
public function __construct($id)
{
$this->id = $id;
$row = AD_Server::getRandomVideo();
if (!empty($row)) {
$this->campaing = $row['id'];
} else {
$this->campaing = false;
}
}
}
<?php
/**
* https://support.google.com/adsense/answer/4455881
* https://support.google.com/adsense/answer/1705822
* AdSense for video: Publisher Approval Form
* https://services.google.com/fb/forms/afvapproval/
*/
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 [
PluginTags::$MONETIZATION,
PluginTags::$ADS,
PluginTags::$FREE,
PluginTags::$PLAYER,
];
}
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()
{
return "AD_Server";
}
public function getUUID()
{
return "3f2a707f-3c06-4b78-90f9-a22f2fda92ef";
}
public function getPluginVersion()
{
return "1.0";
}
public function getEmptyDataObject()
{
$obj = new stdClass();
$obj->start = true;
self::addDataObjectHelper('start', 'Show Pre-Roll ads');
$obj->mid25Percent = true;
self::addDataObjectHelper('mid25Percent', 'Show Mid-Roll ads at 25%');
$obj->mid50Percent = true;
self::addDataObjectHelper('mid50Percent', 'Show Mid-Roll ads at 50%');
$obj->mid75Percent = true;
self::addDataObjectHelper('mid75Percent', 'Show Mid-Roll ads at 75%');
$obj->end = true;
self::addDataObjectHelper('end', 'Show Post-Roll ads');
$o = new stdClass();
$o->type = [];
for ($i = 0; $i <= 100; $i++) {
$o->type[$i . '%'] = "The skip button will appear when you watch {$i}% of the video";
}
$o->value = '10%';
$obj->skipoffset = $o;
self::addDataObjectHelper('skipoffset', 'Skip Offset', 'This is the percentage where the skip button should appear');
$obj->showMarkers = true;
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 = [1 => 'Every video'];
for ($i = 2; $i < 10; $i++) {
$o->type[$i] = "Show ads on each {$i} videos";
}
$o->value = 1;
$obj->showAdsOnEachVideoView = $o;
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 = [0 => 'All positions'];
for ($i = 1; $i < 5; $i++) {
$o->type[$i] = "Show ads on {$i} random positions";
}
$o->value = 2;
$obj->showAdsOnRandomPositions = $o;
self::addDataObjectHelper('showAdsOnRandomPositions', 'Show Ads On Positions', 'This will pick random positions to display the ads, but it will pic only the positions you have checked above. For example, if you want to have 2 random positions, but do not want to have videos on the start position, you must uncheck the start video position checkbox;');
$o = new stdClass();
$o->type = [0 => 'Do not auto add new videos on campaign'];
$rows = VastCampaigns::getAllActive();
if (!is_array($rows)) {
$o->value = 0;
$obj->autoAddNewVideosInCampaignId = $o;
return $obj;
}
foreach ($rows as $row) {
$o->type[$row['id']] = '- ' . $row['name'];
}
$o->value = 0;
$obj->autoAddNewVideosInCampaignId = $o;
self::addDataObjectHelper('autoAddNewVideosInCampaignId', 'Auto Add New Videos In Campaign');
return $obj;
}
public function afterNewVideo($videos_id)
{
_error_log("AD_Server:afterNewVideo start");
$obj = $this->getDataObject();
if (!empty($obj->autoAddNewVideosInCampaignId)) {
$vc = new VastCampaigns($obj->autoAddNewVideosInCampaignId);
if (!empty($vc->getName())) {
$video = new Video("", "", $videos_id);
if (!empty($video->getTitle()) && !empty($obj->autoAddNewVideosInCampaignId->value)) {
_error_log("AD_Server:afterNewVideo saving");
$o = new VastCampaignsVideos(0);
$o->setVast_campaigns_id($obj->autoAddNewVideosInCampaignId->value);
$o->setVideos_id($videos_id);
$o->setLink("");
$o->setAd_title($video->getTitle());
$o->setStatus('a');
$id = $o->save();
_error_log("AD_Server:afterNewVideo saved {$id}");
} else {
_error_log("AD_Server:afterNewVideo videos_id NOT found {$videos_id}");
}
} else {
_error_log("AD_Server:afterNewVideo autoAddNewVideosInCampaignId NOT found ". json_encode($obj->autoAddNewVideosInCampaignId));
}
} else {
_error_log("AD_Server:afterNewVideo is disabled");
}
return true;
}
public function canLoadAds()
{
//if (empty($_GET['videoName']) && empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
return false;
}
}
if (empty($_GET['videoName'])) {
return false;
}
// count it each 2 seconds
if (empty($_SESSION['lastAdShowed']) || $_SESSION['lastAdShowed'] + 2 <= time()) {
_session_start();
$_SESSION['lastAdShowed'] = time();
if (!isset($_SESSION['showAdsCount'])) {
//_error_log("Show Ads Count started");
$_SESSION['showAdsCount'] = 1;
} else {
$_SESSION['showAdsCount']++;
}
}
//_error_log("Show Ads Count {$_SESSION['showAdsCount']}");
$obj = $this->getDataObject();
if (!empty($obj->showAdsOnEachVideoView->value) && $_SESSION['showAdsCount'] % $obj->showAdsOnEachVideoView->value === 0) {
return true;
}
return false;
}
public function getHeadCode()
{
$obj = $this->getDataObject();
if (!$this->canLoadAds()) {
return "";
}
global $global;
$_GET['vmap_id'] = session_id();
$css = '<link href="' . getURL('node_modules/videojs-contrib-ads/dist/videojs.ads.css') . '" rel="stylesheet" type="text/css"/>'
. '<link href="' . getURL('node_modules/videojs-ima/dist/videojs.ima.css') . '" rel="stylesheet" type="text/css"/>';
if (!empty($obj->showMarkers)) {
$css .= '<link href="' . getCDN() . 'plugin/AD_Server/videojs-markers/videojs.markers.css" rel="stylesheet" type="text/css"/>';
}
$css .= '<style>.ima-ad-container{z-index:1000 !important;}</style>';
return $css;
}
private static function getVideoLength()
{
$video_length = 3600; // 1 hour
$videos_id = getVideos_id();
$video = new Video('', '', $videos_id);
$duration = $video->getDuration();
if (!empty($duration)) {
$video_length = parseDurationToSeconds($duration);
}
return $video_length;
}
public static function getVMAPSFromRequest()
{
if (!empty($_REQUEST['vmaps'])) {
$vmaps = _json_decode(base64_decode($_REQUEST['vmaps']));
} else {
$video_length = self::getVideoLength();
$ad_server = AVideoPlugin::loadPlugin('AD_Server');
$vmaps = $ad_server->getVMAPs($video_length);
}
return object_to_array($vmaps);
}
public static function addVMAPS($url, $vmaps)
{
if (empty($vmaps)) {
$vmaps = self::getVMAPSFromRequest();
}
$base64 = base64_encode(_json_encode($vmaps));
$vmapURL = addQueryStringParameter($url, 'vmaps', $base64);
return $vmapURL;
}
public function afterVideoJS()
{
$obj = $this->getDataObject();
if (!$this->canLoadAds() || empty($_GET['vmap_id'])) {
return "";
}
global $global;
$vmap_id = @$_GET['vmap_id'];
$vmaps = self::getVMAPSFromRequest();
$video_length = self::getVideoLength();
$vmapURL = "{$global['webSiteRootURL']}plugin/AD_Server/VMAP.php";
$vmapURL = addQueryStringParameter($vmapURL, 'video_length', $video_length);
$vmapURL = addQueryStringParameter($vmapURL, 'vmap_id', $vmap_id);
$vmapURL = addQueryStringParameter($vmapURL, 'random', uniqid());
$vmapURL = self::addVMAPS($vmapURL, $vmaps);
//var_dump($vmapURL, $vmaps);exit;
PlayerSkins::setIMAADTag($vmapURL);
$onPlayerReady = "";
if (!empty($obj->showMarkers)) {
$onPlayerReady .= "
player.markers({
markerStyle: {
'width': '5px',
'background-color': 'yellow'
},
markerTip: {
display: true,
text: function (marker) {
return marker.text;
}
},
markers: [";
foreach ($vmaps as $value) {
$vastCampaingVideos = new VastCampaignsVideos($value['VAST']['campaing']);
$video = new Video("", "", $vastCampaingVideos->getVideos_id());
if (!empty($video_length) && $value['timeOffsetSeconds'] >= $video_length) {
$value['timeOffsetSeconds'] = $video_length-5;
}
$onPlayerReady .= "{time: {$value['timeOffsetSeconds']}, text: \"" . addcslashes($video->getTitle(), '"') . "\"},";
}
$onPlayerReady .= "]});";
}
PlayerSkins::getStartPlayerJS($onPlayerReady);
$js = '';
$js .= '<script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-contrib-ads/dist/videojs.ads.min.js') . '" type="text/javascript"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-ima/dist/videojs.ima.min.js') . '" type="text/javascript"></script>';
if (!empty($obj->showMarkers)) {
$js .= '<script src="' . getCDN() . 'plugin/AD_Server/videojs-markers/videojs-markers.js"></script>';
}
return $js;
}
private function getRandomPositions()
{
if (empty($_GET['vmap_id'])) {
return "";
}
$obj = $this->getDataObject();
$oldId = session_id();
if (session_status() !== PHP_SESSION_NONE) {
session_write_close();
}
session_id($_GET['vmap_id']);
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$options = [];
if (!empty($obj->start)) {
$options[] = 1;
}
if (!empty($obj->mid25Percent)) {
$options[] = 2;
}
if (!empty($obj->mid50Percent)) {
$options[] = 3;
}
if (!empty($obj->mid75Percent)) {
$options[] = 4;
}
if (!empty($obj->end)) {
$options[] = 5;
}
$selectedOptions = [];
if (empty($_SESSION['lastAdRandomPositions']) || $_SESSION['lastAdRandomPositions'] + 20 <= time()) {
$_SESSION['lastAdRandomPositions'] = time();
if (empty($obj->showAdsOnRandomPositions->value)) {
$selectedOptions = $options;
} else {
for ($i = 0; $i < $obj->showAdsOnRandomPositions->value; $i++) {
shuffle($options);
$selectedOptions[] = array_pop($options);
}
}
$_SESSION['adRandomPositions'] = $selectedOptions;
}
$adRandomPositions = $_SESSION['adRandomPositions'];
if (session_status() !== PHP_SESSION_NONE) {
session_write_close();
}
session_id($oldId);
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
//_error_log("VMAP select those options: " . print_r($adRandomPositions, true));
return $adRandomPositions;
}
public function getVMAPs($video_length)
{
$vmaps = [];
$obj = $this->getDataObject();
$selectedOptions = $this->getRandomPositions();
if (!empty($obj->start) && in_array(1, $selectedOptions)) {
$vmaps[] = new VMAP("start", new VAST(1));
}
if (!empty($obj->mid25Percent) && in_array(2, $selectedOptions)) {
$val = $video_length * (25 / 100);
$vmaps[] = new VMAP($val, new VAST(2));
}
if (!empty($obj->mid50Percent) && in_array(3, $selectedOptions)) {
$val = $video_length * (50 / 100);
$vmaps[] = new VMAP($val, new VAST(3));
}
if (!empty($obj->mid75Percent) && in_array(4, $selectedOptions)) {
$val = $video_length * (75 / 100);
$vmaps[] = new VMAP($val, new VAST(4));
}
if (!empty($obj->end) && in_array(5, $selectedOptions)) {
$vmaps[] = new VMAP("end", new VAST(5), $video_length);
}
return $vmaps;
}
public function VMAPsHasVideos()
{
$vmaps = $this->getVMAPs(100);
//var_dump($vmaps);exit;
foreach ($vmaps as $value) {
if (empty($value->VAST->campaing)) {
return false;
}
}
return true;
}
public function showAdsNow()
{
if (!$this->VMAPsHasVideos()) {
return false;
}
}
public static function getVideos()
{
$campaings = VastCampaigns::getValidCampaigns();
//var_dump($campaings);
$videos = [];
foreach ($campaings as $key => $value) {
$v = VastCampaignsVideos::getValidVideos($value['id']);
$videos = array_merge($videos, $v);
$campaings[$key]['videos'] = $v;
}
return ['campaigns' => $campaings, 'videos' => $videos];
}
public static function getRandomVideo()
{
$result = static::getVideos();
$videos = $result['videos'];
shuffle($videos);
return array_pop($videos);
}
public static function getRandomCampaign()
{
$result = static::getVideos();
$campaing = $result['campaigns'];
shuffle($campaing);
return array_pop($campaing);
}
public function getPluginMenu()
{
global $global;
$filename = $global['systemRootPath'] . 'plugin/AD_Server/pluginMenu.html';
return file_get_contents($filename);
}
public function getValidCampaignsFromVideo($videos_id)
{
return VastCampaigns::getValidCampaignsFromVideo($videos_id);
}
}
class VMAP
{
public $timeOffset;
public $timeOffsetSeconds;
public $VAST;
public $idTag = "preroll-ad";
public function __construct($time, VAST $VAST, $video_length = 0)
{
if ($time === 'start') {
$this->timeOffsetSeconds = 0;
} elseif ($time === 'end') {
$this->timeOffsetSeconds = $video_length;
} else {
$this->timeOffsetSeconds = $time;
}
$this->VAST = $VAST;
$this->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;
} elseif ($time == "end") {
$this->idTag = "postroll-ad-" . $this->VAST->id;
} elseif (is_numeric($time)) {
$time = $this->format($time);
$this->idTag = "midroll-" . $this->VAST->id;
}
// format to 00:00:15.000
$this->timeOffset = $time;
}
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
{
public $id;
public $campaing;
public function __construct($id)
{
$this->id = $id;
$row = AD_Server::getRandomVideo();
if (!empty($row)) {
$this->campaing = $row['id'];
} else {
$this->campaing = false;
}
}
}

View file

@ -1,373 +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;
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;
}
}
<?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

@ -1,131 +1,131 @@
<?php
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
{
protected $id;
protected $users_id;
protected $type;
protected $vast_campaigns_has_videos_id;
protected $ip;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'vast_campaigns_logs';
}
public function getId()
{
return $this->id;
}
public function getUsers_id()
{
return $this->users_id;
}
public function getType()
{
return $this->type;
}
public function getVast_campaigns_has_videos_id()
{
return $this->vast_campaigns_has_videos_id;
}
public function setId($id)
{
$this->id = $id;
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function setType($type)
{
$this->type = $type;
}
public function setVast_campaigns_has_videos_id($vast_campaigns_has_videos_id)
{
$this->vast_campaigns_has_videos_id = $vast_campaigns_has_videos_id;
}
public function getIp()
{
return $this->ip;
}
public function save()
{
$this->ip = getRealIpAddr();
return parent::save();
}
public static function getViews()
{
global $global;
$sql = "SELECT count(*) as total FROM vast_campaigns_logs WHERE `type` = 'start'";
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row['total'];
}
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);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$data = [];
if ($res!=false) {
foreach ($fullData as $row) {
$data[$row['type']] = $row['total'];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $data;
}
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);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$data = [];
if ($res!=false) {
foreach ($fullData as $row) {
$data[$row['type']] = $row['total'];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $data;
}
}
<?php
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
{
protected $id;
protected $users_id;
protected $type;
protected $vast_campaigns_has_videos_id;
protected $ip;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'vast_campaigns_logs';
}
public function getId()
{
return $this->id;
}
public function getUsers_id()
{
return $this->users_id;
}
public function getType()
{
return $this->type;
}
public function getVast_campaigns_has_videos_id()
{
return $this->vast_campaigns_has_videos_id;
}
public function setId($id)
{
$this->id = $id;
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function setType($type)
{
$this->type = $type;
}
public function setVast_campaigns_has_videos_id($vast_campaigns_has_videos_id)
{
$this->vast_campaigns_has_videos_id = $vast_campaigns_has_videos_id;
}
public function getIp()
{
return $this->ip;
}
public function save()
{
$this->ip = getRealIpAddr();
return parent::save();
}
public static function getViews()
{
global $global;
$sql = "SELECT count(*) as total FROM vast_campaigns_logs WHERE `type` = 'start'";
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row['total'];
}
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);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$data = [];
if ($res!=false) {
foreach ($fullData as $row) {
$data[$row['type']] = $row['total'];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $data;
}
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);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$data = [];
if ($res!=false) {
foreach ($fullData as $row) {
$data[$row['type']] = $row['total'];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $data;
}
}

View file

@ -1,210 +1,210 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
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
{
protected $id;
protected $vast_campaigns_id;
protected $videos_id;
protected $status;
protected $link;
protected $ad_title;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'vast_campaigns_has_videos';
}
public function loadFromCampainVideo($vast_campaigns_id, $videos_id)
{
$row = self::getCampainVideo($vast_campaigns_id, $videos_id);
if (empty($row)) {
return false;
}
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
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", [$vast_campaigns_id, $videos_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function getRandomCampainVideo($vast_campaigns_id)
{
global $global;
$vast_campaigns_id = intval($vast_campaigns_id);
if (empty($vast_campaigns_id)) {
$campaings = VastCampaigns::getValidCampaigns();
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", [$vast_campaigns_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
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)) {
$sql .= " AND vast_campaigns_id=$vast_campaigns_id ";
}
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res!=false) {
foreach ($fullData as $row) {
if ($getImages) {
$row['poster'] = Video::getImageFromID($row['videos_id']);
}
$row['data'] = VastCampaignsLogs::getDataFromCampaign($row['vast_campaigns_id']);
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
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' ";
$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;
}
public function getId()
{
return $this->id;
}
public function getVast_campaigns_id()
{
return $this->vast_campaigns_id;
}
public function getVideos_id()
{
return $this->videos_id;
}
public function getStatus()
{
return $this->status;
}
public function setId($id)
{
$this->id = $id;
}
public function setVast_campaigns_id($vast_campaigns_id)
{
$this->vast_campaigns_id = $vast_campaigns_id;
}
public function setVideos_id($videos_id)
{
$this->videos_id = $videos_id;
}
public function setStatus($status)
{
$this->status = $status;
}
public function getLink()
{
return $this->link;
}
public function getAd_title()
{
return $this->ad_title;
}
public function setLink($link)
{
$this->link = $link;
}
public function setAd_title($ad_title)
{
$this->ad_title = $ad_title;
}
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", [$this->id]);
}
return parent::delete();
}
public function save()
{
if (empty($this->vast_campaigns_id) || strtolower($this->vast_campaigns_id)=='null') {
return false;
}
return parent::save();
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
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
{
protected $id;
protected $vast_campaigns_id;
protected $videos_id;
protected $status;
protected $link;
protected $ad_title;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'vast_campaigns_has_videos';
}
public function loadFromCampainVideo($vast_campaigns_id, $videos_id)
{
$row = self::getCampainVideo($vast_campaigns_id, $videos_id);
if (empty($row)) {
return false;
}
foreach ($row as $key => $value) {
$this->$key = $value;
}
return true;
}
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", [$vast_campaigns_id, $videos_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function getRandomCampainVideo($vast_campaigns_id)
{
global $global;
$vast_campaigns_id = intval($vast_campaigns_id);
if (empty($vast_campaigns_id)) {
$campaings = VastCampaigns::getValidCampaigns();
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", [$vast_campaigns_id]);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
return $row;
}
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)) {
$sql .= " AND vast_campaigns_id=$vast_campaigns_id ";
}
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res!=false) {
foreach ($fullData as $row) {
if ($getImages) {
$row['poster'] = Video::getImageFromID($row['videos_id']);
}
$row['data'] = VastCampaignsLogs::getDataFromCampaign($row['vast_campaigns_id']);
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
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' ";
$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;
}
public function getId()
{
return $this->id;
}
public function getVast_campaigns_id()
{
return $this->vast_campaigns_id;
}
public function getVideos_id()
{
return $this->videos_id;
}
public function getStatus()
{
return $this->status;
}
public function setId($id)
{
$this->id = $id;
}
public function setVast_campaigns_id($vast_campaigns_id)
{
$this->vast_campaigns_id = $vast_campaigns_id;
}
public function setVideos_id($videos_id)
{
$this->videos_id = $videos_id;
}
public function setStatus($status)
{
$this->status = $status;
}
public function getLink()
{
return $this->link;
}
public function getAd_title()
{
return $this->ad_title;
}
public function setLink($link)
{
$this->link = $link;
}
public function setAd_title($ad_title)
{
$this->ad_title = $ad_title;
}
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", [$this->id]);
}
return parent::delete();
}
public function save()
{
if (empty($this->vast_campaigns_id) || strtolower($this->vast_campaigns_id)=='null') {
return false;
}
return parent::save();
}
}

View file

@ -1,92 +1,92 @@
<?php
header('Content-type: application/xml');
require_once '../../videos/configuration.php';
allowOrigin();
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'])) {
$video = VastCampaignsVideos::getRandomCampainVideo(intval(@$_GET['campaign_id']));
$_GET['campaign_has_videos_id'] = $video['id'];
}
$vastCampaingVideos = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
$video = new Video("", "", $vastCampaingVideos->getVideos_id());
?>
<?xml version="1.0" encoding="UTF-8"?>
<VAST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vast.xsd" version="3.0">
<Ad id="709684336">
<InLine>
<AdSystem>GDFP</AdSystem>
<AdTitle><?php echo $vastCampaingVideos->getAd_title(); ?></AdTitle>
<Description><![CDATA[<?php echo $vastCampaingVideos->getAd_title(); ?>]]></Description>
<Error><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=Error&[ERRORCODE]]]></Error>
<Impression><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=Impression&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Impression>
<Creatives>
<Creative id="57861016576" sequence="1">
<Linear skipoffset="<?php echo $obj->skipoffset->value; ?>">
<Duration><?php echo $video->getDuration(); ?></Duration>
<TrackingEvents>
<Tracking event="start"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=start&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="firstQuartile"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=firstQuartile&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="midpoint"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=midpoint&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="thirdQuartile"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=thirdQuartile&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="complete"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=complete&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="mute"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=mute&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="unmute"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=unmute&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="rewind"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=rewind&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="pause"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=pause&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="resume"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=resume&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="fullscreen"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=fullscreen&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="creativeView"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=creativeView&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="exitFullscreen"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=exitFullscreen&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="acceptInvitationLinear"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=acceptInvitationLinear&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="closeLinear"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=closeLinear&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
</TrackingEvents>
<?php
$campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
if (!empty($campaignVideo)) {
$link = $campaignVideo->getLink();
if (filter_var($link, FILTER_VALIDATE_URL)) {
?>
<VideoClicks>
<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 {
_error_log("VastCampaignsVideos has not a valid link: {$link}");
}
}
?>
<MediaFiles>
<?php
$adsCount = 0;
$files = getVideosURLMP4WEBMOnly($video->getFilename());
foreach ($files as $key => $value) {
$adsCount++;
echo "\n " . '<MediaFile id="GDFP" delivery="progressive" type="video/mp4" scalable="true" maintainAspectRatio="true"><![CDATA[' . ($value['url']) . ']]></MediaFile>';
}
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>';
}
?>
</MediaFiles>
</Linear>
</Creative>
<Creative id="<?php echo $_GET['campaign_has_videos_id']; ?>" sequence="1">
<CompanionAds>
<Companion id="<?php echo $_GET['campaign_has_videos_id']; ?>" width="300" height="250">
<StaticResource creativeType="image/png"><![CDATA[<?php echo getCDN(); ?>view/img/logo.png]]></StaticResource>
<TrackingEvents>
<Tracking event="creativeView"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=creativeView&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
</TrackingEvents>
<CompanionClickThrough><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=CompanionClickThrough&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></CompanionClickThrough>
</Companion>
</CompanionAds>
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>
<?php
header('Content-type: application/xml');
require_once '../../videos/configuration.php';
allowOrigin();
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'])) {
$video = VastCampaignsVideos::getRandomCampainVideo(intval(@$_GET['campaign_id']));
$_GET['campaign_has_videos_id'] = $video['id'];
}
$vastCampaingVideos = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
$video = new Video("", "", $vastCampaingVideos->getVideos_id());
?>
<?xml version="1.0" encoding="UTF-8"?>
<VAST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vast.xsd" version="3.0">
<Ad id="709684336">
<InLine>
<AdSystem>GDFP</AdSystem>
<AdTitle><?php echo $vastCampaingVideos->getAd_title(); ?></AdTitle>
<Description><![CDATA[<?php echo $vastCampaingVideos->getAd_title(); ?>]]></Description>
<Error><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=Error&[ERRORCODE]]]></Error>
<Impression><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=Impression&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Impression>
<Creatives>
<Creative id="57861016576" sequence="1">
<Linear skipoffset="<?php echo $obj->skipoffset->value; ?>">
<Duration><?php echo $video->getDuration(); ?></Duration>
<TrackingEvents>
<Tracking event="start"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=start&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="firstQuartile"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=firstQuartile&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="midpoint"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=midpoint&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="thirdQuartile"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=thirdQuartile&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="complete"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=complete&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="mute"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=mute&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="unmute"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=unmute&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="rewind"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=rewind&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="pause"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=pause&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="resume"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=resume&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="fullscreen"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=fullscreen&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="creativeView"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=creativeView&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="exitFullscreen"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=exitFullscreen&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="acceptInvitationLinear"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=acceptInvitationLinear&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
<Tracking event="closeLinear"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=closeLinear&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
</TrackingEvents>
<?php
$campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
if (!empty($campaignVideo)) {
$link = $campaignVideo->getLink();
if (filter_var($link, FILTER_VALIDATE_URL)) {
?>
<VideoClicks>
<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 {
_error_log("VastCampaignsVideos has not a valid link: {$link}");
}
}
?>
<MediaFiles>
<?php
$adsCount = 0;
$files = getVideosURLMP4WEBMOnly($video->getFilename());
foreach ($files as $key => $value) {
$adsCount++;
echo "\n " . '<MediaFile id="GDFP" delivery="progressive" type="video/mp4" scalable="true" maintainAspectRatio="true"><![CDATA[' . ($value['url']) . ']]></MediaFile>';
}
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>';
}
?>
</MediaFiles>
</Linear>
</Creative>
<Creative id="<?php echo $_GET['campaign_has_videos_id']; ?>" sequence="1">
<CompanionAds>
<Companion id="<?php echo $_GET['campaign_has_videos_id']; ?>" width="300" height="250">
<StaticResource creativeType="image/png"><![CDATA[<?php echo getCDN(); ?>view/img/logo.png]]></StaticResource>
<TrackingEvents>
<Tracking event="creativeView"><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=creativeView&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></Tracking>
</TrackingEvents>
<CompanionClickThrough><![CDATA[<?php echo $global['webSiteRootURL']; ?>plugin/AD_Server/log.php?label=CompanionClickThrough&ad_mt=[AD_MT]&campaign_has_videos_id=<?php echo $_GET['campaign_has_videos_id']; ?>]]></CompanionClickThrough>
</Companion>
</CompanionAds>
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>

View file

@ -1,35 +1,35 @@
<?php
header('Content-type: application/xml');
require_once '../../videos/configuration.php';
allowOrigin();
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (empty($ad_server)) {
die("not enabled");
}
if (empty($_GET['video_length'])) {
$_GET['video_length'] = 300;
}
if (empty($_GET['vmap_id'])) {
$_GET['vmap_id'] = uniqid();
}
$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'])) {
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>
</vmap:AdSource>
</vmap:AdBreak>
<?php
}
?>
</vmap:VMAP>
<?php
header('Content-type: application/xml');
require_once '../../videos/configuration.php';
allowOrigin();
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (empty($ad_server)) {
die("not enabled");
}
if (empty($_GET['video_length'])) {
$_GET['video_length'] = 300;
}
if (empty($_GET['vmap_id'])) {
$_GET['vmap_id'] = uniqid();
}
$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'])) {
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>
</vmap:AdSource>
</vmap:AdBreak>
<?php
}
?>
</vmap:VMAP>

View file

@ -1,19 +1,19 @@
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
allowOrigin();
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$obj->views = 0;
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (empty($ad_server)) {
$obj->msg = "not enabled";
die(json_encode($obj));
}
$obj->error = false;
$obj->views = VastCampaignsLogs::getViews();
echo json_encode($obj);
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
allowOrigin();
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$obj->views = 0;
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (empty($ad_server)) {
$obj->msg = "not enabled";
die(json_encode($obj));
}
$obj->error = false;
$obj->views = VastCampaignsLogs::getViews();
echo json_encode($obj);

View file

@ -1,30 +1,30 @@
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("VAST"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
include $global['systemRootPath'] . 'plugin/AD_Server/index_head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
include $global['systemRootPath'] . 'plugin/AD_Server/index_body.php';
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("VAST"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
include $global['systemRootPath'] . 'plugin/AD_Server/index_head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
include $global['systemRootPath'] . 'plugin/AD_Server/index_body.php';
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -1,16 +1,16 @@
<?php
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
?>
<link rel="stylesheet" type="text/css" href="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.css"/>
<link href="<?php echo getCDN(); ?>view/js/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css"/>
<style>
#campaignVideosTable td img {
height: 50px;
margin: 5px;
}
.ui-autocomplete{
z-index: 9999999;
}
<?php
$plugin = AVideoPlugin::loadPluginIfEnabled('AD_Server');
$ad_server_location = AVideoPlugin::loadPluginIfEnabled('AD_Server_Location');
?>
<link rel="stylesheet" type="text/css" href="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.css"/>
<link href="<?php echo getCDN(); ?>view/js/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css"/>
<style>
#campaignVideosTable td img {
height: 50px;
margin: 5px;
}
.ui-autocomplete{
z-index: 9999999;
}
</style>

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);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1,59 +1,59 @@
.vjs-marker {
position: absolute;
left: 0;
bottom: 0em;
opacity: 1;
height: 100%;
transition: opacity .2s ease;
-webkit-transition: opacity .2s ease;
-moz-transition: opacity .2s ease;
z-index: 100;
}
.vjs-marker:hover {
cursor: pointer;
-webkit-transform: scale(1.3, 1.3);
-moz-transform: scale(1.3, 1.3);
-o-transform: scale(1.3, 1.3);
-ms-transform: scale(1.3, 1.3);
transform: scale(1.3, 1.3);
}
.vjs-tip {
visibility: hidden;
display: block;
opacity: 0.8;
padding: 5px;
font-size: 10px;
position: absolute;
bottom: 14px;
z-index: 100000;
}
.vjs-tip .vjs-tip-arrow {
background: url(data:image/gif;base64,R0lGODlhCQAJAIABAAAAAAAAACH5BAEAAAEALAAAAAAJAAkAAAIRjAOnwIrcDJxvwkplPtchVQAAOw==) no-repeat top left;
bottom: 0;
left: 50%;
margin-left: -4px;
background-position: bottom left;
position: absolute;
width: 9px;
height: 5px;
}
.vjs-tip .vjs-tip-inner {
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
padding: 5px 8px 4px 8px;
background-color: black;
color: white;
max-width: 200px;
text-align: center;
}
.vjs-break-overlay {
visibility: hidden;
position: absolute;
z-index: 100000;
top: 0;
}
.vjs-break-overlay .vjs-break-overlay-text {
padding: 9px;
text-align: center;
}
.vjs-marker {
position: absolute;
left: 0;
bottom: 0em;
opacity: 1;
height: 100%;
transition: opacity .2s ease;
-webkit-transition: opacity .2s ease;
-moz-transition: opacity .2s ease;
z-index: 100;
}
.vjs-marker:hover {
cursor: pointer;
-webkit-transform: scale(1.3, 1.3);
-moz-transform: scale(1.3, 1.3);
-o-transform: scale(1.3, 1.3);
-ms-transform: scale(1.3, 1.3);
transform: scale(1.3, 1.3);
}
.vjs-tip {
visibility: hidden;
display: block;
opacity: 0.8;
padding: 5px;
font-size: 10px;
position: absolute;
bottom: 14px;
z-index: 100000;
}
.vjs-tip .vjs-tip-arrow {
background: url(data:image/gif;base64,R0lGODlhCQAJAIABAAAAAAAAACH5BAEAAAEALAAAAAAJAAkAAAIRjAOnwIrcDJxvwkplPtchVQAAOw==) no-repeat top left;
bottom: 0;
left: 50%;
margin-left: -4px;
background-position: bottom left;
position: absolute;
width: 9px;
height: 5px;
}
.vjs-tip .vjs-tip-inner {
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
padding: 5px 8px 4px 8px;
background-color: black;
color: white;
max-width: 200px;
text-align: center;
}
.vjs-break-overlay {
visibility: hidden;
position: absolute;
z-index: 100000;
top: 0;
}
.vjs-break-overlay .vjs-break-overlay-text {
padding: 9px;
text-align: center;
}

View file

@ -1,42 +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,30 +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,23 +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

@ -1,81 +1,81 @@
<?php
/**
* https://support.google.com/adsense/answer/4455881
* https://support.google.com/adsense/answer/1705822
* AdSense for video: Publisher Approval Form
* https://services.google.com/fb/forms/afvapproval/
*/
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server_Location/Objects/CampaignLocations.php';
require_once $global['systemRootPath'] . 'plugin/User_Location/Objects/IP2Location.php';
class AD_Server_Location extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$MONETIZATION,
PluginTags::$ADS,
PluginTags::$FREE
);
}
public function getDescription() {
$desc = "Enable select location to display each ad<br>";
$desc .= $this->isReadyLabel(array('AD_Server'));
return $desc;
}
public function getName() {
return "AD_Server_Location";
}
public function getUUID() {
return "77771553-61a2-4189-b033-27a6bb17173d";
}
public function getPluginVersion() {
return "1.0";
}
public function getEmptyDataObject() {
$obj = new stdClass();
return $obj;
}
public function getCampaignPanel(){
global $global;
include $global['systemRootPath'] . 'plugin/AD_Server_Location/campaignPanel.php';
}
public function addCampaignLocation($country_name, $region_name, $city_name, $vast_campaigns_id){
if(!is_array($country_name)){
$country_name = array($country_name);
}
if(!is_array($region_name)){
$region_name = array($region_name);
}
if(!is_array($city_name)){
$city_name = array($city_name);
}
foreach ($country_name as $key => $value) {
$cl = new CampaignLocations(0);
$cl->setCountry_name($country_name[$key]);
$cl->setRegion_name($region_name[$key]);
$cl->setCity_name($city_name[$key]);
$cl->setVast_campaigns_id($vast_campaigns_id);
$cl->save();
}
}
public function getCampaignLocations($vast_campaigns_id){
$cl = new CampaignLocations(0);
$cl->setVast_campaigns_id($vast_campaigns_id);
return $cl->getCampaignLocations();
}
}
<?php
/**
* https://support.google.com/adsense/answer/4455881
* https://support.google.com/adsense/answer/1705822
* AdSense for video: Publisher Approval Form
* https://services.google.com/fb/forms/afvapproval/
*/
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server_Location/Objects/CampaignLocations.php';
require_once $global['systemRootPath'] . 'plugin/User_Location/Objects/IP2Location.php';
class AD_Server_Location extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$MONETIZATION,
PluginTags::$ADS,
PluginTags::$FREE
);
}
public function getDescription() {
$desc = "Enable select location to display each ad<br>";
$desc .= $this->isReadyLabel(array('AD_Server'));
return $desc;
}
public function getName() {
return "AD_Server_Location";
}
public function getUUID() {
return "77771553-61a2-4189-b033-27a6bb17173d";
}
public function getPluginVersion() {
return "1.0";
}
public function getEmptyDataObject() {
$obj = new stdClass();
return $obj;
}
public function getCampaignPanel(){
global $global;
include $global['systemRootPath'] . 'plugin/AD_Server_Location/campaignPanel.php';
}
public function addCampaignLocation($country_name, $region_name, $city_name, $vast_campaigns_id){
if(!is_array($country_name)){
$country_name = array($country_name);
}
if(!is_array($region_name)){
$region_name = array($region_name);
}
if(!is_array($city_name)){
$city_name = array($city_name);
}
foreach ($country_name as $key => $value) {
$cl = new CampaignLocations(0);
$cl->setCountry_name($country_name[$key]);
$cl->setRegion_name($region_name[$key]);
$cl->setCity_name($city_name[$key]);
$cl->setVast_campaigns_id($vast_campaigns_id);
$cl->save();
}
}
public function getCampaignLocations($vast_campaigns_id){
$cl = new CampaignLocations(0);
$cl->setVast_campaigns_id($vast_campaigns_id);
return $cl->getCampaignLocations();
}
}

View file

@ -1,84 +1,84 @@
<?php
$countries = IP2Location::getCountries();
?>
<div class="form-group col-sm-4">
<label for="status"><?php echo __("Country"); ?>:</label>
<select class="form-control input-sm" name="country" id="country">
<option>All</option>
<?php
foreach ($countries as $key => $value) {
echo '<option>' . $value . '</option>';
}
?>
</select>
</div>
<div class="form-group col-sm-4">
<label for="status"><?php echo __("Region"); ?>:</label>
<select class="form-control input-sm" name="region" id="region">
<option>All</option>
</select>
</div>
<div class="form-group col-sm-4">
<label for="status"><?php echo __("City"); ?>:</label>
<select class="form-control input-sm" name="city" id="city">
<option>All</option>
</select>
</div>
<div class="form-group col-sm-12">
<div class="btn btn-success btn-block" id="addLocation"><i class="fa fa-plus"></i> <?php echo __("Add Location Restriction"); ?></div>
</div>
<div class="form-group col-sm-12">
<ul class="list-group" id="locationList">
</ul>
</div>
<script type="text/javascript">
function addLocation(country_name, region_name, city_name){
$('#locationList').append('<li class="list-group-item">'+country_name+' - '+region_name+' - '+city_name+' <span class="btn btn-danger btn-xs btn-sm pull-right" onclick="$(this).parent().remove();"><i class="fa fa-trash"></i></span><input type="hidden" name="country_name[]" value="'+country_name+'"><input type="hidden" name="region_name[]" value="'+region_name+'"><input type="hidden" name="city_name[]" value="'+city_name+'"></li>');
}
$(document).ready(function () {
$("#addLocation").on("click", function (e) {
var country_name = $('#country').val();
var region_name = $('#region').val();
var city_name = $('#city').val();
addLocation(country_name, region_name, city_name);
});
$("#country").on("change", function (e) {
modal.showPleaseWait();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/User_Location/regions.json.php?country=' + $('#country').val(),
success: function (response) {
$('#region').empty();
$('#region').append($("<option></option>").text('All'));
$('#city').empty();
$('#city').append($("<option></option>").text('All'));
$.each(response, function (key, value) {
$('#region').append($("<option></option>").attr("value", value).text(value));
});
modal.hidePleaseWait();
}
});
});
$("#region").on("change", function (e) {
modal.showPleaseWait();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/User_Location/cities.json.php?country=' + $('#country').val() + '&region=' + $('#region').val(),
success: function (response) {
$('#city').empty();
$('#city').append($("<option></option>").text('All'));
$.each(response, function (key, value) {
$('#city').append($("<option></option>").attr("value", value).text(value));
});
modal.hidePleaseWait();
}
});
});
});
<?php
$countries = IP2Location::getCountries();
?>
<div class="form-group col-sm-4">
<label for="status"><?php echo __("Country"); ?>:</label>
<select class="form-control input-sm" name="country" id="country">
<option>All</option>
<?php
foreach ($countries as $key => $value) {
echo '<option>' . $value . '</option>';
}
?>
</select>
</div>
<div class="form-group col-sm-4">
<label for="status"><?php echo __("Region"); ?>:</label>
<select class="form-control input-sm" name="region" id="region">
<option>All</option>
</select>
</div>
<div class="form-group col-sm-4">
<label for="status"><?php echo __("City"); ?>:</label>
<select class="form-control input-sm" name="city" id="city">
<option>All</option>
</select>
</div>
<div class="form-group col-sm-12">
<div class="btn btn-success btn-block" id="addLocation"><i class="fa fa-plus"></i> <?php echo __("Add Location Restriction"); ?></div>
</div>
<div class="form-group col-sm-12">
<ul class="list-group" id="locationList">
</ul>
</div>
<script type="text/javascript">
function addLocation(country_name, region_name, city_name){
$('#locationList').append('<li class="list-group-item">'+country_name+' - '+region_name+' - '+city_name+' <span class="btn btn-danger btn-xs btn-sm pull-right" onclick="$(this).parent().remove();"><i class="fa fa-trash"></i></span><input type="hidden" name="country_name[]" value="'+country_name+'"><input type="hidden" name="region_name[]" value="'+region_name+'"><input type="hidden" name="city_name[]" value="'+city_name+'"></li>');
}
$(document).ready(function () {
$("#addLocation").on("click", function (e) {
var country_name = $('#country').val();
var region_name = $('#region').val();
var city_name = $('#city').val();
addLocation(country_name, region_name, city_name);
});
$("#country").on("change", function (e) {
modal.showPleaseWait();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/User_Location/regions.json.php?country=' + $('#country').val(),
success: function (response) {
$('#region').empty();
$('#region').append($("<option></option>").text('All'));
$('#city').empty();
$('#city').append($("<option></option>").text('All'));
$.each(response, function (key, value) {
$('#region').append($("<option></option>").attr("value", value).text(value));
});
modal.hidePleaseWait();
}
});
});
$("#region").on("change", function (e) {
modal.showPleaseWait();
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/User_Location/cities.json.php?country=' + $('#country').val() + '&region=' + $('#region').val(),
success: function (response) {
$('#city').empty();
$('#city').append($("<option></option>").text('All'));
$.each(response, function (key, value) {
$('#city').append($("<option></option>").attr("value", value).text(value));
});
modal.hidePleaseWait();
}
});
});
});
</script>

View file

@ -1,64 +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));

File diff suppressed because it is too large Load diff

View file

@ -1,35 +1,35 @@
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
[$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');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Content-Type");
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
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 = [];
} else {
$input = object_to_array($input);
}
$parameters = array_merge($_GET, $_POST, $input);
$obj = $plugin->get($parameters);
die(json_encode($obj));
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
[$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');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Content-Type");
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
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 = [];
} else {
$input = object_to_array($input);
}
$parameters = array_merge($_GET, $_POST, $input);
$obj = $plugin->get($parameters);
die(json_encode($obj));

View file

@ -1,112 +1,112 @@
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
if (empty($plugin)) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
$obj = AVideoPlugin::getObjectData("API");
$reflector = new ReflectionClass('API');
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("API"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<style>
pre a{
color: #333;
font-weight: bolder;
}
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
$class_methods = get_class_methods('API');
foreach ($class_methods as $key => $method_name) {
if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) {
unset($class_methods[$key]);
}
}
usort($class_methods, function ($a, $b) {
if (!preg_match("/(get|set)_api_(.*)/", $a, $matchesA)) {
return 0;
}
if (!preg_match("/(get|set)_api_(.*)/", $b, $matchesB)) {
return 0;
}
return strcasecmp($matchesA[2], $matchesB[2]);
});
?>
<div class="container-fluid">
<ul class="list-group">
<li class="list-group-item">
<details>
<summary style="cursor: pointer;"><i class="fas fa-file-upload"></i> Upload a Video</summary>
<br>
For more detailed instructions please <a href="https://github.com/WWBN/AVideo/wiki/Upload-videos-from-third-party-applications" target="_blank" rel="noopener noreferrer" >read this</a>
<br>
Your HTML Form should looks like this. The user and the pass values on the action URL will be the video owner
<pre><?php
$frm = '<form enctype="multipart/form-data" method="post" action="' . $global['webSiteRootURL'] . 'plugin/MobileManager/upload.php?user=' . urlencode(User::getUserName()) . '&pass=' . User::getUserPass() . '">
<input name="title" type="text" /><br>
<textarea name="description"></textarea><br>
<input name="categories_id" type="hidden" value="1" />
<input name="upl" type="file" accept="video/mp4" /><br>
<input type="submit" value="submit" id="submit"/>
</form>';
echo htmlentities($frm);
?>
</pre>
You can Click to get notified for the new video uploads with the Webhook in the Notification plugin, Check <a href="https://github.com/WWBN/AVideo/wiki/Notifications-Plugin#webhooks" target="_blank" rel="noopener noreferrer">here</a> for more details
</details>
</li>
<?php
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(['{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}
?>
</pre>
</details>
</li>
<?php
}
?>
</ul>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
require_once $global['systemRootPath'] . 'plugin/API/API.php';
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
if (empty($plugin)) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
$obj = AVideoPlugin::getObjectData("API");
$reflector = new ReflectionClass('API');
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("API"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<style>
pre a{
color: #333;
font-weight: bolder;
}
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
$class_methods = get_class_methods('API');
foreach ($class_methods as $key => $method_name) {
if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) {
unset($class_methods[$key]);
}
}
usort($class_methods, function ($a, $b) {
if (!preg_match("/(get|set)_api_(.*)/", $a, $matchesA)) {
return 0;
}
if (!preg_match("/(get|set)_api_(.*)/", $b, $matchesB)) {
return 0;
}
return strcasecmp($matchesA[2], $matchesB[2]);
});
?>
<div class="container-fluid">
<ul class="list-group">
<li class="list-group-item">
<details>
<summary style="cursor: pointer;"><i class="fas fa-file-upload"></i> Upload a Video</summary>
<br>
For more detailed instructions please <a href="https://github.com/WWBN/AVideo/wiki/Upload-videos-from-third-party-applications" target="_blank" rel="noopener noreferrer" >read this</a>
<br>
Your HTML Form should looks like this. The user and the pass values on the action URL will be the video owner
<pre><?php
$frm = '<form enctype="multipart/form-data" method="post" action="' . $global['webSiteRootURL'] . 'plugin/MobileManager/upload.php?user=' . urlencode(User::getUserName()) . '&pass=' . User::getUserPass() . '">
<input name="title" type="text" /><br>
<textarea name="description"></textarea><br>
<input name="categories_id" type="hidden" value="1" />
<input name="upl" type="file" accept="video/mp4" /><br>
<input type="submit" value="submit" id="submit"/>
</form>';
echo htmlentities($frm);
?>
</pre>
You can Click to get notified for the new video uploads with the Webhook in the Notification plugin, Check <a href="https://github.com/WWBN/AVideo/wiki/Notifications-Plugin#webhooks" target="_blank" rel="noopener noreferrer">here</a> for more details
</details>
</li>
<?php
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(['{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}
?>
</pre>
</details>
</li>
<?php
}
?>
</ul>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>

View file

@ -1,35 +1,35 @@
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
[$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');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Content-Type");
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
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 = [];
} else {
$input = object_to_array($input);
}
$parameters = array_merge($_GET, $_POST, $input);
$obj = $plugin->set($parameters);
die(json_encode($obj));
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
[$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');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Content-Type");
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
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 = [];
} else {
$input = object_to_array($input);
}
$parameters = array_merge($_GET, $_POST, $input);
$obj = $plugin->set($parameters);
die(json_encode($obj));

View file

@ -1,23 +1,23 @@
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
[$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');
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
if (empty($plugin)) {
$obj = new ApiObject("API Plugin disabled");
} else {
$obj = new ApiObject("API Plugin enabled", false);
}
die(json_encode($obj));
<?php
$configFile = '../../videos/configuration.php';
if (!file_exists($configFile)) {
[$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');
$plugin = AVideoPlugin::loadPluginIfEnabled("API");
$objData = AVideoPlugin::getObjectDataIfEnabled("API");
if (empty($plugin)) {
$obj = new ApiObject("API Plugin disabled");
} else {
$obj = new ApiObject("API Plugin enabled", false);
}
die(json_encode($obj));

View file

@ -1,116 +1,116 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class AdsForJesus extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$ADS,
PluginTags::$FREE,
PluginTags::$PLAYER,
);
}
public function getDescription() {
$txt = " We will provide a simple VMAP Ad link for free, these ads will be placed in your videos.<br>"
. "This will give your users the greatest wisdom of all, as well as invaluable value. <i class=\"fas fa-pray\"> </i> <i class=\"fas fa-cross fa-2x \"></i>";
return $txt;
}
public function getName() {
return "AdsForJesus";
}
public function getUUID() {
return "AdsForJesus-43a9-479b-994a-5430dc22958c";
}
public function getPluginMenu() {
global $global;
return "<a href='https://forjesus.tv/' target='__blank' class='btn btn-success'><img src='https://forjesus.tv/img/logoLandscape-50.png' alt='4JesusTV' class='img img-responsive'></a>";
}
public function getEmptyDataObject() {
$obj = new stdClass();
$obj->start = true;
$obj->mid25Percent = true;
$obj->mid50Percent = true;
$obj->mid75Percent = true;
$obj->end = true;
$obj->topMenuLink = false;
return $obj;
}
public function getHTMLMenuRight() {
global $global;
$obj = $this->getDataObject();
if (empty($obj->topMenuLink)) {
return '';
}
return '<li>
<a href="https://forjesus.tv/" class="btn btn-success navbar-btn" data-toggle="tooltip" title="For jesus TV" data-placement="bottom" >
<i class="fas fa-cross"></i> <span class="hidden-md hidden-sm hidden-mdx">ForJesus.TV Site</span>
</a>
</li>';
}
public function getHeadCode() {
$js = '';
$css = '';
//if (!empty($_GET['videoName']) || !empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
return "<!-- AdsForJesus::getHeadCode not show ads [{$videos_id}] -->";
}
global $global;
$css .= '<link href="' .getURL('node_modules/videojs-ima/dist/videojs.ima.css') .' " rel="stylesheet" type="text/css"/>';
$css .= '<style>.ima-ad-container{z-index:1000 !important;}</style>';
}else{
$css .= "<!-- AdsForJesus::getHeadCode empty videos_id -->";
}
return $js . $css;
}
public function afterVideoJS() {
global $global;
$js = '';
$js .= '<script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-contrib-ads/dist/videojs.ads.min.js') . '" type="text/javascript"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-ima/dist/videojs.ima.min.js') . '" type="text/javascript"></script>';
//if (!empty($_GET['videoName']) || !empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
return "<!-- AdsForJesus::afterVideoJS not show ads [{$videos_id}] -->";
}
if (empty($_GET['u'])) {
$video = Video::getVideoLight($videos_id);
$showAds = AVideoPlugin::showAds($video['id']);
if (!$showAds) {
return "";
}
} else {
$video['duration'] = "01:00:00";
$_GET['videoName'] = "Live-" . uniqid();
}
$video_length = parseDurationToSeconds($video['duration']);
$obj = $this->getDataObject();
PlayerSkins::setIMAADTag("https://forjesus.tv/vmap.xml?video_durarion={$video_length}&start={$obj->start}&mid25Percent={$obj->mid25Percent}&mid50Percent={$obj->mid50Percent}&mid75Percent={$obj->mid75Percent}&end={$obj->end}");
}else{
$js .= "<!-- AdsForJesus::getHeadCode empty videos_id -->";
}
return $js;
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class AdsForJesus extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$ADS,
PluginTags::$FREE,
PluginTags::$PLAYER,
);
}
public function getDescription() {
$txt = " We will provide a simple VMAP Ad link for free, these ads will be placed in your videos.<br>"
. "This will give your users the greatest wisdom of all, as well as invaluable value. <i class=\"fas fa-pray\"> </i> <i class=\"fas fa-cross fa-2x \"></i>";
return $txt;
}
public function getName() {
return "AdsForJesus";
}
public function getUUID() {
return "AdsForJesus-43a9-479b-994a-5430dc22958c";
}
public function getPluginMenu() {
global $global;
return "<a href='https://forjesus.tv/' target='__blank' class='btn btn-success'><img src='https://forjesus.tv/img/logoLandscape-50.png' alt='4JesusTV' class='img img-responsive'></a>";
}
public function getEmptyDataObject() {
$obj = new stdClass();
$obj->start = true;
$obj->mid25Percent = true;
$obj->mid50Percent = true;
$obj->mid75Percent = true;
$obj->end = true;
$obj->topMenuLink = false;
return $obj;
}
public function getHTMLMenuRight() {
global $global;
$obj = $this->getDataObject();
if (empty($obj->topMenuLink)) {
return '';
}
return '<li>
<a href="https://forjesus.tv/" class="btn btn-success navbar-btn" data-toggle="tooltip" title="For jesus TV" data-placement="bottom" >
<i class="fas fa-cross"></i> <span class="hidden-md hidden-sm hidden-mdx">ForJesus.TV Site</span>
</a>
</li>';
}
public function getHeadCode() {
$js = '';
$css = '';
//if (!empty($_GET['videoName']) || !empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
return "<!-- AdsForJesus::getHeadCode not show ads [{$videos_id}] -->";
}
global $global;
$css .= '<link href="' .getURL('node_modules/videojs-ima/dist/videojs.ima.css') .' " rel="stylesheet" type="text/css"/>';
$css .= '<style>.ima-ad-container{z-index:1000 !important;}</style>';
}else{
$css .= "<!-- AdsForJesus::getHeadCode empty videos_id -->";
}
return $js . $css;
}
public function afterVideoJS() {
global $global;
$js = '';
$js .= '<script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-contrib-ads/dist/videojs.ads.min.js') . '" type="text/javascript"></script>';
$js .= '<script src="' . getURL('node_modules/videojs-ima/dist/videojs.ima.min.js') . '" type="text/javascript"></script>';
//if (!empty($_GET['videoName']) || !empty($_GET['u'])) {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$showAds = AVideoPlugin::showAds($videos_id);
if (!$showAds) {
return "<!-- AdsForJesus::afterVideoJS not show ads [{$videos_id}] -->";
}
if (empty($_GET['u'])) {
$video = Video::getVideoLight($videos_id);
$showAds = AVideoPlugin::showAds($video['id']);
if (!$showAds) {
return "";
}
} else {
$video['duration'] = "01:00:00";
$_GET['videoName'] = "Live-" . uniqid();
}
$video_length = parseDurationToSeconds($video['duration']);
$obj = $this->getDataObject();
PlayerSkins::setIMAADTag("https://forjesus.tv/vmap.xml?video_durarion={$video_length}&start={$obj->start}&mid25Percent={$obj->mid25Percent}&mid50Percent={$obj->mid50Percent}&mid75Percent={$obj->mid75Percent}&end={$obj->end}");
}else{
$js .= "<!-- AdsForJesus::getHeadCode empty videos_id -->";
}
return $js;
}
}

View file

@ -1,47 +1,47 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class Articles extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$FREE
);
}
public function getDescription() {
global $global;
$str = "Create rich text articles";
$alert = "";
$dir = $global['systemRootPath'] . 'vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer';
if (!is_writable($dir)) {
$alert = "<div class='alert alert-danger'>Your directory must be writable<br><code>sudo chmod 777 {$dir}</code></div>";
}
return $str.$alert;
}
public function getName() {
return "Articles";
}
public function getUUID() {
return "articles-91db-4357-bb10-ee08b0913778";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->allowAttributes = false;
$obj->allowCSS = false;
return $obj;
}
public function getPluginMenu() {
global $global;
$btn = '<a href="' . $global['webSiteRootURL'] . 'plugin/Articles/updateDescriptions.php" class="btn btn-default btn-xs btn-block" target="_blank">'.__('Update Old Descriptions').'</a>';
$btn .= '<a href="' . $global['webSiteRootURL'] . 'plugin/Articles/updateDescriptionsRemoveTags.php" class="btn btn-default btn-xs btn-block" target="_blank">'.__('Revert Descriptions to NON-HTML').'</a>';
return $btn;
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class Articles extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$FREE
);
}
public function getDescription() {
global $global;
$str = "Create rich text articles";
$alert = "";
$dir = $global['systemRootPath'] . 'vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer';
if (!is_writable($dir)) {
$alert = "<div class='alert alert-danger'>Your directory must be writable<br><code>sudo chmod 777 {$dir}</code></div>";
}
return $str.$alert;
}
public function getName() {
return "Articles";
}
public function getUUID() {
return "articles-91db-4357-bb10-ee08b0913778";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->allowAttributes = false;
$obj->allowCSS = false;
return $obj;
}
public function getPluginMenu() {
global $global;
$btn = '<a href="' . $global['webSiteRootURL'] . 'plugin/Articles/updateDescriptions.php" class="btn btn-default btn-xs btn-block" target="_blank">'.__('Update Old Descriptions').'</a>';
$btn .= '<a href="' . $global['webSiteRootURL'] . 'plugin/Articles/updateDescriptionsRemoveTags.php" class="btn btn-default btn-xs btn-block" target="_blank">'.__('Revert Descriptions to NON-HTML').'</a>';
return $btn;
}
}

View file

@ -1,25 +1,25 @@
<?php
require_once '../../videos/configuration.php';
if(!User::isAdmin()){
die("Must be admin");
}
$videos = Video::getAllVideosLight("", false, true);
foreach ($videos as $value) {
$newDescription = strip_tags($value['description']);
$value['description'] = trim($value['description']);
if(empty($value['description'])){
continue;
}
if(strip_tags($value['description']) === $value['description']){
$video = new Video("", "", $value['id']);
$video->setDescription(nl2br(textToLink($value['description'])));
$video->save();
echo "{$value['title']}<br>";
}
}
<?php
require_once '../../videos/configuration.php';
if(!User::isAdmin()){
die("Must be admin");
}
$videos = Video::getAllVideosLight("", false, true);
foreach ($videos as $value) {
$newDescription = strip_tags($value['description']);
$value['description'] = trim($value['description']);
if(empty($value['description'])){
continue;
}
if(strip_tags($value['description']) === $value['description']){
$video = new Video("", "", $value['id']);
$video->setDescription(nl2br(textToLink($value['description'])));
$video->save();
echo "{$value['title']}<br>";
}
}

View file

@ -1,35 +1,35 @@
<?php
require_once '../../videos/configuration.php';
if(!User::isAdmin()){
die("Must be admin");
}
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
$videos = Video::getAllVideosLight("", false, true);
foreach ($videos as $value) {
$value['description'] = trim($value['description']);
if(empty($value['description'])){
continue;
}
$newDescription = strip_tags($value['description'], "<br><p>");
if($newDescription==$value['description']){
continue;
}
$newDescription = br2nl($newDescription);
if($newDescription==$value['description']){
continue;
}
if(empty($newDescription)){
continue;
}
$video = new Video("", "", $value['id']);
$video->setDescription($newDescription);
$video->save();
echo "{$value['title']}<br>";
}
<?php
require_once '../../videos/configuration.php';
if(!User::isAdmin()){
die("Must be admin");
}
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
$videos = Video::getAllVideosLight("", false, true);
foreach ($videos as $value) {
$value['description'] = trim($value['description']);
if(empty($value['description'])){
continue;
}
$newDescription = strip_tags($value['description'], "<br><p>");
if($newDescription==$value['description']){
continue;
}
$newDescription = br2nl($newDescription);
if($newDescription==$value['description']){
continue;
}
if(empty($newDescription)){
continue;
}
$video = new Video("", "", $value['id']);
$video->setDescription($newDescription);
$video->save();
echo "{$value['title']}<br>";
}

View file

@ -1,71 +1,71 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/Audit/Objects/AuditTable.php';
class Audit extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$RECOMMENDED,
PluginTags::$FREE,
PluginTags::$SECURITY
);
}
public function getDescription() {
return "Save all insert, update and delete queries for audit";
}
public function getName() {
return "Audit";
}
public function getUUID() {
return "26570956-dc62-46e3-ace9-86c6e8f9c81b";
}
public function getPluginVersion() {
return "2.0";
}
public function getEmptyDataObject() {
$obj = new stdClass();
$obj->autoDeleteAuditOlderThanDays = 60;
}
public function getPluginMenu() {
global $global;
$filename = $global['systemRootPath'] . 'plugin/Audit/pluginMenu.html';
return file_get_contents($filename);
}
function exec($method, $class, $statement, $formats, $values, $users_id) {
$audit = new AuditTable(0);
return $audit->audit($method, $class, $statement, $formats, $values, $users_id);
}
public function updateScript() {
global $global;
//update version 2.0
if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) {
sqlDal::executeFile($global['systemRootPath'] . 'plugin/Audit/install/updateV2.0.sql');
}
return true;
}
public function getEnd() {
_session_start();
if(User::isAdmin() && empty($_SESSION['auditDelete'])){
$obj = $this->getDataObject();
if(!empty($obj->autoDeleteAuditOlderThanDays)){
AuditTable::deleteOlderThan($obj->autoDeleteAuditOlderThanDays);
$_SESSION['auditDelete'] = 1;
return true;
}
}
return false;
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/Audit/Objects/AuditTable.php';
class Audit extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$RECOMMENDED,
PluginTags::$FREE,
PluginTags::$SECURITY
);
}
public function getDescription() {
return "Save all insert, update and delete queries for audit";
}
public function getName() {
return "Audit";
}
public function getUUID() {
return "26570956-dc62-46e3-ace9-86c6e8f9c81b";
}
public function getPluginVersion() {
return "2.0";
}
public function getEmptyDataObject() {
$obj = new stdClass();
$obj->autoDeleteAuditOlderThanDays = 60;
}
public function getPluginMenu() {
global $global;
$filename = $global['systemRootPath'] . 'plugin/Audit/pluginMenu.html';
return file_get_contents($filename);
}
function exec($method, $class, $statement, $formats, $values, $users_id) {
$audit = new AuditTable(0);
return $audit->audit($method, $class, $statement, $formats, $values, $users_id);
}
public function updateScript() {
global $global;
//update version 2.0
if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) {
sqlDal::executeFile($global['systemRootPath'] . 'plugin/Audit/install/updateV2.0.sql');
}
return true;
}
public function getEnd() {
_session_start();
if(User::isAdmin() && empty($_SESSION['auditDelete'])){
$obj = $this->getDataObject();
if(!empty($obj->autoDeleteAuditOlderThanDays)){
AuditTable::deleteOlderThan($obj->autoDeleteAuditOlderThanDays);
$_SESSION['auditDelete'] = 1;
return true;
}
}
return false;
}
}

View file

@ -1,2 +1,2 @@
ALTER TABLE `audit`
ALTER TABLE `audit`
CHANGE COLUMN `ip` `ip` VARCHAR(255) NULL;

View file

@ -1,18 +1,18 @@
<?php
require_once '../../../videos/configuration.php';
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not manager plugin Audit"));
exit;
}
header('Content-Type: application/json');
require_once $global['systemRootPath'] . 'plugin/Audit/Objects/AuditTable.php';
$rows = AuditTable::getAll();
$rowsTotal = AuditTable::getTotal();
?>
{
"draw": <?php echo $_GET['draw']; ?>,
"recordsTotal": <?php echo $rowsTotal; ?>,
"recordsFiltered": <?php echo $rowsTotal; ?>,
"data": <?php echo json_encode($rows); ?>
<?php
require_once '../../../videos/configuration.php';
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not manager plugin Audit"));
exit;
}
header('Content-Type: application/json');
require_once $global['systemRootPath'] . 'plugin/Audit/Objects/AuditTable.php';
$rows = AuditTable::getAll();
$rowsTotal = AuditTable::getTotal();
?>
{
"draw": <?php echo $_GET['draw']; ?>,
"recordsTotal": <?php echo $rowsTotal; ?>,
"recordsFiltered": <?php echo $rowsTotal; ?>,
"data": <?php echo json_encode($rows); ?>
}

View file

@ -1,87 +1,87 @@
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not manager plugin Audit"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle( __("Audit"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<link rel="stylesheet" type="text/css" href="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.css"/>
<style>
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-body">
<table id="auditTable" class="table table-striped">
<thead>
<tr>
<th>Class</th>
<th>Method</th>
<th>Statement</th>
<th>Format</th>
<th>Values</th>
<th>Created</th>
<th>User</th>
<th>IP</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Class</th>
<th>Method</th>
<th>Statement</th>
<th>Format</th>
<th>Values</th>
<th>Created</th>
<th>User</th>
<th>IP</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script type="text/javascript" src="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.js"></script>
<script>
$(document).ready(function () {
var auditTable = $('#auditTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo $global['webSiteRootURL']; ?>plugin/Audit/page/audits.json.php",
},
"columns": [
{"data": "class"},
{"data": "method"},
{"data": "statement"},
{"data": "formats"},
{"data": "values"},
{"data": "created"},
{"data": "user"},
{"data": "ip"},
],
select: true,
"order": [[5, "desc"]]
});
});
</script>
</body>
</html>
<?php
require_once '../../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not manager plugin Audit"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle( __("Audit"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<link rel="stylesheet" type="text/css" href="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.css"/>
<style>
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-body">
<table id="auditTable" class="table table-striped">
<thead>
<tr>
<th>Class</th>
<th>Method</th>
<th>Statement</th>
<th>Format</th>
<th>Values</th>
<th>Created</th>
<th>User</th>
<th>IP</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Class</th>
<th>Method</th>
<th>Statement</th>
<th>Format</th>
<th>Values</th>
<th>Created</th>
<th>User</th>
<th>IP</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script type="text/javascript" src="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.js"></script>
<script>
$(document).ready(function () {
var auditTable = $('#auditTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo $global['webSiteRootURL']; ?>plugin/Audit/page/audits.json.php",
},
"columns": [
{"data": "class"},
{"data": "method"},
{"data": "statement"},
{"data": "formats"},
{"data": "values"},
{"data": "created"},
{"data": "user"},
{"data": "ip"},
],
select: true,
"order": [[5, "desc"]]
});
});
</script>
</body>
</html>

View file

@ -1,150 +1,150 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'objects/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
class AutoPostOnSocialMedia extends PluginAbstract {
static $scheduleType = 'AutoPostOnSocialMedia';
public function getDescription() {
$desc = "AutoPostOnSocialMedia Plugin
Our final goal is to post a tweet on your Twitter account using the REST API. This process requires you to register the application on Twitter and get the API keys.
These API keys are act like your identity for your Twitter account. To create application, go to <a href='https://apps.twitter.com/' target='_blank'>Twitter Apps</a> and follow the below steps.
Click the button \"Create New App\".
Fill up Name, Description, Website fields.
Accept agreement and click the button \"Create your Twitter application\".
On the next page, click on the tab \"Keys and Access Tokens\". Under this tab you will find your Consumer Key and Consumer Secret. Copy these details and store it in safe place.
Under the same tab, you will see the section \"Your Access Token\". Click on the button \"Create Access Token\".
At this step, copy your Access Token and Access Token Secret. Keep these details safe.
Login in your app: http://dev.twitter.com/apps
In the Settings tab, change the Application type to Read, Write and Access direct messages
In the Reset keys tab, press the Reset button, update the consumer key and secret in your application accordingly.";
$desc = nl2br($desc);
return $desc;
}
public function getName() {
return "AutoPostOnSocialMedia";
}
public function getUUID() {
return "AutoPostOnSocialMedia-5ee8405eaaa16";
}
public function getPluginVersion() {
return "1.0";
}
public function updateScript() {
global $global;
/*
if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) {
sqlDal::executeFile($global['systemRootPath'] . 'plugin/PayPerView/install/updateV2.0.sql');
}
*
*/
return true;
}
public function getEmptyDataObject() {
$obj = new stdClass();
/*
$obj->textSample = "text";
$obj->checkboxSample = true;
$obj->numberSample = 5;
$o = new stdClass();
$o->type = array(0=>__("Default"))+array(1,2,3);
$o->value = 0;
$obj->selectBoxSample = $o;
$o = new stdClass();
$o->type = "textarea";
$o->value = "";
$obj->textareaSample = $o;
*/
$obj->TwitterEnable = true;
$obj->TwitterAPIKey = "";
$obj->TwitterAPIKeySecret = "";
$o = new stdClass();
$o->type = "textarea";
$o->value = "";
$obj->TwitterBearerToken = $o;
$obj->TwitterAccessToken = "";
$obj->TwitterAccessTokenSecret = "";
$o = new stdClass();
$o->type = array(
0 => __("All time"),
1 => __("1 Day"),
7 => __("7 Day"),
30 => __("1 Month"),
60 => __("2 Months"),
90 => __("3 Months"),
182 => __("6 Months"),
365 => __("12 Months"));
$o->value = 365;
$obj->postARandomVideoFromLastDays = $o;
return $obj;
}
public function getPluginMenu() {
global $global;
$btn = '<button onclick="avideoModalIframeLarge(webSiteRootURL+\'plugin/AutoPostOnSocialMedia/View/editor.php\')" class="btn btn-primary btn-sm btn-xs btn-block"><i class="fa fa-edit"></i> Edit</button>';
$btn .= '<button onclick="avideoAjax(webSiteRootURL+\'plugin/AutoPostOnSocialMedia/autopost.json.php\', {})" class="btn btn-primary btn-sm btn-xs btn-block"><i class="fab fa-twitter"></i> Autopost now</button>';
return $btn;
}
static function postVideo($videos_id) {
$url = Video::getLinkToVideo($videos_id, "", false, "permalink", $get);
return self::post($url);
}
static function post($msg) {
$obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia');
//var_dump($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret, $msg);exit;
if($obj->TwitterEnable){
$connection = new TwitterOAuth($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret);
$post_tweets = $connection->post("statuses/update", ["status" => $msg]);
}
return $post_tweets;
}
public function getVideosManagerListButton() {
if (!User::isAdmin()) {
return "";
}
$btn = '<button type="button" class="btn btn-default btn-light btn-sm btn-xs btn-block " onclick="avideoAlertAJAX(webSiteRootURL+\\\'plugin/AutoPostOnSocialMedia/post.json.php?videos_id=\' + row.id + \'\\\');" ><i class="fab fa-twitter"></i> Post On Twitter</button>';
return $btn;
}
static function getRandomVideo() {
$obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia');
$days = $obj->postARandomVideoFromLastDays->value;
$sql = "SELECT * FROM videos WHERE 1=1 ";
$sql .= " AND status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
if(!empty($days)){
$sql .=" AND created >= ( CURDATE() - INTERVAL {$days} DAY ) ";
}
$sql .= " ORDER BY RAND() LIMIT 1 ";
//echo var_dump($days, $sql);
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'objects/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
class AutoPostOnSocialMedia extends PluginAbstract {
static $scheduleType = 'AutoPostOnSocialMedia';
public function getDescription() {
$desc = "AutoPostOnSocialMedia Plugin
Our final goal is to post a tweet on your Twitter account using the REST API. This process requires you to register the application on Twitter and get the API keys.
These API keys are act like your identity for your Twitter account. To create application, go to <a href='https://apps.twitter.com/' target='_blank'>Twitter Apps</a> and follow the below steps.
Click the button \"Create New App\".
Fill up Name, Description, Website fields.
Accept agreement and click the button \"Create your Twitter application\".
On the next page, click on the tab \"Keys and Access Tokens\". Under this tab you will find your Consumer Key and Consumer Secret. Copy these details and store it in safe place.
Under the same tab, you will see the section \"Your Access Token\". Click on the button \"Create Access Token\".
At this step, copy your Access Token and Access Token Secret. Keep these details safe.
Login in your app: http://dev.twitter.com/apps
In the Settings tab, change the Application type to Read, Write and Access direct messages
In the Reset keys tab, press the Reset button, update the consumer key and secret in your application accordingly.";
$desc = nl2br($desc);
return $desc;
}
public function getName() {
return "AutoPostOnSocialMedia";
}
public function getUUID() {
return "AutoPostOnSocialMedia-5ee8405eaaa16";
}
public function getPluginVersion() {
return "1.0";
}
public function updateScript() {
global $global;
/*
if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) {
sqlDal::executeFile($global['systemRootPath'] . 'plugin/PayPerView/install/updateV2.0.sql');
}
*
*/
return true;
}
public function getEmptyDataObject() {
$obj = new stdClass();
/*
$obj->textSample = "text";
$obj->checkboxSample = true;
$obj->numberSample = 5;
$o = new stdClass();
$o->type = array(0=>__("Default"))+array(1,2,3);
$o->value = 0;
$obj->selectBoxSample = $o;
$o = new stdClass();
$o->type = "textarea";
$o->value = "";
$obj->textareaSample = $o;
*/
$obj->TwitterEnable = true;
$obj->TwitterAPIKey = "";
$obj->TwitterAPIKeySecret = "";
$o = new stdClass();
$o->type = "textarea";
$o->value = "";
$obj->TwitterBearerToken = $o;
$obj->TwitterAccessToken = "";
$obj->TwitterAccessTokenSecret = "";
$o = new stdClass();
$o->type = array(
0 => __("All time"),
1 => __("1 Day"),
7 => __("7 Day"),
30 => __("1 Month"),
60 => __("2 Months"),
90 => __("3 Months"),
182 => __("6 Months"),
365 => __("12 Months"));
$o->value = 365;
$obj->postARandomVideoFromLastDays = $o;
return $obj;
}
public function getPluginMenu() {
global $global;
$btn = '<button onclick="avideoModalIframeLarge(webSiteRootURL+\'plugin/AutoPostOnSocialMedia/View/editor.php\')" class="btn btn-primary btn-sm btn-xs btn-block"><i class="fa fa-edit"></i> Edit</button>';
$btn .= '<button onclick="avideoAjax(webSiteRootURL+\'plugin/AutoPostOnSocialMedia/autopost.json.php\', {})" class="btn btn-primary btn-sm btn-xs btn-block"><i class="fab fa-twitter"></i> Autopost now</button>';
return $btn;
}
static function postVideo($videos_id) {
$url = Video::getLinkToVideo($videos_id, "", false, "permalink", $get);
return self::post($url);
}
static function post($msg) {
$obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia');
//var_dump($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret, $msg);exit;
if($obj->TwitterEnable){
$connection = new TwitterOAuth($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret);
$post_tweets = $connection->post("statuses/update", ["status" => $msg]);
}
return $post_tweets;
}
public function getVideosManagerListButton() {
if (!User::isAdmin()) {
return "";
}
$btn = '<button type="button" class="btn btn-default btn-light btn-sm btn-xs btn-block " onclick="avideoAlertAJAX(webSiteRootURL+\\\'plugin/AutoPostOnSocialMedia/post.json.php?videos_id=\' + row.id + \'\\\');" ><i class="fab fa-twitter"></i> Post On Twitter</button>';
return $btn;
}
static function getRandomVideo() {
$obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia');
$days = $obj->postARandomVideoFromLastDays->value;
$sql = "SELECT * FROM videos WHERE 1=1 ";
$sql .= " AND status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
if(!empty($days)){
$sql .=" AND created >= ( CURDATE() - INTERVAL {$days} DAY ) ";
}
$sql .= " ORDER BY RAND() LIMIT 1 ";
//echo var_dump($days, $sql);
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
}

View file

@ -1,145 +1,145 @@
<?php
require_once '../../../videos/configuration.php';
AVideoPlugin::loadPlugin("AutoPostOnSocialMedia");
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<title><?php echo $config->getWebSiteTitle(); ?> :: AutoPostOnSocialMedia</title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-sm-2">
<input type="checkbox" onclick="$('.scheduleTwitterPost input:checkbox').prop('checked', this.checked);" id="AutoPostOnSocialMediaCheckbox">
<label for="AutoPostOnSocialMediaCheckbox">
<?php echo __('AutoPostOnSocialMedia') ?>
</label>
</div>
<div class="col-sm-8">
<button class="btn btn-success btn-block" onclick="saveScheduleTwitter();">
<i class="fas fa-save"></i>
<?php echo __('Save') ?>
</button>
</div>
<div class="col-sm-2">
<div class="pull-right">
<?php echo AVideoPlugin::getSwitchButton("AutoPostOnSocialMedia"); ?>
</div>
</div>
</div>
</div>
<div class="panel-body scheduleTwitterPost">
<?php
$rows = Scheduler_commands::getAllFromType(AutoPostOnSocialMedia::$scheduleType);
$savedValues = array();
foreach ($rows as $value) {
if(!isset($savedValues[$value['repeat_day_of_week']])){
$savedValues[$value['repeat_day_of_week']] = array();
}
$savedValues[$value['repeat_day_of_week']][] = $value['repeat_hour'];
}
//var_dump($savedValues);
$weekdays = array(
__('Sunday'),
__('Monday'),
__('Tuesday'),
__('Wednsday'),
__('Thursday'),
__('Friday'),
__('Saturday')
);
$columns = 3;
foreach ($weekdays as $weekday => $value) {
?>
<div class="col-lg-3 col-md-4 col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<input type="checkbox" onclick="$('.scheduleTwitterPost input.form-check-input-<?php echo $value; ?>:checkbox').prop('checked', this.checked);" id="AutoPostOnSocialMediaCheckbox-<?php echo $value; ?>">
<label for="AutoPostOnSocialMediaCheckbox-<?php echo $value; ?>">
<?php echo $value; ?>
</label>
</div>
<div class="panel-body">
<?php
$i = 0;
for ($c = 1; $c <= $columns; $c++) {
$val = 12 / $columns;
$class = 'col-xs-' . $val;
$time = 24 / $columns;
?>
<div class="<?php echo $class; ?>">
<?php
for (; $i < $time * $c; $i++) {
$checked = '';
if(!empty($savedValues[$weekday]) && in_array($i, $savedValues[$weekday])){
$checked = 'checked="checked"';
}
?>
<div class="form-check">
<input class="form-check-input form-check-input-<?php echo $value; ?>" type="checkbox" <?php echo $checked; ?>
value="<?php echo $weekday; ?>_<?php echo $i; ?>" id="flexCheckDefault<?php echo $value . $i; ?>">
<label class="form-check-label" for="flexCheckDefault<?php echo $value . $i; ?>">
<?php printf("%02d", $i); ?>H
</label>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script>
$(function () {
});
function saveScheduleTwitter() {
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'plugin/AutoPostOnSocialMedia/saveSchedule.json.php',
method: 'POST',
data: {
'checkedItems': getCheckedItems()
},
success: function (response) {
avideoResponse(response);
modal.hidePleaseWait();
}
});
}
function getCheckedItems() {
var selected = new Array();
$("input.form-check-input:checkbox:checked").each(function () {
selected.push($(this).val());
});
console.log('selected', selected);
return selected;
}
</script>
</body>
</html>
<?php
require_once '../../../videos/configuration.php';
AVideoPlugin::loadPlugin("AutoPostOnSocialMedia");
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<title><?php echo $config->getWebSiteTitle(); ?> :: AutoPostOnSocialMedia</title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-sm-2">
<input type="checkbox" onclick="$('.scheduleTwitterPost input:checkbox').prop('checked', this.checked);" id="AutoPostOnSocialMediaCheckbox">
<label for="AutoPostOnSocialMediaCheckbox">
<?php echo __('AutoPostOnSocialMedia') ?>
</label>
</div>
<div class="col-sm-8">
<button class="btn btn-success btn-block" onclick="saveScheduleTwitter();">
<i class="fas fa-save"></i>
<?php echo __('Save') ?>
</button>
</div>
<div class="col-sm-2">
<div class="pull-right">
<?php echo AVideoPlugin::getSwitchButton("AutoPostOnSocialMedia"); ?>
</div>
</div>
</div>
</div>
<div class="panel-body scheduleTwitterPost">
<?php
$rows = Scheduler_commands::getAllFromType(AutoPostOnSocialMedia::$scheduleType);
$savedValues = array();
foreach ($rows as $value) {
if(!isset($savedValues[$value['repeat_day_of_week']])){
$savedValues[$value['repeat_day_of_week']] = array();
}
$savedValues[$value['repeat_day_of_week']][] = $value['repeat_hour'];
}
//var_dump($savedValues);
$weekdays = array(
__('Sunday'),
__('Monday'),
__('Tuesday'),
__('Wednsday'),
__('Thursday'),
__('Friday'),
__('Saturday')
);
$columns = 3;
foreach ($weekdays as $weekday => $value) {
?>
<div class="col-lg-3 col-md-4 col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<input type="checkbox" onclick="$('.scheduleTwitterPost input.form-check-input-<?php echo $value; ?>:checkbox').prop('checked', this.checked);" id="AutoPostOnSocialMediaCheckbox-<?php echo $value; ?>">
<label for="AutoPostOnSocialMediaCheckbox-<?php echo $value; ?>">
<?php echo $value; ?>
</label>
</div>
<div class="panel-body">
<?php
$i = 0;
for ($c = 1; $c <= $columns; $c++) {
$val = 12 / $columns;
$class = 'col-xs-' . $val;
$time = 24 / $columns;
?>
<div class="<?php echo $class; ?>">
<?php
for (; $i < $time * $c; $i++) {
$checked = '';
if(!empty($savedValues[$weekday]) && in_array($i, $savedValues[$weekday])){
$checked = 'checked="checked"';
}
?>
<div class="form-check">
<input class="form-check-input form-check-input-<?php echo $value; ?>" type="checkbox" <?php echo $checked; ?>
value="<?php echo $weekday; ?>_<?php echo $i; ?>" id="flexCheckDefault<?php echo $value . $i; ?>">
<label class="form-check-label" for="flexCheckDefault<?php echo $value . $i; ?>">
<?php printf("%02d", $i); ?>H
</label>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script>
$(function () {
});
function saveScheduleTwitter() {
modal.showPleaseWait();
$.ajax({
url: webSiteRootURL + 'plugin/AutoPostOnSocialMedia/saveSchedule.json.php',
method: 'POST',
data: {
'checkedItems': getCheckedItems()
},
success: function (response) {
avideoResponse(response);
modal.hidePleaseWait();
}
});
}
function getCheckedItems() {
var selected = new Array();
$("input.form-check-input:checkbox:checked").each(function () {
selected.push($(this).val());
});
console.log('selected', selected);
return selected;
}
</script>
</body>
</html>

View file

@ -1,32 +1,32 @@
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = '';
$objAutoPostOnSocialMedia = AVideoPlugin::getDataObjectIfEnabled('AutoPostOnSocialMedia');
if(empty($objAutoPostOnSocialMedia)){
$obj->msg = 'Plugin disabled';
die(json_encode($obj));
}
if(!isCommandLineInterface() && !User::isAdmin() && !isTokenValid($_REQUEST['token'])){
$obj->msg = 'Forbbiden';
die(json_encode($obj));
}
$video = AutoPostOnSocialMedia::getRandomVideo();
$obj->video = $video;
if(empty($obj->video)){
$obj->msg = 'Invalid video';
die(json_encode($obj));
}
$_REQUEST['videos_id'] = $obj->video['id'];
require_once $global['systemRootPath'] . 'plugin/AutoPostOnSocialMedia/post.json.php';
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = '';
$objAutoPostOnSocialMedia = AVideoPlugin::getDataObjectIfEnabled('AutoPostOnSocialMedia');
if(empty($objAutoPostOnSocialMedia)){
$obj->msg = 'Plugin disabled';
die(json_encode($obj));
}
if(!isCommandLineInterface() && !User::isAdmin() && !isTokenValid($_REQUEST['token'])){
$obj->msg = 'Forbbiden';
die(json_encode($obj));
}
$video = AutoPostOnSocialMedia::getRandomVideo();
$obj->video = $video;
if(empty($obj->video)){
$obj->msg = 'Invalid video';
die(json_encode($obj));
}
$_REQUEST['videos_id'] = $obj->video['id'];
require_once $global['systemRootPath'] . 'plugin/AutoPostOnSocialMedia/post.json.php';

View file

@ -1,40 +1,40 @@
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = '';
$obj->videos_id = 0;
$objAutoPostOnSocialMedia = AVideoPlugin::getDataObjectIfEnabled('AutoPostOnSocialMedia');
if(empty($objAutoPostOnSocialMedia)){
$obj->msg = 'Plugin disabled';
die(json_encode($obj));
}
if(!isCommandLineInterface() && !User::isAdmin() && !isTokenValid($_REQUEST['token'])){
$obj->msg = 'Forbbiden';
die(json_encode($obj));
}
$obj->videos_id = intval($_REQUEST['videos_id']);
if(empty($obj->videos_id)){
$obj->videos_id = intval($argv[1]);
}
if(empty($obj->videos_id)){
$obj->msg = 'Invalid videos ID';
die(json_encode($obj));
}
$obj->response = AutoPostOnSocialMedia::postVideo($obj->videos_id);
if(!empty($obj->response->error)){
$obj->msg = $obj->response->error;
}else{
$obj->error = false;
}
<?php
require_once '../../videos/configuration.php';
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = '';
$obj->videos_id = 0;
$objAutoPostOnSocialMedia = AVideoPlugin::getDataObjectIfEnabled('AutoPostOnSocialMedia');
if(empty($objAutoPostOnSocialMedia)){
$obj->msg = 'Plugin disabled';
die(json_encode($obj));
}
if(!isCommandLineInterface() && !User::isAdmin() && !isTokenValid($_REQUEST['token'])){
$obj->msg = 'Forbbiden';
die(json_encode($obj));
}
$obj->videos_id = intval($_REQUEST['videos_id']);
if(empty($obj->videos_id)){
$obj->videos_id = intval($argv[1]);
}
if(empty($obj->videos_id)){
$obj->msg = 'Invalid videos ID';
die(json_encode($obj));
}
$obj->response = AutoPostOnSocialMedia::postVideo($obj->videos_id);
if(!empty($obj->response->error)){
$obj->msg = $obj->response->error;
}else{
$obj->error = false;
}
die(json_encode($obj));

View file

@ -1,126 +1,126 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/BlockonomicsYPT/Objects/BlockonomicsOrder.php';
class BlockonomicsYPT extends PluginAbstract {
static $BASE_URL = "https://www.blockonomics.co/";
static function getPRICE_URL() {
$obj = AVideoPlugin::getObjectData("YPTWallet");
$currency = $obj->currency;
return self::$BASE_URL . 'api/price?currency=' . strtoupper($currency);
}
public function getDescription() {
global $global;
$obj = $this->getDataObject();
$return = "<a href='https://www.blockonomics.co'>Blockonomics</a> is a decentralized and permissionless bitcoin payment solution.";
$return .= "<br>HTTP Callback URL: <br><code>{$global['webSiteRootURL']}plugin/BlockonomicsYPT/callback.php?secret={$obj->Secret}</code>";
return $return;
}
public function getName() {
return "BlockonomicsYPT";
}
public function getUUID() {
return "bitcoin9-c0b6-4264-85cb-47ae076d949f";
}
public function getPluginVersion() {
return "1.0";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->APIKey = "NUdcVWq0Juz29qnJH9hebgdvEY0qiSIpWZo5nCWXask";
$obj->Secret = md5($global['systemRootPath'] . $global['salt']);
$obj->ExpireInSeconds = 600;
return $obj;
}
public function setUpPayment($total_cost = '1.00') {
global $global;
$total_cost = floatval($total_cost);
$obj = $this->getDataObject();
$objWallet = AVideoPlugin::getObjectData("YPTWallet");
$currency = $objWallet->currency;
//return here if total is empty
if (empty($total_cost)) {
echo $json_response = json_encode(array("error" => "Total Is Empty"));
return;
}
if (!User::isLogged()) {
echo $json_response = json_encode(array("error" => "Must be logged in"));
return;
}
//Generate new address for this invoice
$new_address = $this->getNewAddress($obj->APIKey);
if (empty($new_address)) {
_error_log('Blockonomics ERROR 1: ' . $contents . ' ' . json_last_error_msg(), AVideoLog::$ERROR);
return false;
}
//Getting price
$options = array('http' => array('method' => 'GET'));
$context = stream_context_create($options);
$contents = url_get_contents(self::getPRICE_URL(), $context, 0, true);
$price = _json_decode($contents);
//Total Cart value in bits
$bits = intval(1.0e8 * $total_cost / $price->price);
// save on database
$b = new BlockonomicsOrder(0);
$b->setAddr($new_address);
$b->setBits($bits);
$b->setBits_payed(0);
$b->setStatus("-1");
$b->setTxid("");
$b->setUsers_id(User::getId());
$b->setTotal_value($total_cost);
$b->setCurrency($currency);
return $b->save();
}
public function getNewAddress($api_key) {
$url = 'https://www.blockonomics.co/api/new_address';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$header = "Authorization: Bearer " . $api_key;
$headers = array();
$headers[] = $header;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
_error_log("Blockonomics Error 2:" . curl_error($ch));
return false;
}
$responseObj = _json_decode($contents);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200) {
return $responseObj->address;
} else {
//echo "<div class='alert alert-danger'>{$responseObj->message}</div>";
_error_log("Blockonomics Error 3: [{$status}] {$responseObj->message}");
}
return false;
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/BlockonomicsYPT/Objects/BlockonomicsOrder.php';
class BlockonomicsYPT extends PluginAbstract {
static $BASE_URL = "https://www.blockonomics.co/";
static function getPRICE_URL() {
$obj = AVideoPlugin::getObjectData("YPTWallet");
$currency = $obj->currency;
return self::$BASE_URL . 'api/price?currency=' . strtoupper($currency);
}
public function getDescription() {
global $global;
$obj = $this->getDataObject();
$return = "<a href='https://www.blockonomics.co'>Blockonomics</a> is a decentralized and permissionless bitcoin payment solution.";
$return .= "<br>HTTP Callback URL: <br><code>{$global['webSiteRootURL']}plugin/BlockonomicsYPT/callback.php?secret={$obj->Secret}</code>";
return $return;
}
public function getName() {
return "BlockonomicsYPT";
}
public function getUUID() {
return "bitcoin9-c0b6-4264-85cb-47ae076d949f";
}
public function getPluginVersion() {
return "1.0";
}
public function getEmptyDataObject() {
global $global;
$obj = new stdClass();
$obj->APIKey = "NUdcVWq0Juz29qnJH9hebgdvEY0qiSIpWZo5nCWXask";
$obj->Secret = md5($global['systemRootPath'] . $global['salt']);
$obj->ExpireInSeconds = 600;
return $obj;
}
public function setUpPayment($total_cost = '1.00') {
global $global;
$total_cost = floatval($total_cost);
$obj = $this->getDataObject();
$objWallet = AVideoPlugin::getObjectData("YPTWallet");
$currency = $objWallet->currency;
//return here if total is empty
if (empty($total_cost)) {
echo $json_response = json_encode(array("error" => "Total Is Empty"));
return;
}
if (!User::isLogged()) {
echo $json_response = json_encode(array("error" => "Must be logged in"));
return;
}
//Generate new address for this invoice
$new_address = $this->getNewAddress($obj->APIKey);
if (empty($new_address)) {
_error_log('Blockonomics ERROR 1: ' . $contents . ' ' . json_last_error_msg(), AVideoLog::$ERROR);
return false;
}
//Getting price
$options = array('http' => array('method' => 'GET'));
$context = stream_context_create($options);
$contents = url_get_contents(self::getPRICE_URL(), $context, 0, true);
$price = _json_decode($contents);
//Total Cart value in bits
$bits = intval(1.0e8 * $total_cost / $price->price);
// save on database
$b = new BlockonomicsOrder(0);
$b->setAddr($new_address);
$b->setBits($bits);
$b->setBits_payed(0);
$b->setStatus("-1");
$b->setTxid("");
$b->setUsers_id(User::getId());
$b->setTotal_value($total_cost);
$b->setCurrency($currency);
return $b->save();
}
public function getNewAddress($api_key) {
$url = 'https://www.blockonomics.co/api/new_address';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$header = "Authorization: Bearer " . $api_key;
$headers = array();
$headers[] = $header;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
_error_log("Blockonomics Error 2:" . curl_error($ch));
return false;
}
$responseObj = _json_decode($contents);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200) {
return $responseObj->address;
} else {
//echo "<div class='alert alert-danger'>{$responseObj->message}</div>";
_error_log("Blockonomics Error 3: [{$status}] {$responseObj->message}");
}
return false;
}
}

View file

@ -1,73 +1,73 @@
<?php
/**
-2 : PAYMENT_EXPIRED
-1 : PAYMENT_ERROR (Happens when Paid BTC amount is not matching expected value)
0 : UNPAID
1 : IN_PROCESS
2 : PAID
*/
// check recurrent payments
header('Content-Type: application/json');
if (empty($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
require_once $global['systemRootPath'] . 'videos/configuration.php';
$plugin = AVideoPlugin::loadPluginIfEnabled("BlockonomicsYPT");
$obj = $plugin->getDataObject();
$txid = $_GET['txid'];
$value = $_GET['value'];
$status = $_GET['status'];
$addr = $_GET['addr'];
//Match secret for security
if ($_GET['secret'] != $obj->Secret) {
echo "Secret is not matching.";
return;
}
$order = new BlockonomicsOrder(0);
$order->loadFromAddress($addr);
if (empty($order->getId())) {
echo "Address not found.";
return;
}
if ($order->getStatus() < -1) {
//payment already in error/expired, do nothing
return;
}
$new_status = $status;
if ($status == 0 && time() > strtotime($order->getCreated()) + $obj->ExpireInSeconds) {
//Payment expired, Paid after 10 minutes
$new_status = -3;
print('expired');
}
if ($status == 2 && $value < $order->getBits()) {
//Payment error, amount paid not matching expected
$new_status = -2;
}
$order->setTxid($txid);
$order->setBits_payed($value);
// add balance on the wallet
if ($new_status == 2 && $order->getStatus()!=200) {
$plugin = AVideoPlugin::loadPluginIfEnabled("YPTWallet");
$users_id = $order->getUsers_id();
$total = $order->getTotal_value();
$plugin->addBalance($users_id, $total, "Blockonomics payment", json_encode($order));
// status OK, do not process it anymore
$new_status = 200;
}
$order->setStatus($new_status);
$order->save();
_error_log("Blockonomics Callback: GET=". json_encode($_GET));
_error_log("Blockonomics Callback: order=". json_encode($order));
<?php
/**
-2 : PAYMENT_EXPIRED
-1 : PAYMENT_ERROR (Happens when Paid BTC amount is not matching expected value)
0 : UNPAID
1 : IN_PROCESS
2 : PAID
*/
// check recurrent payments
header('Content-Type: application/json');
if (empty($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
require_once $global['systemRootPath'] . 'videos/configuration.php';
$plugin = AVideoPlugin::loadPluginIfEnabled("BlockonomicsYPT");
$obj = $plugin->getDataObject();
$txid = $_GET['txid'];
$value = $_GET['value'];
$status = $_GET['status'];
$addr = $_GET['addr'];
//Match secret for security
if ($_GET['secret'] != $obj->Secret) {
echo "Secret is not matching.";
return;
}
$order = new BlockonomicsOrder(0);
$order->loadFromAddress($addr);
if (empty($order->getId())) {
echo "Address not found.";
return;
}
if ($order->getStatus() < -1) {
//payment already in error/expired, do nothing
return;
}
$new_status = $status;
if ($status == 0 && time() > strtotime($order->getCreated()) + $obj->ExpireInSeconds) {
//Payment expired, Paid after 10 minutes
$new_status = -3;
print('expired');
}
if ($status == 2 && $value < $order->getBits()) {
//Payment error, amount paid not matching expected
$new_status = -2;
}
$order->setTxid($txid);
$order->setBits_payed($value);
// add balance on the wallet
if ($new_status == 2 && $order->getStatus()!=200) {
$plugin = AVideoPlugin::loadPluginIfEnabled("YPTWallet");
$users_id = $order->getUsers_id();
$total = $order->getTotal_value();
$plugin->addBalance($users_id, $total, "Blockonomics payment", json_encode($order));
// status OK, do not process it anymore
$new_status = 200;
}
$order->setStatus($new_status);
$order->save();
_error_log("Blockonomics Callback: GET=". json_encode($_GET));
_error_log("Blockonomics Callback: order=". json_encode($order));
?>

View file

@ -1,136 +1,136 @@
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isLogged()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
$plugin = AVideoPlugin::loadPluginIfEnabled("BlockonomicsYPT");
$obj = AVideoPlugin::getObjectData("BlockonomicsYPT");
$order_id = $plugin->setUpPayment($_GET['value']);
$order = new BlockonomicsOrder($order_id);
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle( __("Invoice"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<style>
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h1>
Order#: <?php echo sprintf('%08d', $order->getId()); ?>
</h1>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<h2>Bitcoin Address</h2>
<a href="bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>">
<div id="qrcode" class="text-center"></div>
</a>
<br/>
<div class="field">
<div class="control">
<input type="text" class="input form-control" value="<?php echo $order->getAddr(); ?>" readonly="readonly">
</div>
</div>
</div>
<div class="col-md-6">
<h2>To pay, send exact amount of BTC to the given address</h2>
<h3>Amount</h3>
<p><strong><?php echo $order->getFormatedBits(); ?></strong> BTC ⇌ <strong><?php echo $order->getTotal_value(); ?></strong> <?php echo $order->getCurrency(); ?></p>
<br/>
<h2>Payment Details: </h2>
<h4 style="display: none;" class="bstatus label label-danger" id="status-3"> Payment Expired</h4>
<h4 style="display: none;" class="bstatus label label-danger" id="status-2"> Payment Error</h4>
<h4 style="display: none;" class="bstatus label label-warning" id="status0"> Unconfirmed</h4>
<h4 style="display: none;" class="bstatus label label-warning" id="status1"> Partially Confirmed</h4>
<h4 style="display: none;" class="bstatus label label-success" id="status2" >Confirmed</h4>
<div>
Received : <strong id="received"><?php echo $order->getFormatedBits_payed(); ?></strong>
<small>BTC</small>
</div>
<div style="margin-bottom:10px;" >
Transaction : <span id="transaction"></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:100%" id="timeleft">
100%
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script src="<?php echo getCDN(); ?>plugin/BlockonomicsYPT/jquery.qrcode.min.js" type="text/javascript"></script>
<script>
var totalSeconds = <?php echo $obj->ExpireInSeconds; ?>;
var totalSecondsPassed = <?php echo time() - strtotime($order->getCreated()); ?>;
var totalSecondsleft = totalSeconds - totalSecondsPassed;
$(document).ready(function () {
$('#qrcode').qrcode({width: 220, height: 220, text: "bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>"});
setInterval(function () {
totalSecondsleft--;
if (totalSecondsleft < 1) {
totalSecondsleft = 0;
}
var percent = (totalSecondsleft / totalSeconds) * 100;
$("#timeleft").css('width', percent + "%").html(totalSecondsleft + " <?php echo __("Seconds Left"); ?>");
}, 1000);
check();
});
function check() {
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/BlockonomicsYPT/check.php?addr=<?php echo $order->getAddr(); ?>',
success: function (response) {
console.log(response);
if (response.status < 2) {
$("#transaction").html('<a target="_blank" href="http://www.blockonomics.co/api/tx?txid=' + response.txid + '&addr={{<?php echo $order->getAddr(); ?>}}">' + response.txid + '</a>');
$("#received").html((response.bits_payed / 1.0e8));
setTimeout(function () {
check();
}, 3000);
}else{
response.status = 2;
}
$(".bstatus").not("#status"+response.status).hide();
$("#status"+response.status).fadeIn();
}
});
}
</script>
</body>
</html>
<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isLogged()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
$plugin = AVideoPlugin::loadPluginIfEnabled("BlockonomicsYPT");
$obj = AVideoPlugin::getObjectData("BlockonomicsYPT");
$order_id = $plugin->setUpPayment($_GET['value']);
$order = new BlockonomicsOrder($order_id);
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle( __("Invoice"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<style>
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h1>
Order#: <?php echo sprintf('%08d', $order->getId()); ?>
</h1>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<h2>Bitcoin Address</h2>
<a href="bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>">
<div id="qrcode" class="text-center"></div>
</a>
<br/>
<div class="field">
<div class="control">
<input type="text" class="input form-control" value="<?php echo $order->getAddr(); ?>" readonly="readonly">
</div>
</div>
</div>
<div class="col-md-6">
<h2>To pay, send exact amount of BTC to the given address</h2>
<h3>Amount</h3>
<p><strong><?php echo $order->getFormatedBits(); ?></strong> BTC ⇌ <strong><?php echo $order->getTotal_value(); ?></strong> <?php echo $order->getCurrency(); ?></p>
<br/>
<h2>Payment Details: </h2>
<h4 style="display: none;" class="bstatus label label-danger" id="status-3"> Payment Expired</h4>
<h4 style="display: none;" class="bstatus label label-danger" id="status-2"> Payment Error</h4>
<h4 style="display: none;" class="bstatus label label-warning" id="status0"> Unconfirmed</h4>
<h4 style="display: none;" class="bstatus label label-warning" id="status1"> Partially Confirmed</h4>
<h4 style="display: none;" class="bstatus label label-success" id="status2" >Confirmed</h4>
<div>
Received : <strong id="received"><?php echo $order->getFormatedBits_payed(); ?></strong>
<small>BTC</small>
</div>
<div style="margin-bottom:10px;" >
Transaction : <span id="transaction"></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:100%" id="timeleft">
100%
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script src="<?php echo getCDN(); ?>plugin/BlockonomicsYPT/jquery.qrcode.min.js" type="text/javascript"></script>
<script>
var totalSeconds = <?php echo $obj->ExpireInSeconds; ?>;
var totalSecondsPassed = <?php echo time() - strtotime($order->getCreated()); ?>;
var totalSecondsleft = totalSeconds - totalSecondsPassed;
$(document).ready(function () {
$('#qrcode').qrcode({width: 220, height: 220, text: "bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>"});
setInterval(function () {
totalSecondsleft--;
if (totalSecondsleft < 1) {
totalSecondsleft = 0;
}
var percent = (totalSecondsleft / totalSeconds) * 100;
$("#timeleft").css('width', percent + "%").html(totalSecondsleft + " <?php echo __("Seconds Left"); ?>");
}, 1000);
check();
});
function check() {
$.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/BlockonomicsYPT/check.php?addr=<?php echo $order->getAddr(); ?>',
success: function (response) {
console.log(response);
if (response.status < 2) {
$("#transaction").html('<a target="_blank" href="http://www.blockonomics.co/api/tx?txid=' + response.txid + '&addr={{<?php echo $order->getAddr(); ?>}}">' + response.txid + '</a>');
$("#received").html((response.bits_payed / 1.0e8));
setTimeout(function () {
check();
}, 3000);
}else{
response.status = 2;
}
$(".bstatus").not("#status"+response.status).hide();
$("#status"+response.status).fadeIn();
}
});
}
</script>
</body>
</html>

View file

@ -1,28 +1,28 @@
(function(r){r.fn.qrcode=function(h){var s;function u(a){this.mode=s;this.data=a}function o(a,c){this.typeNumber=a;this.errorCorrectLevel=c;this.modules=null;this.moduleCount=0;this.dataCache=null;this.dataList=[]}function q(a,c){if(void 0==a.length)throw Error(a.length+"/"+c);for(var d=0;d<a.length&&0==a[d];)d++;this.num=Array(a.length-d+c);for(var b=0;b<a.length-d;b++)this.num[b]=a[b+d]}function p(a,c){this.totalCount=a;this.dataCount=c}function t(){this.buffer=[];this.length=0}u.prototype={getLength:function(){return this.data.length},
write:function(a){for(var c=0;c<this.data.length;c++)a.put(this.data.charCodeAt(c),8)}};o.prototype={addData:function(a){this.dataList.push(new u(a));this.dataCache=null},isDark:function(a,c){if(0>a||this.moduleCount<=a||0>c||this.moduleCount<=c)throw Error(a+","+c);return this.modules[a][c]},getModuleCount:function(){return this.moduleCount},make:function(){if(1>this.typeNumber){for(var a=1,a=1;40>a;a++){for(var c=p.getRSBlocks(a,this.errorCorrectLevel),d=new t,b=0,e=0;e<c.length;e++)b+=c[e].dataCount;
for(e=0;e<this.dataList.length;e++)c=this.dataList[e],d.put(c.mode,4),d.put(c.getLength(),j.getLengthInBits(c.mode,a)),c.write(d);if(d.getLengthInBits()<=8*b)break}this.typeNumber=a}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17;this.modules=Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=Array(this.moduleCount);for(var b=0;b<this.moduleCount;b++)this.modules[d][b]=null}this.setupPositionProbePattern(0,0);this.setupPositionProbePattern(this.moduleCount-
7,0);this.setupPositionProbePattern(0,this.moduleCount-7);this.setupPositionAdjustPattern();this.setupTimingPattern();this.setupTypeInfo(a,c);7<=this.typeNumber&&this.setupTypeNumber(a);null==this.dataCache&&(this.dataCache=o.createData(this.typeNumber,this.errorCorrectLevel,this.dataList));this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,c){for(var d=-1;7>=d;d++)if(!(-1>=a+d||this.moduleCount<=a+d))for(var b=-1;7>=b;b++)-1>=c+b||this.moduleCount<=c+b||(this.modules[a+d][c+b]=
0<=d&&6>=d&&(0==b||6==b)||0<=b&&6>=b&&(0==d||6==d)||2<=d&&4>=d&&2<=b&&4>=b?!0:!1)},getBestMaskPattern:function(){for(var a=0,c=0,d=0;8>d;d++){this.makeImpl(!0,d);var b=j.getLostPoint(this);if(0==d||a>b)a=b,c=d}return c},createMovieClip:function(a,c,d){a=a.createEmptyMovieClip(c,d);this.make();for(c=0;c<this.modules.length;c++)for(var d=1*c,b=0;b<this.modules[c].length;b++){var e=1*b;this.modules[c][b]&&(a.beginFill(0,100),a.moveTo(e,d),a.lineTo(e+1,d),a.lineTo(e+1,d+1),a.lineTo(e,d+1),a.endFill())}return a},
setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(a=8;a<this.moduleCount-8;a++)null==this.modules[6][a]&&(this.modules[6][a]=0==a%2)},setupPositionAdjustPattern:function(){for(var a=j.getPatternPosition(this.typeNumber),c=0;c<a.length;c++)for(var d=0;d<a.length;d++){var b=a[c],e=a[d];if(null==this.modules[b][e])for(var f=-2;2>=f;f++)for(var i=-2;2>=i;i++)this.modules[b+f][e+i]=-2==f||2==f||-2==i||2==i||0==f&&0==i?!0:!1}},setupTypeNumber:function(a){for(var c=
j.getBCHTypeNumber(this.typeNumber),d=0;18>d;d++){var b=!a&&1==(c>>d&1);this.modules[Math.floor(d/3)][d%3+this.moduleCount-8-3]=b}for(d=0;18>d;d++)b=!a&&1==(c>>d&1),this.modules[d%3+this.moduleCount-8-3][Math.floor(d/3)]=b},setupTypeInfo:function(a,c){for(var d=j.getBCHTypeInfo(this.errorCorrectLevel<<3|c),b=0;15>b;b++){var e=!a&&1==(d>>b&1);6>b?this.modules[b][8]=e:8>b?this.modules[b+1][8]=e:this.modules[this.moduleCount-15+b][8]=e}for(b=0;15>b;b++)e=!a&&1==(d>>b&1),8>b?this.modules[8][this.moduleCount-
b-1]=e:9>b?this.modules[8][15-b-1+1]=e:this.modules[8][15-b-1]=e;this.modules[this.moduleCount-8][8]=!a},mapData:function(a,c){for(var d=-1,b=this.moduleCount-1,e=7,f=0,i=this.moduleCount-1;0<i;i-=2)for(6==i&&i--;;){for(var g=0;2>g;g++)if(null==this.modules[b][i-g]){var n=!1;f<a.length&&(n=1==(a[f]>>>e&1));j.getMask(c,b,i-g)&&(n=!n);this.modules[b][i-g]=n;e--; -1==e&&(f++,e=7)}b+=d;if(0>b||this.moduleCount<=b){b-=d;d=-d;break}}}};o.PAD0=236;o.PAD1=17;o.createData=function(a,c,d){for(var c=p.getRSBlocks(a,
c),b=new t,e=0;e<d.length;e++){var f=d[e];b.put(f.mode,4);b.put(f.getLength(),j.getLengthInBits(f.mode,a));f.write(b)}for(e=a=0;e<c.length;e++)a+=c[e].dataCount;if(b.getLengthInBits()>8*a)throw Error("code length overflow. ("+b.getLengthInBits()+">"+8*a+")");for(b.getLengthInBits()+4<=8*a&&b.put(0,4);0!=b.getLengthInBits()%8;)b.putBit(!1);for(;!(b.getLengthInBits()>=8*a);){b.put(o.PAD0,8);if(b.getLengthInBits()>=8*a)break;b.put(o.PAD1,8)}return o.createBytes(b,c)};o.createBytes=function(a,c){for(var d=
0,b=0,e=0,f=Array(c.length),i=Array(c.length),g=0;g<c.length;g++){var n=c[g].dataCount,h=c[g].totalCount-n,b=Math.max(b,n),e=Math.max(e,h);f[g]=Array(n);for(var k=0;k<f[g].length;k++)f[g][k]=255&a.buffer[k+d];d+=n;k=j.getErrorCorrectPolynomial(h);n=(new q(f[g],k.getLength()-1)).mod(k);i[g]=Array(k.getLength()-1);for(k=0;k<i[g].length;k++)h=k+n.getLength()-i[g].length,i[g][k]=0<=h?n.get(h):0}for(k=g=0;k<c.length;k++)g+=c[k].totalCount;d=Array(g);for(k=n=0;k<b;k++)for(g=0;g<c.length;g++)k<f[g].length&&
(d[n++]=f[g][k]);for(k=0;k<e;k++)for(g=0;g<c.length;g++)k<i[g].length&&(d[n++]=i[g][k]);return d};s=4;for(var j={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,
78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var c=a<<10;0<=j.getBCHDigit(c)-j.getBCHDigit(j.G15);)c^=j.G15<<j.getBCHDigit(c)-j.getBCHDigit(j.G15);return(a<<10|c)^j.G15_MASK},getBCHTypeNumber:function(a){for(var c=a<<12;0<=j.getBCHDigit(c)-
j.getBCHDigit(j.G18);)c^=j.G18<<j.getBCHDigit(c)-j.getBCHDigit(j.G18);return a<<12|c},getBCHDigit:function(a){for(var c=0;0!=a;)c++,a>>>=1;return c},getPatternPosition:function(a){return j.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,c,d){switch(a){case 0:return 0==(c+d)%2;case 1:return 0==c%2;case 2:return 0==d%3;case 3:return 0==(c+d)%3;case 4:return 0==(Math.floor(c/2)+Math.floor(d/3))%2;case 5:return 0==c*d%2+c*d%3;case 6:return 0==(c*d%2+c*d%3)%2;case 7:return 0==(c*d%3+(c+d)%2)%2;default:throw Error("bad maskPattern:"+
a);}},getErrorCorrectPolynomial:function(a){for(var c=new q([1],0),d=0;d<a;d++)c=c.multiply(new q([1,l.gexp(d)],0));return c},getLengthInBits:function(a,c){if(1<=c&&10>c)switch(a){case 1:return 10;case 2:return 9;case s:return 8;case 8:return 8;default:throw Error("mode:"+a);}else if(27>c)switch(a){case 1:return 12;case 2:return 11;case s:return 16;case 8:return 10;default:throw Error("mode:"+a);}else if(41>c)switch(a){case 1:return 14;case 2:return 13;case s:return 16;case 8:return 12;default:throw Error("mode:"+
a);}else throw Error("type:"+c);},getLostPoint:function(a){for(var c=a.getModuleCount(),d=0,b=0;b<c;b++)for(var e=0;e<c;e++){for(var f=0,i=a.isDark(b,e),g=-1;1>=g;g++)if(!(0>b+g||c<=b+g))for(var h=-1;1>=h;h++)0>e+h||c<=e+h||0==g&&0==h||i==a.isDark(b+g,e+h)&&f++;5<f&&(d+=3+f-5)}for(b=0;b<c-1;b++)for(e=0;e<c-1;e++)if(f=0,a.isDark(b,e)&&f++,a.isDark(b+1,e)&&f++,a.isDark(b,e+1)&&f++,a.isDark(b+1,e+1)&&f++,0==f||4==f)d+=3;for(b=0;b<c;b++)for(e=0;e<c-6;e++)a.isDark(b,e)&&!a.isDark(b,e+1)&&a.isDark(b,e+
2)&&a.isDark(b,e+3)&&a.isDark(b,e+4)&&!a.isDark(b,e+5)&&a.isDark(b,e+6)&&(d+=40);for(e=0;e<c;e++)for(b=0;b<c-6;b++)a.isDark(b,e)&&!a.isDark(b+1,e)&&a.isDark(b+2,e)&&a.isDark(b+3,e)&&a.isDark(b+4,e)&&!a.isDark(b+5,e)&&a.isDark(b+6,e)&&(d+=40);for(e=f=0;e<c;e++)for(b=0;b<c;b++)a.isDark(b,e)&&f++;a=Math.abs(100*f/c/c-50)/5;return d+10*a}},l={glog:function(a){if(1>a)throw Error("glog("+a+")");return l.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;256<=a;)a-=255;return l.EXP_TABLE[a]},EXP_TABLE:Array(256),
LOG_TABLE:Array(256)},m=0;8>m;m++)l.EXP_TABLE[m]=1<<m;for(m=8;256>m;m++)l.EXP_TABLE[m]=l.EXP_TABLE[m-4]^l.EXP_TABLE[m-5]^l.EXP_TABLE[m-6]^l.EXP_TABLE[m-8];for(m=0;255>m;m++)l.LOG_TABLE[l.EXP_TABLE[m]]=m;q.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var c=Array(this.getLength()+a.getLength()-1),d=0;d<this.getLength();d++)for(var b=0;b<a.getLength();b++)c[d+b]^=l.gexp(l.glog(this.get(d))+l.glog(a.get(b)));return new q(c,0)},mod:function(a){if(0>
this.getLength()-a.getLength())return this;for(var c=l.glog(this.get(0))-l.glog(a.get(0)),d=Array(this.getLength()),b=0;b<this.getLength();b++)d[b]=this.get(b);for(b=0;b<a.getLength();b++)d[b]^=l.gexp(l.glog(a.get(b))+c);return(new q(d,0)).mod(a)}};p.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],
[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,
116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,
43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,
3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,
55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,
45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];p.getRSBlocks=function(a,c){var d=p.getRsBlockTable(a,c);if(void 0==d)throw Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+c);for(var b=d.length/3,e=[],f=0;f<b;f++)for(var h=d[3*f+0],g=d[3*f+1],j=d[3*f+2],l=0;l<h;l++)e.push(new p(g,j));return e};p.getRsBlockTable=function(a,c){switch(c){case 1:return p.RS_BLOCK_TABLE[4*(a-1)+0];case 0:return p.RS_BLOCK_TABLE[4*(a-1)+1];case 3:return p.RS_BLOCK_TABLE[4*
(a-1)+2];case 2:return p.RS_BLOCK_TABLE[4*(a-1)+3]}};t.prototype={get:function(a){return 1==(this.buffer[Math.floor(a/8)]>>>7-a%8&1)},put:function(a,c){for(var d=0;d<c;d++)this.putBit(1==(a>>>c-d-1&1))},getLengthInBits:function(){return this.length},putBit:function(a){var c=Math.floor(this.length/8);this.buffer.length<=c&&this.buffer.push(0);a&&(this.buffer[c]|=128>>>this.length%8);this.length++}};"string"===typeof h&&(h={text:h});h=r.extend({},{render:"canvas",width:256,height:256,typeNumber:-1,
correctLevel:2,background:"#ffffff",foreground:"#000000"},h);return this.each(function(){var a;if("canvas"==h.render){a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();var c=document.createElement("canvas");c.width=h.width;c.height=h.height;for(var d=c.getContext("2d"),b=h.width/a.getModuleCount(),e=h.height/a.getModuleCount(),f=0;f<a.getModuleCount();f++)for(var i=0;i<a.getModuleCount();i++){d.fillStyle=a.isDark(f,i)?h.foreground:h.background;var g=Math.ceil((i+1)*b)-Math.floor(i*b),
j=Math.ceil((f+1)*b)-Math.floor(f*b);d.fillRect(Math.round(i*b),Math.round(f*e),g,j)}}else{a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();c=r("<table></table>").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e<a.getModuleCount();e++){f=r("<tr></tr>").css("height",b+"px").appendTo(c);for(i=0;i<a.getModuleCount();i++)r("<td></td>").css("width",
d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;jQuery(a).appendTo(this)})}})(jQuery);
(function(r){r.fn.qrcode=function(h){var s;function u(a){this.mode=s;this.data=a}function o(a,c){this.typeNumber=a;this.errorCorrectLevel=c;this.modules=null;this.moduleCount=0;this.dataCache=null;this.dataList=[]}function q(a,c){if(void 0==a.length)throw Error(a.length+"/"+c);for(var d=0;d<a.length&&0==a[d];)d++;this.num=Array(a.length-d+c);for(var b=0;b<a.length-d;b++)this.num[b]=a[b+d]}function p(a,c){this.totalCount=a;this.dataCount=c}function t(){this.buffer=[];this.length=0}u.prototype={getLength:function(){return this.data.length},
write:function(a){for(var c=0;c<this.data.length;c++)a.put(this.data.charCodeAt(c),8)}};o.prototype={addData:function(a){this.dataList.push(new u(a));this.dataCache=null},isDark:function(a,c){if(0>a||this.moduleCount<=a||0>c||this.moduleCount<=c)throw Error(a+","+c);return this.modules[a][c]},getModuleCount:function(){return this.moduleCount},make:function(){if(1>this.typeNumber){for(var a=1,a=1;40>a;a++){for(var c=p.getRSBlocks(a,this.errorCorrectLevel),d=new t,b=0,e=0;e<c.length;e++)b+=c[e].dataCount;
for(e=0;e<this.dataList.length;e++)c=this.dataList[e],d.put(c.mode,4),d.put(c.getLength(),j.getLengthInBits(c.mode,a)),c.write(d);if(d.getLengthInBits()<=8*b)break}this.typeNumber=a}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(a,c){this.moduleCount=4*this.typeNumber+17;this.modules=Array(this.moduleCount);for(var d=0;d<this.moduleCount;d++){this.modules[d]=Array(this.moduleCount);for(var b=0;b<this.moduleCount;b++)this.modules[d][b]=null}this.setupPositionProbePattern(0,0);this.setupPositionProbePattern(this.moduleCount-
7,0);this.setupPositionProbePattern(0,this.moduleCount-7);this.setupPositionAdjustPattern();this.setupTimingPattern();this.setupTypeInfo(a,c);7<=this.typeNumber&&this.setupTypeNumber(a);null==this.dataCache&&(this.dataCache=o.createData(this.typeNumber,this.errorCorrectLevel,this.dataList));this.mapData(this.dataCache,c)},setupPositionProbePattern:function(a,c){for(var d=-1;7>=d;d++)if(!(-1>=a+d||this.moduleCount<=a+d))for(var b=-1;7>=b;b++)-1>=c+b||this.moduleCount<=c+b||(this.modules[a+d][c+b]=
0<=d&&6>=d&&(0==b||6==b)||0<=b&&6>=b&&(0==d||6==d)||2<=d&&4>=d&&2<=b&&4>=b?!0:!1)},getBestMaskPattern:function(){for(var a=0,c=0,d=0;8>d;d++){this.makeImpl(!0,d);var b=j.getLostPoint(this);if(0==d||a>b)a=b,c=d}return c},createMovieClip:function(a,c,d){a=a.createEmptyMovieClip(c,d);this.make();for(c=0;c<this.modules.length;c++)for(var d=1*c,b=0;b<this.modules[c].length;b++){var e=1*b;this.modules[c][b]&&(a.beginFill(0,100),a.moveTo(e,d),a.lineTo(e+1,d),a.lineTo(e+1,d+1),a.lineTo(e,d+1),a.endFill())}return a},
setupTimingPattern:function(){for(var a=8;a<this.moduleCount-8;a++)null==this.modules[a][6]&&(this.modules[a][6]=0==a%2);for(a=8;a<this.moduleCount-8;a++)null==this.modules[6][a]&&(this.modules[6][a]=0==a%2)},setupPositionAdjustPattern:function(){for(var a=j.getPatternPosition(this.typeNumber),c=0;c<a.length;c++)for(var d=0;d<a.length;d++){var b=a[c],e=a[d];if(null==this.modules[b][e])for(var f=-2;2>=f;f++)for(var i=-2;2>=i;i++)this.modules[b+f][e+i]=-2==f||2==f||-2==i||2==i||0==f&&0==i?!0:!1}},setupTypeNumber:function(a){for(var c=
j.getBCHTypeNumber(this.typeNumber),d=0;18>d;d++){var b=!a&&1==(c>>d&1);this.modules[Math.floor(d/3)][d%3+this.moduleCount-8-3]=b}for(d=0;18>d;d++)b=!a&&1==(c>>d&1),this.modules[d%3+this.moduleCount-8-3][Math.floor(d/3)]=b},setupTypeInfo:function(a,c){for(var d=j.getBCHTypeInfo(this.errorCorrectLevel<<3|c),b=0;15>b;b++){var e=!a&&1==(d>>b&1);6>b?this.modules[b][8]=e:8>b?this.modules[b+1][8]=e:this.modules[this.moduleCount-15+b][8]=e}for(b=0;15>b;b++)e=!a&&1==(d>>b&1),8>b?this.modules[8][this.moduleCount-
b-1]=e:9>b?this.modules[8][15-b-1+1]=e:this.modules[8][15-b-1]=e;this.modules[this.moduleCount-8][8]=!a},mapData:function(a,c){for(var d=-1,b=this.moduleCount-1,e=7,f=0,i=this.moduleCount-1;0<i;i-=2)for(6==i&&i--;;){for(var g=0;2>g;g++)if(null==this.modules[b][i-g]){var n=!1;f<a.length&&(n=1==(a[f]>>>e&1));j.getMask(c,b,i-g)&&(n=!n);this.modules[b][i-g]=n;e--; -1==e&&(f++,e=7)}b+=d;if(0>b||this.moduleCount<=b){b-=d;d=-d;break}}}};o.PAD0=236;o.PAD1=17;o.createData=function(a,c,d){for(var c=p.getRSBlocks(a,
c),b=new t,e=0;e<d.length;e++){var f=d[e];b.put(f.mode,4);b.put(f.getLength(),j.getLengthInBits(f.mode,a));f.write(b)}for(e=a=0;e<c.length;e++)a+=c[e].dataCount;if(b.getLengthInBits()>8*a)throw Error("code length overflow. ("+b.getLengthInBits()+">"+8*a+")");for(b.getLengthInBits()+4<=8*a&&b.put(0,4);0!=b.getLengthInBits()%8;)b.putBit(!1);for(;!(b.getLengthInBits()>=8*a);){b.put(o.PAD0,8);if(b.getLengthInBits()>=8*a)break;b.put(o.PAD1,8)}return o.createBytes(b,c)};o.createBytes=function(a,c){for(var d=
0,b=0,e=0,f=Array(c.length),i=Array(c.length),g=0;g<c.length;g++){var n=c[g].dataCount,h=c[g].totalCount-n,b=Math.max(b,n),e=Math.max(e,h);f[g]=Array(n);for(var k=0;k<f[g].length;k++)f[g][k]=255&a.buffer[k+d];d+=n;k=j.getErrorCorrectPolynomial(h);n=(new q(f[g],k.getLength()-1)).mod(k);i[g]=Array(k.getLength()-1);for(k=0;k<i[g].length;k++)h=k+n.getLength()-i[g].length,i[g][k]=0<=h?n.get(h):0}for(k=g=0;k<c.length;k++)g+=c[k].totalCount;d=Array(g);for(k=n=0;k<b;k++)for(g=0;g<c.length;g++)k<f[g].length&&
(d[n++]=f[g][k]);for(k=0;k<e;k++)for(g=0;g<c.length;g++)k<i[g].length&&(d[n++]=i[g][k]);return d};s=4;for(var j={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,
78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(a){for(var c=a<<10;0<=j.getBCHDigit(c)-j.getBCHDigit(j.G15);)c^=j.G15<<j.getBCHDigit(c)-j.getBCHDigit(j.G15);return(a<<10|c)^j.G15_MASK},getBCHTypeNumber:function(a){for(var c=a<<12;0<=j.getBCHDigit(c)-
j.getBCHDigit(j.G18);)c^=j.G18<<j.getBCHDigit(c)-j.getBCHDigit(j.G18);return a<<12|c},getBCHDigit:function(a){for(var c=0;0!=a;)c++,a>>>=1;return c},getPatternPosition:function(a){return j.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,c,d){switch(a){case 0:return 0==(c+d)%2;case 1:return 0==c%2;case 2:return 0==d%3;case 3:return 0==(c+d)%3;case 4:return 0==(Math.floor(c/2)+Math.floor(d/3))%2;case 5:return 0==c*d%2+c*d%3;case 6:return 0==(c*d%2+c*d%3)%2;case 7:return 0==(c*d%3+(c+d)%2)%2;default:throw Error("bad maskPattern:"+
a);}},getErrorCorrectPolynomial:function(a){for(var c=new q([1],0),d=0;d<a;d++)c=c.multiply(new q([1,l.gexp(d)],0));return c},getLengthInBits:function(a,c){if(1<=c&&10>c)switch(a){case 1:return 10;case 2:return 9;case s:return 8;case 8:return 8;default:throw Error("mode:"+a);}else if(27>c)switch(a){case 1:return 12;case 2:return 11;case s:return 16;case 8:return 10;default:throw Error("mode:"+a);}else if(41>c)switch(a){case 1:return 14;case 2:return 13;case s:return 16;case 8:return 12;default:throw Error("mode:"+
a);}else throw Error("type:"+c);},getLostPoint:function(a){for(var c=a.getModuleCount(),d=0,b=0;b<c;b++)for(var e=0;e<c;e++){for(var f=0,i=a.isDark(b,e),g=-1;1>=g;g++)if(!(0>b+g||c<=b+g))for(var h=-1;1>=h;h++)0>e+h||c<=e+h||0==g&&0==h||i==a.isDark(b+g,e+h)&&f++;5<f&&(d+=3+f-5)}for(b=0;b<c-1;b++)for(e=0;e<c-1;e++)if(f=0,a.isDark(b,e)&&f++,a.isDark(b+1,e)&&f++,a.isDark(b,e+1)&&f++,a.isDark(b+1,e+1)&&f++,0==f||4==f)d+=3;for(b=0;b<c;b++)for(e=0;e<c-6;e++)a.isDark(b,e)&&!a.isDark(b,e+1)&&a.isDark(b,e+
2)&&a.isDark(b,e+3)&&a.isDark(b,e+4)&&!a.isDark(b,e+5)&&a.isDark(b,e+6)&&(d+=40);for(e=0;e<c;e++)for(b=0;b<c-6;b++)a.isDark(b,e)&&!a.isDark(b+1,e)&&a.isDark(b+2,e)&&a.isDark(b+3,e)&&a.isDark(b+4,e)&&!a.isDark(b+5,e)&&a.isDark(b+6,e)&&(d+=40);for(e=f=0;e<c;e++)for(b=0;b<c;b++)a.isDark(b,e)&&f++;a=Math.abs(100*f/c/c-50)/5;return d+10*a}},l={glog:function(a){if(1>a)throw Error("glog("+a+")");return l.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;256<=a;)a-=255;return l.EXP_TABLE[a]},EXP_TABLE:Array(256),
LOG_TABLE:Array(256)},m=0;8>m;m++)l.EXP_TABLE[m]=1<<m;for(m=8;256>m;m++)l.EXP_TABLE[m]=l.EXP_TABLE[m-4]^l.EXP_TABLE[m-5]^l.EXP_TABLE[m-6]^l.EXP_TABLE[m-8];for(m=0;255>m;m++)l.LOG_TABLE[l.EXP_TABLE[m]]=m;q.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var c=Array(this.getLength()+a.getLength()-1),d=0;d<this.getLength();d++)for(var b=0;b<a.getLength();b++)c[d+b]^=l.gexp(l.glog(this.get(d))+l.glog(a.get(b)));return new q(c,0)},mod:function(a){if(0>
this.getLength()-a.getLength())return this;for(var c=l.glog(this.get(0))-l.glog(a.get(0)),d=Array(this.getLength()),b=0;b<this.getLength();b++)d[b]=this.get(b);for(b=0;b<a.getLength();b++)d[b]^=l.gexp(l.glog(a.get(b))+c);return(new q(d,0)).mod(a)}};p.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],
[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,
116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,
43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,
3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,
55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,
45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];p.getRSBlocks=function(a,c){var d=p.getRsBlockTable(a,c);if(void 0==d)throw Error("bad rs block @ typeNumber:"+a+"/errorCorrectLevel:"+c);for(var b=d.length/3,e=[],f=0;f<b;f++)for(var h=d[3*f+0],g=d[3*f+1],j=d[3*f+2],l=0;l<h;l++)e.push(new p(g,j));return e};p.getRsBlockTable=function(a,c){switch(c){case 1:return p.RS_BLOCK_TABLE[4*(a-1)+0];case 0:return p.RS_BLOCK_TABLE[4*(a-1)+1];case 3:return p.RS_BLOCK_TABLE[4*
(a-1)+2];case 2:return p.RS_BLOCK_TABLE[4*(a-1)+3]}};t.prototype={get:function(a){return 1==(this.buffer[Math.floor(a/8)]>>>7-a%8&1)},put:function(a,c){for(var d=0;d<c;d++)this.putBit(1==(a>>>c-d-1&1))},getLengthInBits:function(){return this.length},putBit:function(a){var c=Math.floor(this.length/8);this.buffer.length<=c&&this.buffer.push(0);a&&(this.buffer[c]|=128>>>this.length%8);this.length++}};"string"===typeof h&&(h={text:h});h=r.extend({},{render:"canvas",width:256,height:256,typeNumber:-1,
correctLevel:2,background:"#ffffff",foreground:"#000000"},h);return this.each(function(){var a;if("canvas"==h.render){a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();var c=document.createElement("canvas");c.width=h.width;c.height=h.height;for(var d=c.getContext("2d"),b=h.width/a.getModuleCount(),e=h.height/a.getModuleCount(),f=0;f<a.getModuleCount();f++)for(var i=0;i<a.getModuleCount();i++){d.fillStyle=a.isDark(f,i)?h.foreground:h.background;var g=Math.ceil((i+1)*b)-Math.floor(i*b),
j=Math.ceil((f+1)*b)-Math.floor(f*b);d.fillRect(Math.round(i*b),Math.round(f*e),g,j)}}else{a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();c=r("<table></table>").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e<a.getModuleCount();e++){f=r("<tr></tr>").css("height",b+"px").appendTo(c);for(i=0;i<a.getModuleCount();i++)r("<td></td>").css("width",
d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;jQuery(a).appendTo(this)})}})(jQuery);

View file

@ -1,272 +1,272 @@
<?php
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 [
PluginTags::$RECOMMENDED,
PluginTags::$LIVE,
PluginTags::$PLAYER,
PluginTags::$STORAGE,
];
}
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 "
. "content without slow loading times";
$txt .= "<br>If you are using the CDN Storage, add this into your crontab <code>2 1 * * * php {$global['systemRootPath']}plugin/CDN/tools/moveMissingFiles.php</code>. "
. "This command will daily check your files and free some space into your server";
$help = "";
return $txt . $help;
}
public function getName()
{
return "CDN";
}
public function getUUID()
{
return "CDN73225-3807-4167-ba81-0509dd280e06";
}
public function getPluginVersion()
{
return "2.0";
}
public function getEmptyDataObject()
{
global $global, $config;
$obj = new stdClass();
$obj->key = "";
$obj->CDN = "";
$obj->CDN_S3 = "";
$obj->CDN_B2 = "";
$obj->CDN_FTP = "";
// this is a JSON with site_id + URL
$obj->CDN_YPTStorage = ""; // array
$obj->CDN_Live = "";
// this is a JSON with servers_id + URL
$obj->CDN_LiveServers = ""; // array
$obj->enable_storage = false;
$obj->storage_autoupload_new_videos = true;
$obj->storage_users_can_choose_storage = true;
$obj->storage_username = "";
$obj->storage_password = "";
$obj->storage_hostname = "";
return $obj;
}
public function getVideosManagerListButton()
{
$btn = '';
$videoHLSObj = AVideoPlugin::getDataObjectIfEnabled('VideoHLS');
if(!empty($videoHLSObj)){
if (!empty($videoHLSObj->saveMP4CopyOnCDNStorageToAllowDownload) || !empty($videoHLSObj->saveMP3CopyOnCDNStorageToAllowDownload)) {
$btn .= '<button type="button" class="btn btn-default btn-light btn-sm btn-xs btn-block " onclick="avideoModalIframeSmall(webSiteRootURL+\\\'plugin/CDN/downloadButtons.php?videos_id=\'+ row.id +\'\\\');" ><i class="fas fa-download"></i> Download</button>';
}
}
if (self::userCanMoveVideoStorage()) {
$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()
{
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/CDN/pluginMenu.html';
$content = file_get_contents($fileAPIName);
$obj = $this->getDataObject();
$url = "https://youphp.tube/marketplace/CDN/iframe.php?hash={hash}";
$url = addQueryStringParameter($url, 'hash', $obj->key);
$url = addQueryStringParameter($url, 'webSiteRootURL', $global['webSiteRootURL']);
$cdnMenu = str_replace('{url}', $url, $content);
$storageMenu = '';
if (self::userCanMoveVideoStorage()) {
$fileStorageMenu = $global['systemRootPath'] . 'plugin/CDN/Storage/pluginMenu.html';
$storageMenu = file_get_contents($fileStorageMenu);
}
return $cdnMenu.$storageMenu;
}
/**
*
* @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
* @return boolean
*/
public static function getURL($type = 'CDN', $id = 0)
{
$obj = AVideoPlugin::getObjectData('CDN');
if (empty($obj->{$type})) {
return false;
}
if (isIPPrivate(getDomain())) {
_error_log('The CDN will not work under a private network $type=' . $type);
return false;
}
$url = '';
switch ($type) {
case 'CDN':
case 'CDN_S3':
case 'CDN_B2':
case 'CDN_FTP':
case 'CDN_Live':
$url = $obj->{$type};
break;
case 'CDN_LiveServers':
case 'CDN_YPTStorage':
if (!empty($id)) {
$json = _json_decode($obj->{$type});
//var_dump(!empty($json), is_object($json), is_array($json));//exit;
if (!empty($json) && (is_object($json) || is_array($json))) {
foreach ($json as $value) {
if ($value->id == $id) {
$url = $value->URLToCDN;
break;
}
}
}
}
//var_dump($url);exit;
break;
}
if (!empty($url) && isValidURL($url)) {
return addLastSlash($url);
}
return false;
}
public static function getCDN_S3URL()
{
$plugin = AVideoPlugin::getDataObjectIfEnabled('AWS_S3');
$CDN_S3 = '';
if (!empty($plugin)) {
$region = trim($plugin->region);
$bucket_name = trim($plugin->bucket_name);
$endpoint = trim($plugin->endpoint);
if (!empty($endpoint)) {
$CDN_S3 = str_replace('https://', "https://{$bucket_name}.", $endpoint);
} elseif (!empty($plugin->region)) {
$CDN_S3 = "https://{$bucket_name}.s3-accesspoint.{$region}.amazonaws.com";
}
if (!empty($resp->CDN_S3)) {
$CDN_S3 = addLastSlash($resp->CDN_S3);
}
}
return $CDN_S3;
}
public static function getCDN_B2URL()
{
$CDN_B2 = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('Blackblaze_B2');
if (!empty($plugin)) {
$b2 = new Blackblaze_B2();
$CDN_B2 = $b2->getEndpoint();
if (!empty($resp->CDN_B2)) {
$CDN_B2 = addLastSlash($resp->CDN_B2);
}
}
return $CDN_B2;
}
public static function getCDN_FTPURL()
{
$CDN_FTP = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (!empty($plugin)) {
$CDN_FTP = addLastSlash($plugin->endpoint);
}
return $CDN_FTP;
}
public static function getVideoTags($videos_id)
{
global $global;
if (empty($videos_id)) {
return [];
}
if (!Video::canEdit($videos_id)) {
return [];
}
$video = Video::getVideoLight($videos_id);
$sites_id = $video['sites_id'];
$obj = new stdClass();
$obj->label = 'Storage';
$isMoving = CDNStorage::isMoving($videos_id);
if ($isMoving) {
$obj->type = "danger";
$obj->text = '<i class="fas fa-sync fa-spin"></i> ' . __('Moving');
} elseif (empty($sites_id)) {
$obj->type = "success";
$obj->text = '<i class="fas fa-map-marker-alt"></i> ' . __('Local');
} else {
$obj->type = "warning";
$obj->text = "<i class=\"fas fa-project-diagram\"></i> " . __('Storage');
}
//var_dump($obj);exit;
return [$obj];
}
public function onEncoderNotifyIsDone($videos_id)
{
return $this->processNewVideo($videos_id);
}
public function onUploadIsDone($videos_id)
{
return $this->processNewVideo($videos_id);
}
private function processNewVideo($videos_id)
{
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if ($obj->enable_storage) {
if ($obj->storage_autoupload_new_videos) {
CDNStorage::moveLocalToRemote($videos_id, false);
}
}
}
public static function userCanMoveVideoStorage()
{
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj->enable_storage)) {
return false;
}
if (User::isAdmin()) {
return true;
}
if (!empty($obj->storage_users_can_choose_storage) && User::canUpload()) {
return true;
}
return false;
}
public function getFooterCode()
{
global $global;
if (self::userCanMoveVideoStorage()) {
include $global['systemRootPath'] . 'plugin/CDN/Storage/footer.php';
}
}
}
<?php
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 [
PluginTags::$RECOMMENDED,
PluginTags::$LIVE,
PluginTags::$PLAYER,
PluginTags::$STORAGE,
];
}
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 "
. "content without slow loading times";
$txt .= "<br>If you are using the CDN Storage, add this into your crontab <code>2 1 * * * php {$global['systemRootPath']}plugin/CDN/tools/moveMissingFiles.php</code>. "
. "This command will daily check your files and free some space into your server";
$help = "";
return $txt . $help;
}
public function getName()
{
return "CDN";
}
public function getUUID()
{
return "CDN73225-3807-4167-ba81-0509dd280e06";
}
public function getPluginVersion()
{
return "2.0";
}
public function getEmptyDataObject()
{
global $global, $config;
$obj = new stdClass();
$obj->key = "";
$obj->CDN = "";
$obj->CDN_S3 = "";
$obj->CDN_B2 = "";
$obj->CDN_FTP = "";
// this is a JSON with site_id + URL
$obj->CDN_YPTStorage = ""; // array
$obj->CDN_Live = "";
// this is a JSON with servers_id + URL
$obj->CDN_LiveServers = ""; // array
$obj->enable_storage = false;
$obj->storage_autoupload_new_videos = true;
$obj->storage_users_can_choose_storage = true;
$obj->storage_username = "";
$obj->storage_password = "";
$obj->storage_hostname = "";
return $obj;
}
public function getVideosManagerListButton()
{
$btn = '';
$videoHLSObj = AVideoPlugin::getDataObjectIfEnabled('VideoHLS');
if(!empty($videoHLSObj)){
if (!empty($videoHLSObj->saveMP4CopyOnCDNStorageToAllowDownload) || !empty($videoHLSObj->saveMP3CopyOnCDNStorageToAllowDownload)) {
$btn .= '<button type="button" class="btn btn-default btn-light btn-sm btn-xs btn-block " onclick="avideoModalIframeSmall(webSiteRootURL+\\\'plugin/CDN/downloadButtons.php?videos_id=\'+ row.id +\'\\\');" ><i class="fas fa-download"></i> Download</button>';
}
}
if (self::userCanMoveVideoStorage()) {
$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()
{
global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/CDN/pluginMenu.html';
$content = file_get_contents($fileAPIName);
$obj = $this->getDataObject();
$url = "https://youphp.tube/marketplace/CDN/iframe.php?hash={hash}";
$url = addQueryStringParameter($url, 'hash', $obj->key);
$url = addQueryStringParameter($url, 'webSiteRootURL', $global['webSiteRootURL']);
$cdnMenu = str_replace('{url}', $url, $content);
$storageMenu = '';
if (self::userCanMoveVideoStorage()) {
$fileStorageMenu = $global['systemRootPath'] . 'plugin/CDN/Storage/pluginMenu.html';
$storageMenu = file_get_contents($fileStorageMenu);
}
return $cdnMenu.$storageMenu;
}
/**
*
* @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
* @return boolean
*/
public static function getURL($type = 'CDN', $id = 0)
{
$obj = AVideoPlugin::getObjectData('CDN');
if (empty($obj->{$type})) {
return false;
}
if (isIPPrivate(getDomain())) {
_error_log('The CDN will not work under a private network $type=' . $type);
return false;
}
$url = '';
switch ($type) {
case 'CDN':
case 'CDN_S3':
case 'CDN_B2':
case 'CDN_FTP':
case 'CDN_Live':
$url = $obj->{$type};
break;
case 'CDN_LiveServers':
case 'CDN_YPTStorage':
if (!empty($id)) {
$json = _json_decode($obj->{$type});
//var_dump(!empty($json), is_object($json), is_array($json));//exit;
if (!empty($json) && (is_object($json) || is_array($json))) {
foreach ($json as $value) {
if ($value->id == $id) {
$url = $value->URLToCDN;
break;
}
}
}
}
//var_dump($url);exit;
break;
}
if (!empty($url) && isValidURL($url)) {
return addLastSlash($url);
}
return false;
}
public static function getCDN_S3URL()
{
$plugin = AVideoPlugin::getDataObjectIfEnabled('AWS_S3');
$CDN_S3 = '';
if (!empty($plugin)) {
$region = trim($plugin->region);
$bucket_name = trim($plugin->bucket_name);
$endpoint = trim($plugin->endpoint);
if (!empty($endpoint)) {
$CDN_S3 = str_replace('https://', "https://{$bucket_name}.", $endpoint);
} elseif (!empty($plugin->region)) {
$CDN_S3 = "https://{$bucket_name}.s3-accesspoint.{$region}.amazonaws.com";
}
if (!empty($resp->CDN_S3)) {
$CDN_S3 = addLastSlash($resp->CDN_S3);
}
}
return $CDN_S3;
}
public static function getCDN_B2URL()
{
$CDN_B2 = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('Blackblaze_B2');
if (!empty($plugin)) {
$b2 = new Blackblaze_B2();
$CDN_B2 = $b2->getEndpoint();
if (!empty($resp->CDN_B2)) {
$CDN_B2 = addLastSlash($resp->CDN_B2);
}
}
return $CDN_B2;
}
public static function getCDN_FTPURL()
{
$CDN_FTP = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (!empty($plugin)) {
$CDN_FTP = addLastSlash($plugin->endpoint);
}
return $CDN_FTP;
}
public static function getVideoTags($videos_id)
{
global $global;
if (empty($videos_id)) {
return [];
}
if (!Video::canEdit($videos_id)) {
return [];
}
$video = Video::getVideoLight($videos_id);
$sites_id = $video['sites_id'];
$obj = new stdClass();
$obj->label = 'Storage';
$isMoving = CDNStorage::isMoving($videos_id);
if ($isMoving) {
$obj->type = "danger";
$obj->text = '<i class="fas fa-sync fa-spin"></i> ' . __('Moving');
} elseif (empty($sites_id)) {
$obj->type = "success";
$obj->text = '<i class="fas fa-map-marker-alt"></i> ' . __('Local');
} else {
$obj->type = "warning";
$obj->text = "<i class=\"fas fa-project-diagram\"></i> " . __('Storage');
}
//var_dump($obj);exit;
return [$obj];
}
public function onEncoderNotifyIsDone($videos_id)
{
return $this->processNewVideo($videos_id);
}
public function onUploadIsDone($videos_id)
{
return $this->processNewVideo($videos_id);
}
private function processNewVideo($videos_id)
{
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if ($obj->enable_storage) {
if ($obj->storage_autoupload_new_videos) {
CDNStorage::moveLocalToRemote($videos_id, false);
}
}
}
public static function userCanMoveVideoStorage()
{
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj->enable_storage)) {
return false;
}
if (User::isAdmin()) {
return true;
}
if (!empty($obj->storage_users_can_choose_storage) && User::canUpload()) {
return true;
}
return false;
}
public function getFooterCode()
{
global $global;
if (self::userCanMoveVideoStorage()) {
include $global['systemRootPath'] . 'plugin/CDN/Storage/footer.php';
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,23 +1,23 @@
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
* The FtpException class.
* Exception thrown if an error on runtime of the FTP client occurs.
* @inheritDoc
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpException extends \Exception
{
}
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
* The FtpException class.
* Exception thrown if an error on runtime of the FTP client occurs.
* @inheritDoc
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpException extends \Exception
{
}

View file

@ -1,116 +1,116 @@
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
* Wrap the PHP FTP functions
*
* @method bool alloc() alloc(int $filesize, string &$result = null) Allocates space for a file to be uploaded
* @method bool cdup() cdup() Changes to the parent directory
* @method bool chdir() chdir(string $directory) Changes the current directory on a FTP server
* @method int chmod() chmod(int $mode, string $filename) Set permissions on a file via FTP
* @method bool close() close() Closes an FTP connection
* @method bool delete() delete(string $path) Deletes a file on the FTP server
* @method bool exec() exec(string $command) Requests execution of a command on the FTP server
* @method bool fget() fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server and saves to an open file
* @method bool fput() fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Uploads from an open file to the FTP server
* @method mixed get_option() get_option(int $option) Retrieves various runtime behaviours of the current FTP stream
* @method bool get() get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server
* @method bool login() login(string $username, string $password) Logs in to an FTP connection
* @method int mdtm() mdtm(string $remote_file) Returns the last modified time of the given file
* @method string mkdir() mkdir(string $directory) Creates a directory
* @method int nb_continue() nb_continue() Continues retrieving/sending a file (non-blocking)
* @method int nb_fget() nb_fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to an open file (non-blocking)
* @method int nb_fput() nb_fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Stores a file from an open file to the FTP server (non-blocking)
* @method int nb_get() nb_get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to a local file (non-blocking)
* @method int nb_put() nb_put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Stores a file on the FTP server (non-blocking)
* @method array nlist() nlist(string $directory) Returns a list of files in the given directory
* @method bool pasv() pasv(bool $pasv) Turns passive mode on or off
* @method bool put() put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Uploads a file to the FTP server
* @method string pwd() pwd() Returns the current directory name
* @method bool quit() quit() Closes an FTP connection
* @method array raw() raw(string $command) Sends an arbitrary command to an FTP server
* @method array rawlist() rawlist(string $directory, bool $recursive = false) Returns a detailed list of files in the given directory
* @method bool rename() rename(string $oldname, string $newname) Renames a file or a directory on the FTP server
* @method bool rmdir() rmdir(string $directory) Removes a directory
* @method bool set_option() set_option(int $option, mixed $value) Set miscellaneous runtime FTP options
* @method bool site() site(string $command) Sends a SITE command to the server
* @method int size() size(string $remote_file) Returns the size of the given file
* @method string systype() systype() Returns the system type identifier of the remote FTP server
*
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpWrapper
{
/**
* The connection with the server
*
* @var resource
*/
protected $conn;
/**
* Constructor.
*
* @param resource &$connection The FTP (or SSL-FTP) connection (takes by reference).
*/
public function __construct(&$connection)
{
$this->conn = &$connection;
}
/**
* Forward the method call to FTP functions
*
* @param string $function
* @param array $arguments
* @return mixed
* @throws FtpException When the function is not valid
*/
public function __call($function, array $arguments)
{
$function = 'ftp_' . $function;
if (function_exists($function)) {
array_unshift($arguments, $this->conn);
return call_user_func_array($function, $arguments);
}
throw new FtpException("{$function} is not a valid FTP function");
}
/**
* Opens a FTP connection
*
* @param string $host
* @param int $port
* @param int $timeout
* @return resource
*/
public function connect($host, $port = 21, $timeout = 90)
{
return ftp_connect($host, $port, $timeout);
}
/**
* Opens a Secure SSL-FTP connection
* @param string $host
* @param int $port
* @param int $timeout
* @return resource
*/
public function ssl_connect($host, $port = 21, $timeout = 90)
{
return ftp_ssl_connect($host, $port, $timeout);
}
}
<?php
/*
* This file is part of the `nicolab/php-ftp-client` package.
*
* (c) Nicolas Tallefourtane <dev@nicolab.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Nicolas Tallefourtane http://nicolab.net
*/
namespace FtpClient;
/**
* Wrap the PHP FTP functions
*
* @method bool alloc() alloc(int $filesize, string &$result = null) Allocates space for a file to be uploaded
* @method bool cdup() cdup() Changes to the parent directory
* @method bool chdir() chdir(string $directory) Changes the current directory on a FTP server
* @method int chmod() chmod(int $mode, string $filename) Set permissions on a file via FTP
* @method bool close() close() Closes an FTP connection
* @method bool delete() delete(string $path) Deletes a file on the FTP server
* @method bool exec() exec(string $command) Requests execution of a command on the FTP server
* @method bool fget() fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server and saves to an open file
* @method bool fput() fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Uploads from an open file to the FTP server
* @method mixed get_option() get_option(int $option) Retrieves various runtime behaviours of the current FTP stream
* @method bool get() get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Downloads a file from the FTP server
* @method bool login() login(string $username, string $password) Logs in to an FTP connection
* @method int mdtm() mdtm(string $remote_file) Returns the last modified time of the given file
* @method string mkdir() mkdir(string $directory) Creates a directory
* @method int nb_continue() nb_continue() Continues retrieving/sending a file (non-blocking)
* @method int nb_fget() nb_fget(resource $handle, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to an open file (non-blocking)
* @method int nb_fput() nb_fput(string $remote_file, resource $handle, int $mode, int $startpos = 0) Stores a file from an open file to the FTP server (non-blocking)
* @method int nb_get() nb_get(string $local_file, string $remote_file, int $mode, int $resumepos = 0) Retrieves a file from the FTP server and writes it to a local file (non-blocking)
* @method int nb_put() nb_put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Stores a file on the FTP server (non-blocking)
* @method array nlist() nlist(string $directory) Returns a list of files in the given directory
* @method bool pasv() pasv(bool $pasv) Turns passive mode on or off
* @method bool put() put(string $remote_file, string $local_file, int $mode, int $startpos = 0) Uploads a file to the FTP server
* @method string pwd() pwd() Returns the current directory name
* @method bool quit() quit() Closes an FTP connection
* @method array raw() raw(string $command) Sends an arbitrary command to an FTP server
* @method array rawlist() rawlist(string $directory, bool $recursive = false) Returns a detailed list of files in the given directory
* @method bool rename() rename(string $oldname, string $newname) Renames a file or a directory on the FTP server
* @method bool rmdir() rmdir(string $directory) Removes a directory
* @method bool set_option() set_option(int $option, mixed $value) Set miscellaneous runtime FTP options
* @method bool site() site(string $command) Sends a SITE command to the server
* @method int size() size(string $remote_file) Returns the size of the given file
* @method string systype() systype() Returns the system type identifier of the remote FTP server
*
* @author Nicolas Tallefourtane <dev@nicolab.net>
*/
class FtpWrapper
{
/**
* The connection with the server
*
* @var resource
*/
protected $conn;
/**
* Constructor.
*
* @param resource &$connection The FTP (or SSL-FTP) connection (takes by reference).
*/
public function __construct(&$connection)
{
$this->conn = &$connection;
}
/**
* Forward the method call to FTP functions
*
* @param string $function
* @param array $arguments
* @return mixed
* @throws FtpException When the function is not valid
*/
public function __call($function, array $arguments)
{
$function = 'ftp_' . $function;
if (function_exists($function)) {
array_unshift($arguments, $this->conn);
return call_user_func_array($function, $arguments);
}
throw new FtpException("{$function} is not a valid FTP function");
}
/**
* Opens a FTP connection
*
* @param string $host
* @param int $port
* @param int $timeout
* @return resource
*/
public function connect($host, $port = 21, $timeout = 90)
{
return ftp_connect($host, $port, $timeout);
}
/**
* Opens a Secure SSL-FTP connection
* @param string $host
* @param int $port
* @param int $timeout
* @return resource
*/
public function ssl_connect($host, $port = 21, $timeout = 90)
{
return ftp_ssl_connect($host, $port, $timeout);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,10 @@
<script>
function socketCDNStorageMoved(json) {
var element = $("#grid.videosManager");
if(element.length && typeof element.bootgrid === 'function'){
console.log('socketCDNStorageMoved', json);
avideoToastSuccess(json);
element.bootgrid('reload');
}
}
<script>
function socketCDNStorageMoved(json) {
var element = $("#grid.videosManager");
if(element.length && typeof element.bootgrid === 'function'){
console.log('socketCDNStorageMoved', json);
avideoToastSuccess(json);
element.bootgrid('reload');
}
}
</script>

View file

@ -1,77 +1,77 @@
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<i class="fas fa-project-diagram"></i> <span class="hidden-md hidden-sm hidden-xs"><?php echo __('Storage'); ?></span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="#" onclick="uploadSelected(); return false;">
<i class="fas fa-cloud-upload-alt"></i>
<?php echo __('Upload selected'); ?>
</a>
</li>
<li>
<a href="#" onclick="downloadSelected(); return false;">
<i class="fas fa-cloud-download-alt"></i>
<?php echo __('Download selected'); ?>
</a>
</li>
</ul>
</div>
<script>
function uploadSelected() {
var videos_ids = getSelectedVideos();
if (videos_ids.length === 0) {
avideoAlertError("Please select some videos");
return false;
}
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveLocalToRemote.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': videos_ids
},
success: function (response) {
console.log('uploadSelected', response);
}
});
setTimeout(function () {
modal.hidePleaseWait();
avideoToastSuccess('<?php echo __("Processing!"); ?>');
$("#grid").bootgrid('reload');
}, 1000);
}
function downloadSelected() {
var videos_ids = getSelectedVideos();
if (videos_ids.length === 0) {
avideoAlertError("Please select some videos");
return false;
}
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveRemoteToLocal.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': videos_ids
},
success: function (response) {
console.log('uploadSelected', response);
}
});
setTimeout(function () {
modal.hidePleaseWait();
avideoToastSuccess('<?php echo __("Processing!"); ?>');
$("#grid").bootgrid('reload');
}, 1000);
}
</script>
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<i class="fas fa-project-diagram"></i> <span class="hidden-md hidden-sm hidden-xs"><?php echo __('Storage'); ?></span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="#" onclick="uploadSelected(); return false;">
<i class="fas fa-cloud-upload-alt"></i>
<?php echo __('Upload selected'); ?>
</a>
</li>
<li>
<a href="#" onclick="downloadSelected(); return false;">
<i class="fas fa-cloud-download-alt"></i>
<?php echo __('Download selected'); ?>
</a>
</li>
</ul>
</div>
<script>
function uploadSelected() {
var videos_ids = getSelectedVideos();
if (videos_ids.length === 0) {
avideoAlertError("Please select some videos");
return false;
}
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveLocalToRemote.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': videos_ids
},
success: function (response) {
console.log('uploadSelected', response);
}
});
setTimeout(function () {
modal.hidePleaseWait();
avideoToastSuccess('<?php echo __("Processing!"); ?>');
$("#grid").bootgrid('reload');
}, 1000);
}
function downloadSelected() {
var videos_ids = getSelectedVideos();
if (videos_ids.length === 0) {
avideoAlertError("Please select some videos");
return false;
}
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveRemoteToLocal.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': videos_ids
},
success: function (response) {
console.log('uploadSelected', response);
}
});
setTimeout(function () {
modal.hidePleaseWait();
avideoToastSuccess('<?php echo __("Processing!"); ?>');
$("#grid").bootgrid('reload');
}, 1000);
}
</script>

View file

@ -1,46 +1,46 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
session_write_close();
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$isEnabled = AVideoPlugin::isEnabledByName('CDN');
if (!$isEnabled) {
$obj->msg = "CDN is disabled";
die(json_encode($obj));
}
if (empty($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = intval(@$argv[1]);
}
if (empty($_REQUEST['videos_id'])) {
$obj->msg = "Video ID is empty ";
_error_log("{$obj->msg} ".json_encode($_REQUEST));
die(json_encode($obj));
}
if (!is_array($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = [$_REQUEST['videos_id']];
}
_error_log('Start to move file ');
foreach ($_REQUEST['videos_id'] as $videos_id) {
if (!isCommandLineInterface()) {
if (!Video::canEdit($videos_id)) {
$obj->error = true;
$obj->msg = "Command line only";
die(json_encode($obj));
}
}
$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);
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
session_write_close();
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$isEnabled = AVideoPlugin::isEnabledByName('CDN');
if (!$isEnabled) {
$obj->msg = "CDN is disabled";
die(json_encode($obj));
}
if (empty($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = intval(@$argv[1]);
}
if (empty($_REQUEST['videos_id'])) {
$obj->msg = "Video ID is empty ";
_error_log("{$obj->msg} ".json_encode($_REQUEST));
die(json_encode($obj));
}
if (!is_array($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = [$_REQUEST['videos_id']];
}
_error_log('Start to move file ');
foreach ($_REQUEST['videos_id'] as $videos_id) {
if (!isCommandLineInterface()) {
if (!Video::canEdit($videos_id)) {
$obj->error = true;
$obj->msg = "Command line only";
die(json_encode($obj));
}
}
$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

@ -1,46 +1,46 @@
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
session_write_close();
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$isEnabled = AVideoPlugin::isEnabledByName('CDN');
if (!$isEnabled) {
$obj->msg = "CDN is disabled";
die(json_encode($obj));
}
if (empty($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = intval(@$argv[1]);
}
if (empty($_REQUEST['videos_id'])) {
$obj->msg = "Video ID is empty";
die(json_encode($obj));
}
if (!is_array($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = [$_REQUEST['videos_id']];
}
_error_log('Start to move remote to local ');
foreach ($_REQUEST['videos_id'] as $videos_id) {
if (!isCommandLineInterface()) {
if (!Video::canEdit($videos_id)) {
$obj->error = true;
$obj->msg = "Command line only";
die(json_encode($obj));
}
}
$obj->error = false;
$obj->response = CDNStorage::moveRemoteToLocal($videos_id);
}
_error_log('Finish to move remote to local ');
echo json_encode($obj);
<?php
$config = dirname(__FILE__) . '/../../../videos/configuration.php';
require_once $config;
session_write_close();
header('Content-Type: application/json');
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
$isEnabled = AVideoPlugin::isEnabledByName('CDN');
if (!$isEnabled) {
$obj->msg = "CDN is disabled";
die(json_encode($obj));
}
if (empty($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = intval(@$argv[1]);
}
if (empty($_REQUEST['videos_id'])) {
$obj->msg = "Video ID is empty";
die(json_encode($obj));
}
if (!is_array($_REQUEST['videos_id'])) {
$_REQUEST['videos_id'] = [$_REQUEST['videos_id']];
}
_error_log('Start to move remote to local ');
foreach ($_REQUEST['videos_id'] as $videos_id) {
if (!isCommandLineInterface()) {
if (!Video::canEdit($videos_id)) {
$obj->error = true;
$obj->msg = "Command line only";
die(json_encode($obj));
}
}
$obj->error = false;
$obj->response = CDNStorage::moveRemoteToLocal($videos_id);
}
_error_log('Finish to move remote to local ');
echo json_encode($obj);

View file

@ -1,19 +1,19 @@
<div class="panel panel-danger">
<div class="panel-heading">
<?php echo $video['title']; ?>
</div>
<div class="panel-body">
<i class="fas fa-sync fa-spin"></i>
<?php
echo __('Created') . ': ' . humanTimingAgo($isMoving['created'], 0, false).' ';
echo __('Modified') . ': ' . humanTimingAgo($isMoving['modified'], 0, false);
?>
</div>
<div class="panel-footer">
<?php
$file = CDNStorage::getLogFile($videos_id);
echo nl2br(file_get_contents($file));
?>
</div>
<div class="panel panel-danger">
<div class="panel-heading">
<?php echo $video['title']; ?>
</div>
<div class="panel-body">
<i class="fas fa-sync fa-spin"></i>
<?php
echo __('Created') . ': ' . humanTimingAgo($isMoving['created'], 0, false).' ';
echo __('Modified') . ': ' . humanTimingAgo($isMoving['modified'], 0, false);
?>
</div>
<div class="panel-footer">
<?php
$file = CDNStorage::getLogFile($videos_id);
echo nl2br(file_get_contents($file));
?>
</div>
</div>

View file

@ -1,100 +1,100 @@
<div class="panel panel-default">
<div class="panel-heading">
<?php echo $video['title']; ?>
</div>
<div class="panel-body">
<div class="btn-group btn-group-justified" role="group" aria-label="Basic example">
<?php
$totalL = $totalR = $totalFileSizeR = $totalFileSizeL = 0;
$list = CDNStorage::getFilesListBoth($videos_id);
$listString = [];
foreach ($list as $key => $value) {
if (!empty($value['local']['local_filesize']) && $value['local']['local_filesize'] > 20 && $value['local']['local_filesize'] > 0) {
$totalL++;
$totalFileSizeL += $value['local']['local_filesize'];
$humanSize = humanFileSize($value['local']['local_filesize']);
$listString[] = '<span class="label label-success"><i class="fas fa-map-marker-alt"></i> ' . __('Local') . '</span>';
$listString[] = '<span class="label label-primary">' . $humanSize . '</span>';
}
if (!empty($value['remote']['remote_filesize']) && $value['remote']['remote_filesize'] > 0) {
$totalR++;
$totalFileSizeR += $value['remote']['remote_filesize'];
$humanSize = humanFileSize($value['remote']['remote_filesize']);
$listString[] = '<span class="label label-warning"><i class="fas fa-project-diagram"></i> ' . __('Storage') . '</span>';
$listString[] = '<span class="label label-primary">' . $humanSize . '</span>';
}
$listString[] = " {$key} <br>";
}
if ($totalL) {
?>
<button type="button" class="btn btn-warning" onclick="CDNStorageUpload();">
<i class="fas fa-project-diagram"></i>
<?php
printf(__('Upload %d files to storage'), $totalL);
$humanSize = humanFileSize($totalFileSizeL);
echo ' (' . $humanSize . ')'; ?>
</button>
<script>
function CDNStorageUpload() {
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveLocalToRemote.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': <?php echo $videos_id; ?>
},
success: function (response) {
//modal.hidePleaseWait();
document.location.reload();
console.log('CDNStorageUpload', response);
}
});
}
</script>
<?php
}
if ($totalR) {
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 . ')'; ?>
</button>
<script>
function CDNStorageDownload() {
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveRemoteToLocal.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': <?php echo $videos_id; ?>
},
success: function (response) {
//modal.hidePleaseWait();
document.location.reload();
console.log('CDNStorageDownload', response);
}
});
}
</script>
<?php
}
?>
</div>
</div>
<div class="panel-footer" style="max-height: 440px; overflow: auto;">
<?php
echo implode('', $listString);
?>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<?php echo $video['title']; ?>
</div>
<div class="panel-body">
<div class="btn-group btn-group-justified" role="group" aria-label="Basic example">
<?php
$totalL = $totalR = $totalFileSizeR = $totalFileSizeL = 0;
$list = CDNStorage::getFilesListBoth($videos_id);
$listString = [];
foreach ($list as $key => $value) {
if (!empty($value['local']['local_filesize']) && $value['local']['local_filesize'] > 20 && $value['local']['local_filesize'] > 0) {
$totalL++;
$totalFileSizeL += $value['local']['local_filesize'];
$humanSize = humanFileSize($value['local']['local_filesize']);
$listString[] = '<span class="label label-success"><i class="fas fa-map-marker-alt"></i> ' . __('Local') . '</span>';
$listString[] = '<span class="label label-primary">' . $humanSize . '</span>';
}
if (!empty($value['remote']['remote_filesize']) && $value['remote']['remote_filesize'] > 0) {
$totalR++;
$totalFileSizeR += $value['remote']['remote_filesize'];
$humanSize = humanFileSize($value['remote']['remote_filesize']);
$listString[] = '<span class="label label-warning"><i class="fas fa-project-diagram"></i> ' . __('Storage') . '</span>';
$listString[] = '<span class="label label-primary">' . $humanSize . '</span>';
}
$listString[] = " {$key} <br>";
}
if ($totalL) {
?>
<button type="button" class="btn btn-warning" onclick="CDNStorageUpload();">
<i class="fas fa-project-diagram"></i>
<?php
printf(__('Upload %d files to storage'), $totalL);
$humanSize = humanFileSize($totalFileSizeL);
echo ' (' . $humanSize . ')'; ?>
</button>
<script>
function CDNStorageUpload() {
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveLocalToRemote.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': <?php echo $videos_id; ?>
},
success: function (response) {
//modal.hidePleaseWait();
document.location.reload();
console.log('CDNStorageUpload', response);
}
});
}
</script>
<?php
}
if ($totalR) {
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 . ')'; ?>
</button>
<script>
function CDNStorageDownload() {
modal.showPleaseWait();
var url = webSiteRootURL + 'plugin/CDN/Storage/moveRemoteToLocal.json.php';
$.ajax({
url: url,
method: 'POST',
data: {
'videos_id': <?php echo $videos_id; ?>
},
success: function (response) {
//modal.hidePleaseWait();
document.location.reload();
console.log('CDNStorageDownload', response);
}
});
}
</script>
<?php
}
?>
</div>
</div>
<div class="panel-footer" style="max-height: 440px; overflow: auto;">
<?php
echo implode('', $listString);
?>
</div>
</div>

View file

@ -1,42 +1,42 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
$videos_id = intval($_REQUEST['videos_id']);
if (empty($videos_id)) {
forbiddenPage('Videos ID is required');
}
if (!Video::canEdit($videos_id)) {
forbiddenPage('You cannot edit this video');
}
$video = Video::getVideoLight($videos_id);
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<title><?php echo $config->getWebSiteTitle(); ?> :: Move Storage</title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<?php
$isMoving = CDNStorage::isMoving($videos_id);
if (!empty($isMoving)) {
include './panelIsMoving.php';
} else {
include './panelMove.php';
}
?>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
$videos_id = intval($_REQUEST['videos_id']);
if (empty($videos_id)) {
forbiddenPage('Videos ID is required');
}
if (!Video::canEdit($videos_id)) {
forbiddenPage('You cannot edit this video');
}
$video = Video::getVideoLight($videos_id);
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<title><?php echo $config->getWebSiteTitle(); ?> :: Move Storage</title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container-fluid">
<?php
$isMoving = CDNStorage::isMoving($videos_id);
if (!empty($isMoving)) {
include './panelIsMoving.php';
} else {
include './panelMove.php';
}
?>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
</body>
</html>

View file

@ -1,43 +1,43 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once '../CDN.php';
if (!User::isAdmin()) {
die("Must be admin for testing");
}
if (!function_exists('ftp_put')) {
die("You MUST install the PHP FTP functions");
}
$obj = AVideoPlugin::getDataObject('CDN');
_error_log("CDNStorage: test start");
$tmp_name = "{$global['systemRootPath']}plugin/CDN/Storage/test.txt";
$filename = "test.txt";
$remote_file = "{$filename}";
echo '<h2>Transferring...</h2>' . PHP_EOL;
echo '<h4>Test 1 Default configuration</h4>' . PHP_EOL;
echo '<h4>Test 1 Default configuration</h4>' . PHP_EOL;
$CDNstorage = new \FtpClient\FtpClient();
$CDNstorage->connect($obj->storage_hostname);
$CDNstorage->login($obj->storage_username, $obj->storage_password);
$CDNstorage->pasv(true);
if ($CDNstorage->modifiedTime($remote_file) > 0) {
$CDNstorage->delete($filename);
if ($CDNstorage->modifiedTime($remote_file) > 0) {
die("Please first delete the file {$remote_file} from the FTP dir");
}
}
$response = $CDNstorage->put($remote_file, $tmp_name);
if ($CDNstorage->modifiedTime($remote_file) > 0) {
echo "The default configuration works";
} else {
echo '<h4>Default configuration fail</h4>' . PHP_EOL;
}
$pz = CDNStorage::getPZ();
echo "<br><a href='https://{$pz}{$filename}' target='_blank'>{$filename}</a><br>";
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
require_once '../CDN.php';
if (!User::isAdmin()) {
die("Must be admin for testing");
}
if (!function_exists('ftp_put')) {
die("You MUST install the PHP FTP functions");
}
$obj = AVideoPlugin::getDataObject('CDN');
_error_log("CDNStorage: test start");
$tmp_name = "{$global['systemRootPath']}plugin/CDN/Storage/test.txt";
$filename = "test.txt";
$remote_file = "{$filename}";
echo '<h2>Transferring...</h2>' . PHP_EOL;
echo '<h4>Test 1 Default configuration</h4>' . PHP_EOL;
echo '<h4>Test 1 Default configuration</h4>' . PHP_EOL;
$CDNstorage = new \FtpClient\FtpClient();
$CDNstorage->connect($obj->storage_hostname);
$CDNstorage->login($obj->storage_username, $obj->storage_password);
$CDNstorage->pasv(true);
if ($CDNstorage->modifiedTime($remote_file) > 0) {
$CDNstorage->delete($filename);
if ($CDNstorage->modifiedTime($remote_file) > 0) {
die("Please first delete the file {$remote_file} from the FTP dir");
}
}
$response = $CDNstorage->put($remote_file, $tmp_name);
if ($CDNstorage->modifiedTime($remote_file) > 0) {
echo "The default configuration works";
} else {
echo '<h4>Default configuration fail</h4>' . PHP_EOL;
}
$pz = CDNStorage::getPZ();
echo "<br><a href='https://{$pz}{$filename}' target='_blank'>{$filename}</a><br>";

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 = [];
$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));
<?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,47 +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,67 +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 = [];
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,77 +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 = [];
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,79 +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 = [];
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,54 +1,54 @@
<?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');
}
$_1hour = 3600;
$_2hours = $_1hour*2;
ob_end_flush();
set_time_limit($_2hours);
ini_set('max_execution_time', $_2hours);
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();
<?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');
}
$_1hour = 3600;
$_2hours = $_1hour*2;
ob_end_flush();
set_time_limit($_2hours);
ini_set('max_execution_time', $_2hours);
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,408 +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 [
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;
}
<?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

@ -1,224 +1,224 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
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;
public static function getSearchFieldsNames()
{
return ['domain', 'ishttps', 'user_location', 'timezone', 'name'];
}
public static function getTableName()
{
return 'CachesInDB';
}
public function setId($id)
{
$this->id = intval($id);
}
public function setContent($content)
{
$content = self::encodeContent($content);
$this->content = $content;
}
public function setDomain($domain)
{
$this->domain = $domain;
}
public function setIshttps($ishttps)
{
$this->ishttps = $ishttps;
}
public function setLoggedType($loggedType)
{
$this->loggedType = $loggedType;
}
public function setUser_location($user_location)
{
$this->user_location = $user_location;
}
public function setExpires($expires)
{
$this->expires = $expires;
}
public function setTimezone($timezone)
{
$this->timezone = $timezone;
}
public function setName($name)
{
$this->name = $name;
}
public function getId()
{
return intval($this->id);
}
public function getContent()
{
$this->content = self::decodeContent($this->content);
return $this->content;
}
public function getDomain()
{
return $this->domain;
}
public function getIshttps()
{
return $this->ishttps;
}
public function getLoggedType()
{
return $this->loggedType;
}
public function getUser_location()
{
return $this->user_location;
}
public function getExpires()
{
return $this->expires;
}
public function getTimezone()
{
return $this->timezone;
}
public function getName()
{
return $this->name;
}
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", [$ishttps, $loggedType, $name, $domain, $user_location], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
if (!empty($data) && !empty($data['content'])) {
$data['content'] = self::decodeContent($data['content']);
}
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function _setCache($name, $value, $domain, $ishttps, $user_location, $loggedType)
{
if (!is_string($value)) {
$value = _json_encode($value);
}
if (empty($value)) {
return false;
}
$row = self::_getCache($name, $domain, $ishttps, $user_location, $loggedType);
if (!empty($row)) {
$c = new CachesInDB($row['id']);
} else {
$c = new CachesInDB(0);
}
$c->setContent($value);
$c->setName($name);
$c->setDomain($domain);
$c->setIshttps($ishttps);
$c->setUser_location($user_location);
$c->setLoggedType($loggedType);
$c->setExpires(date('Y-m-d H:i:s', strtotime('+ 1 month')));
return $c->save();
}
public static function _deleteCache($name)
{
global $global;
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", [$name]);
}
public static function _deleteCacheStartingWith($name)
{
global $global;
if (empty($name)) {
return false;
}
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE name LIKE '{$name}%'";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql);
}
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)) {
$content = _json_encode($content);
}
$prefix = substr($content, 0, 10);
if ($prefix!== CachesInDB::$prefix) {
$base64 = base64_encode($content);
$content = CachesInDB::$prefix.$base64;
}
return $content;
}
public static function decodeContent($content)
{
$prefix = substr($content, 0, 10);
if ($prefix === CachesInDB::$prefix) {
$content = str_replace(CachesInDB::$prefix, '', $content);
$content = base64_decode($content);
}
return $content;
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
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;
public static function getSearchFieldsNames()
{
return ['domain', 'ishttps', 'user_location', 'timezone', 'name'];
}
public static function getTableName()
{
return 'CachesInDB';
}
public function setId($id)
{
$this->id = intval($id);
}
public function setContent($content)
{
$content = self::encodeContent($content);
$this->content = $content;
}
public function setDomain($domain)
{
$this->domain = $domain;
}
public function setIshttps($ishttps)
{
$this->ishttps = $ishttps;
}
public function setLoggedType($loggedType)
{
$this->loggedType = $loggedType;
}
public function setUser_location($user_location)
{
$this->user_location = $user_location;
}
public function setExpires($expires)
{
$this->expires = $expires;
}
public function setTimezone($timezone)
{
$this->timezone = $timezone;
}
public function setName($name)
{
$this->name = $name;
}
public function getId()
{
return intval($this->id);
}
public function getContent()
{
$this->content = self::decodeContent($this->content);
return $this->content;
}
public function getDomain()
{
return $this->domain;
}
public function getIshttps()
{
return $this->ishttps;
}
public function getLoggedType()
{
return $this->loggedType;
}
public function getUser_location()
{
return $this->user_location;
}
public function getExpires()
{
return $this->expires;
}
public function getTimezone()
{
return $this->timezone;
}
public function getName()
{
return $this->name;
}
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", [$ishttps, $loggedType, $name, $domain, $user_location], true);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
if (!empty($data) && !empty($data['content'])) {
$data['content'] = self::decodeContent($data['content']);
}
$row = $data;
} else {
$row = false;
}
return $row;
}
public static function _setCache($name, $value, $domain, $ishttps, $user_location, $loggedType)
{
if (!is_string($value)) {
$value = _json_encode($value);
}
if (empty($value)) {
return false;
}
$row = self::_getCache($name, $domain, $ishttps, $user_location, $loggedType);
if (!empty($row)) {
$c = new CachesInDB($row['id']);
} else {
$c = new CachesInDB(0);
}
$c->setContent($value);
$c->setName($name);
$c->setDomain($domain);
$c->setIshttps($ishttps);
$c->setUser_location($user_location);
$c->setLoggedType($loggedType);
$c->setExpires(date('Y-m-d H:i:s', strtotime('+ 1 month')));
return $c->save();
}
public static function _deleteCache($name)
{
global $global;
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", [$name]);
}
public static function _deleteCacheStartingWith($name)
{
global $global;
if (empty($name)) {
return false;
}
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE name LIKE '{$name}%'";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql);
}
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)) {
$content = _json_encode($content);
}
$prefix = substr($content, 0, 10);
if ($prefix!== CachesInDB::$prefix) {
$base64 = base64_encode($content);
$content = CachesInDB::$prefix.$base64;
}
return $content;
}
public static function decodeContent($content)
{
$prefix = substr($content, 0, 10);
if ($prefix === CachesInDB::$prefix) {
$content = str_replace(CachesInDB::$prefix, '', $content);
$content = base64_decode($content);
}
return $content;
}
}

View file

@ -1,32 +1,32 @@
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
if (!isCommandLineInterface()) {
die('Command Line only');
}
$daysLimit = 3;
// delete object cache
$cacheDir = ObjectYPT::getCacheDir();
if (empty($cacheDir) || !preg_match('/YPTObjectCache/', $cacheDir)) {
die('Wrong dir: '.$cacheDir);
}
_error_log('crontab.php: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
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);
//delete site cache
$cacheDir = getCacheDir();
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);
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
if (!isCommandLineInterface()) {
die('Command Line only');
}
$daysLimit = 3;
// delete object cache
$cacheDir = ObjectYPT::getCacheDir();
if (empty($cacheDir) || !preg_match('/YPTObjectCache/', $cacheDir)) {
die('Wrong dir: '.$cacheDir);
}
_error_log('crontab.php: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
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);
//delete site cache
$cacheDir = getCacheDir();
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);

View file

@ -1,30 +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,47 +1,47 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class Chromecast extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$FREE
);
}
public function getDescription() {
return "A plugin that adds a button to the control bar which will cast videos to a Chromecast.";
}
public function getName() {
return "Chromecast";
}
public function getUUID() {
return "cast1de9-b4f7-4462-bda6-458b0736593d";
}
public function getEmptyDataObject() {
$obj = new stdClass();
return $obj;
}
public function getHeadCode() {
global $global;
$css = "";
if (isVideo()) {
$css .= '<link href="' .getCDN() . 'plugin/Chromecast/videojs-chromecast/silvermine-videojs-chromecast.css" rel="stylesheet" type="text/css"/>';
$css .= "<style>.vjs-chromecast-button .vjs-icon-placeholder {width: 20px;height: 20px;</style>";
}
return $css;
}
public function getFooterCode() {
global $global;
if (isVideoOrAudioNotEmbed()) {
include $global['systemRootPath'] . 'plugin/Chromecast/footer.php';
}
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class Chromecast extends PluginAbstract {
public function getTags() {
return array(
PluginTags::$FREE
);
}
public function getDescription() {
return "A plugin that adds a button to the control bar which will cast videos to a Chromecast.";
}
public function getName() {
return "Chromecast";
}
public function getUUID() {
return "cast1de9-b4f7-4462-bda6-458b0736593d";
}
public function getEmptyDataObject() {
$obj = new stdClass();
return $obj;
}
public function getHeadCode() {
global $global;
$css = "";
if (isVideo()) {
$css .= '<link href="' .getCDN() . 'plugin/Chromecast/videojs-chromecast/silvermine-videojs-chromecast.css" rel="stylesheet" type="text/css"/>';
$css .= "<style>.vjs-chromecast-button .vjs-icon-placeholder {width: 20px;height: 20px;</style>";
}
return $css;
}
public function getFooterCode() {
global $global;
if (isVideoOrAudioNotEmbed()) {
include $global['systemRootPath'] . 'plugin/Chromecast/footer.php';
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,23 +1,23 @@
<?php
class CloneLog
{
public $file;
public function __construct()
{
global $global;
$clonesDir = Video::getStoragePath()."cache/clones/";
$this->file = "{$clonesDir}client.log";
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir."index.html", '');
}
file_put_contents($this->file, "");
}
public function add($message)
{
_error_log($message);
file_put_contents($this->file, $message.PHP_EOL, FILE_APPEND | LOCK_EX);
}
}
<?php
class CloneLog
{
public $file;
public function __construct()
{
global $global;
$clonesDir = Video::getStoragePath()."cache/clones/";
$this->file = "{$clonesDir}client.log";
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir."index.html", '');
}
file_put_contents($this->file, "");
}
public function add($message)
{
_error_log($message);
file_put_contents($this->file, $message.PHP_EOL, FILE_APPEND | LOCK_EX);
}
}

View file

@ -1,89 +1,89 @@
<?php
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 [
PluginTags::$SECURITY,
PluginTags::$FREE,
];
}
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()) {
$txt .= "<div class='alert alert-danger'>To use rsync feature you must install it <code>sudo apt-get install rsync</code></div>";
}
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()
{
return "CloneSite";
}
public function getUUID()
{
return "c0731de9-b4f7-4462-bda6-458b0736593d";
}
public function getPluginVersion()
{
return "1.1";
}
public function getPluginMenu()
{
global $global;
$filename = $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html';
return file_get_contents($filename);
}
public function getEmptyDataObject()
{
global $global;
$obj = new stdClass();
$obj->cloneSiteURL = "";
$obj->cloneSiteSSHIP = "";
$obj->cloneSiteSSHUser = "";
$obj->cloneSiteSSHPort = "22";
$o = new stdClass();
$o->type = "encrypted";
$o->value = "";
$obj->cloneSiteSSHPassword = $o;
$obj->useRsync = true;
$obj->MaintenanceMode = false;
$obj->myKey = md5($global['systemRootPath'].$global['salt']);
return $obj;
}
public function getStart()
{
$obj = $this->getDataObject();
if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getStart();
}
}
public function getFooterCode()
{
$obj = $this->getDataObject();
if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getFooterCode();
}
}
}
<?php
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 [
PluginTags::$SECURITY,
PluginTags::$FREE,
];
}
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()) {
$txt .= "<div class='alert alert-danger'>To use rsync feature you must install it <code>sudo apt-get install rsync</code></div>";
}
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()
{
return "CloneSite";
}
public function getUUID()
{
return "c0731de9-b4f7-4462-bda6-458b0736593d";
}
public function getPluginVersion()
{
return "1.1";
}
public function getPluginMenu()
{
global $global;
$filename = $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html';
return file_get_contents($filename);
}
public function getEmptyDataObject()
{
global $global;
$obj = new stdClass();
$obj->cloneSiteURL = "";
$obj->cloneSiteSSHIP = "";
$obj->cloneSiteSSHUser = "";
$obj->cloneSiteSSHPort = "22";
$o = new stdClass();
$o->type = "encrypted";
$o->value = "";
$obj->cloneSiteSSHPassword = $o;
$obj->useRsync = true;
$obj->MaintenanceMode = false;
$obj->myKey = md5($global['systemRootPath'].$global['salt']);
return $obj;
}
public function getStart()
{
$obj = $this->getDataObject();
if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getStart();
}
}
public function getFooterCode()
{
$obj = $this->getDataObject();
if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getFooterCode();
}
}
}

View file

@ -1,182 +1,182 @@
<?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();
}
}
<?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,211 +1,211 @@
<?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);
<?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,71 +1,71 @@
<?php
require_once '../../videos/configuration.php';
set_time_limit(0);
session_write_close();
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
header('Content-Type: application/json');
$videosDir = Video::getStoragePath()."";
$clonesDir = "{$videosDir}cache/clones/";
$photosDir = "{$videosDir}userPhoto/";
$resp = new stdClass();
$resp->error = true;
$resp->msg = "";
$resp->url = $_GET['url'];
$resp->key = $_GET['key'];
$resp->useRsync = intval($_GET['useRsync']);
$resp->videosDir = Video::getStoragePath()."";
$resp->sqlFile = "";
$resp->videoFiles = [];
$resp->photoFiles = [];
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if (empty($objClone)) {
$resp->msg = "CloneSite is not enabled on the Master site";
die(json_encode($resp));
}
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)) {
$resp->msg = $canClone->msg;
die(json_encode($resp));
}
if (!empty($_GET['deleteDump'])) {
$resp->error = !unlink("{$clonesDir}{$_GET['deleteDump']}");
$resp->msg = "Delete Dump {$_GET['deleteDump']}";
die(json_encode($resp));
}
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir."index.html", '');
}
$resp->sqlFile = uniqid('Clone_mysqlDump_').".sql";
// update this clone last request
$resp->error = !$canClone->clone->updateLastCloneRequest();
// get mysql dump
$cmd = "mysqldump -u {$mysqlUser} -p{$mysqlPass} --host {$mysqlHost} {$mysqlDatabase} > {$clonesDir}{$resp->sqlFile}";
_error_log("Clone: Dump to {$clonesDir}{$resp->sqlFile}");
exec($cmd." 2>&1", $output, $return_val);
if ($return_val !== 0) {
_error_log("Clone Error: ". print_r($output, true));
}
if (empty($resp->useRsync)) {
$resp->videoFiles = getCloneFilesInfo($videosDir);
$resp->photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
}
echo json_encode($resp);
<?php
require_once '../../videos/configuration.php';
set_time_limit(0);
session_write_close();
require_once $global['systemRootPath'] . 'plugin/CloneSite/Objects/Clones.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
header('Content-Type: application/json');
$videosDir = Video::getStoragePath()."";
$clonesDir = "{$videosDir}cache/clones/";
$photosDir = "{$videosDir}userPhoto/";
$resp = new stdClass();
$resp->error = true;
$resp->msg = "";
$resp->url = $_GET['url'];
$resp->key = $_GET['key'];
$resp->useRsync = intval($_GET['useRsync']);
$resp->videosDir = Video::getStoragePath()."";
$resp->sqlFile = "";
$resp->videoFiles = [];
$resp->photoFiles = [];
$objClone = AVideoPlugin::getObjectDataIfEnabled("CloneSite");
if (empty($objClone)) {
$resp->msg = "CloneSite is not enabled on the Master site";
die(json_encode($resp));
}
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)) {
$resp->msg = $canClone->msg;
die(json_encode($resp));
}
if (!empty($_GET['deleteDump'])) {
$resp->error = !unlink("{$clonesDir}{$_GET['deleteDump']}");
$resp->msg = "Delete Dump {$_GET['deleteDump']}";
die(json_encode($resp));
}
if (!file_exists($clonesDir)) {
mkdir($clonesDir, 0777, true);
file_put_contents($clonesDir."index.html", '');
}
$resp->sqlFile = uniqid('Clone_mysqlDump_').".sql";
// update this clone last request
$resp->error = !$canClone->clone->updateLastCloneRequest();
// get mysql dump
$cmd = "mysqldump -u {$mysqlUser} -p{$mysqlPass} --host {$mysqlHost} {$mysqlDatabase} > {$clonesDir}{$resp->sqlFile}";
_error_log("Clone: Dump to {$clonesDir}{$resp->sqlFile}");
exec($cmd." 2>&1", $output, $return_val);
if ($return_val !== 0) {
_error_log("Clone Error: ". print_r($output, true));
}
if (empty($resp->useRsync)) {
$resp->videoFiles = getCloneFilesInfo($videosDir);
$resp->photoFiles = getCloneFilesInfo($photosDir, "userPhoto/");
}
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,59 +1,59 @@
<?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'));
}
<?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

@ -1,166 +1,166 @@
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
$plugin = AVideoPlugin::loadPluginIfEnabled('CloneSite');
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("Clone Site"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<link rel="stylesheet" type="text/css" href="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.css"/>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fas fa-clone"></i> <?php echo __("Manage Clones"); ?>
</div>
<div class="panel-body">
<table id="campaignTable" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th><?php echo __("URL"); ?></th>
<th><?php echo __("Key"); ?></th>
<th><?php echo __("Last Clone"); ?></th>
<th><?php echo __("Status"); ?></th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php echo __("URL"); ?></th>
<th><?php echo __("Key"); ?></th>
<th><?php echo __("Last Clone"); ?></th>
<th><?php echo __("Status"); ?></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div id="btnModelLinks" style="display: none;">
<div class="btn-group pull-right">
<button href="" class="editor_status btn {status-class} btn-xs">
<i class="{status-icon}"></i> {status-text}
</button>
<button href="" class="editor_delete_link btn btn-danger btn-xs">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script type="text/javascript" src="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var tableLinks = $('#campaignTable').DataTable({
"ajax": "<?php echo $global['webSiteRootURL']; ?>plugin/CloneSite/clones.json.php",
"columns": [
{"data": "url"},
{"data": "key"},
{"data": "last_clone_request"},
{
data: 'status',
"render": function (data, type, full, meta) {
var content = "<span class='label label-success'>Active</span>";
if(full.status === 'i'){
content = "<span class='label label-danger'>Inactive</span>";
}
return content;
}
},
{
data: 'status',
"render": function (data, type, full, meta) {
var content = $('#btnModelLinks').html();
if(full.status === 'i'){
content = content.replace("{status-class}", "btn-success");
content = content.replace("{status-icon}", "fas fa-check-square");
content = content.replace("{status-text}", "Activate");
}else{
content = content.replace("{status-class}", "btn-default");
content = content.replace("{status-icon}", "fas fa-ban");
content = content.replace("{status-text}", "Deactivate");
}
return content;
}
}
],
select: true,
});
$('#campaignTable').on('click', 'button.editor_status', function (e) {
e.preventDefault();
var tr = $(this).closest('tr')[0];
var data = tableLinks.row(tr).data();
modal.showPleaseWait();
$.ajax({
type: "POST",
url: "<?php echo $global['webSiteRootURL']; ?>plugin/CloneSite/changeStatus.json.php",
data: data
}).done(function (resposta) {
if (resposta.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", resposta.msg, "error");
}
tableLinks.ajax.reload();
modal.hidePleaseWait();
});
});
$('#campaignTable').on('click', 'button.editor_delete_link', function (e) {
e.preventDefault();
var tr = $(this).closest('tr')[0];
var data = tableLinks.row(tr).data();
swal({
title: "<?php echo __("Are you sure?"); ?>",
text: "<?php echo __("You will not be able to recover this action!"); ?>",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(willDelete) {
if (willDelete) {
modal.showPleaseWait();
$.ajax({
type: "POST",
url: "<?php echo $global['webSiteRootURL']; ?>plugin/CloneSite/delete.json.php",
data: data
}).done(function (resposta) {
if (resposta.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", resposta.msg, "error");
}
tableLinks.ajax.reload();
modal.hidePleaseWait();
});
}
});
});
});
</script>
</body>
</html>
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php';
}
$plugin = AVideoPlugin::loadPluginIfEnabled('CloneSite');
if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<?php
echo getHTMLTitle(__("Clone Site"));
?>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<link rel="stylesheet" type="text/css" href="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.css"/>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fas fa-clone"></i> <?php echo __("Manage Clones"); ?>
</div>
<div class="panel-body">
<table id="campaignTable" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th><?php echo __("URL"); ?></th>
<th><?php echo __("Key"); ?></th>
<th><?php echo __("Last Clone"); ?></th>
<th><?php echo __("Status"); ?></th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php echo __("URL"); ?></th>
<th><?php echo __("Key"); ?></th>
<th><?php echo __("Last Clone"); ?></th>
<th><?php echo __("Status"); ?></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div id="btnModelLinks" style="display: none;">
<div class="btn-group pull-right">
<button href="" class="editor_status btn {status-class} btn-xs">
<i class="{status-icon}"></i> {status-text}
</button>
<button href="" class="editor_delete_link btn btn-danger btn-xs">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script type="text/javascript" src="<?php echo getCDN(); ?>view/css/DataTables/datatables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var tableLinks = $('#campaignTable').DataTable({
"ajax": "<?php echo $global['webSiteRootURL']; ?>plugin/CloneSite/clones.json.php",
"columns": [
{"data": "url"},
{"data": "key"},
{"data": "last_clone_request"},
{
data: 'status',
"render": function (data, type, full, meta) {
var content = "<span class='label label-success'>Active</span>";
if(full.status === 'i'){
content = "<span class='label label-danger'>Inactive</span>";
}
return content;
}
},
{
data: 'status',
"render": function (data, type, full, meta) {
var content = $('#btnModelLinks').html();
if(full.status === 'i'){
content = content.replace("{status-class}", "btn-success");
content = content.replace("{status-icon}", "fas fa-check-square");
content = content.replace("{status-text}", "Activate");
}else{
content = content.replace("{status-class}", "btn-default");
content = content.replace("{status-icon}", "fas fa-ban");
content = content.replace("{status-text}", "Deactivate");
}
return content;
}
}
],
select: true,
});
$('#campaignTable').on('click', 'button.editor_status', function (e) {
e.preventDefault();
var tr = $(this).closest('tr')[0];
var data = tableLinks.row(tr).data();
modal.showPleaseWait();
$.ajax({
type: "POST",
url: "<?php echo $global['webSiteRootURL']; ?>plugin/CloneSite/changeStatus.json.php",
data: data
}).done(function (resposta) {
if (resposta.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", resposta.msg, "error");
}
tableLinks.ajax.reload();
modal.hidePleaseWait();
});
});
$('#campaignTable').on('click', 'button.editor_delete_link', function (e) {
e.preventDefault();
var tr = $(this).closest('tr')[0];
var data = tableLinks.row(tr).data();
swal({
title: "<?php echo __("Are you sure?"); ?>",
text: "<?php echo __("You will not be able to recover this action!"); ?>",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(willDelete) {
if (willDelete) {
modal.showPleaseWait();
$.ajax({
type: "POST",
url: "<?php echo $global['webSiteRootURL']; ?>plugin/CloneSite/delete.json.php",
data: data
}).done(function (resposta) {
if (resposta.error) {
avideoAlert("<?php echo __("Sorry!"); ?>", resposta.msg, "error");
}
tableLinks.ajax.reload();
modal.hidePleaseWait();
});
}
});
});
});
</script>
</body>
</html>

View file

@ -1,59 +1,59 @@
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class CookieAlert extends PluginAbstract {
public function getDescription() {
return "EU Cookie Law Notice Plugin";
}
public function getName() {
return "CookieAlert";
}
public function getUUID() {
return "6daca392-7b14-44fb-aa33-51cba620d92e";
}
public function getPluginVersion() {
return "1.0";
}
public function getHeadCode() {
if($this->doNotShow()){
return "";
}
$obj = $this->getDataObject();
global $global;
$css = '<link href="' . getCDN() . 'plugin/CookieAlert/cookiealert.css" rel="stylesheet" type="text/css"/>';
$css .= '<style></style>';
return $css;
}
private function doNotShow(){
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
if(isEmbed() || preg_match("/embed/i", $baseName) || !empty($_GET['embed'])){
return true;
}
return false;
}
public function getEmptyDataObject() {
$obj = new stdClass();
$obj->text = '<b>This website uses cookies</b> &#x1F36A; so we can provide you with the best user experience. Without these cookies, the website simply would not work.';
$obj->btnText = 'I agree';
return $obj;
}
public function getFooterCode() {
if($this->doNotShow()){
return "";
}
$obj = $this->getDataObject();
global $global;
include $global['systemRootPath'] . 'plugin/CookieAlert/footer.php';
}
}
<?php
global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class CookieAlert extends PluginAbstract {
public function getDescription() {
return "EU Cookie Law Notice Plugin";
}
public function getName() {
return "CookieAlert";
}
public function getUUID() {
return "6daca392-7b14-44fb-aa33-51cba620d92e";
}
public function getPluginVersion() {
return "1.0";
}
public function getHeadCode() {
if($this->doNotShow()){
return "";
}
$obj = $this->getDataObject();
global $global;
$css = '<link href="' . getCDN() . 'plugin/CookieAlert/cookiealert.css" rel="stylesheet" type="text/css"/>';
$css .= '<style></style>';
return $css;
}
private function doNotShow(){
$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
if(isEmbed() || preg_match("/embed/i", $baseName) || !empty($_GET['embed'])){
return true;
}
return false;
}
public function getEmptyDataObject() {
$obj = new stdClass();
$obj->text = '<b>This website uses cookies</b> &#x1F36A; so we can provide you with the best user experience. Without these cookies, the website simply would not work.';
$obj->btnText = 'I agree';
return $obj;
}
public function getFooterCode() {
if($this->doNotShow()){
return "";
}
$obj = $this->getDataObject();
global $global;
include $global['systemRootPath'] . 'plugin/CookieAlert/footer.php';
}
}

View file

@ -1,11 +1,11 @@
<!-- COOKIES -->
<div class="alert alert-dismissible text-center cookiealert" role="alert">
<div class="cookiealert-container">
<?php echo $obj->text; ?>
<button type="button" class="btn btn-primary btn-sm acceptcookies" aria-label="Close">
<?php echo $obj->btnText; ?>
</button>
</div>
</div>
<!-- /COOKIES -->
<!-- COOKIES -->
<div class="alert alert-dismissible text-center cookiealert" role="alert">
<div class="cookiealert-container">
<?php echo $obj->text; ?>
<button type="button" class="btn btn-primary btn-sm acceptcookies" aria-label="Close">
<?php echo $obj->btnText; ?>
</button>
</div>
</div>
<!-- /COOKIES -->
<script src="<?php echo getCDN(); ?>plugin/CookieAlert/cookiealert-standalone.js"></script>

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
<?php
require_once '../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$name = "advancedCustom.json.php";
$obj = ObjectYPT::getCache($name, 60);
if(empty($obj)){
$obj = AVideoPlugin::getObjectData("CustomizeAdvanced");
ObjectYPT::setCache($name, $obj);
}
<?php
require_once '../../videos/configuration.php';
session_write_close();
header('Content-Type: application/json');
$name = "advancedCustom.json.php";
$obj = ObjectYPT::getCache($name, 60);
if(empty($obj)){
$obj = AVideoPlugin::getObjectData("CustomizeAdvanced");
ObjectYPT::setCache($name, $obj);
}
echo json_encode($obj);

View file

@ -1,13 +1,13 @@
$(function () {
$("#mainNavBar").on("show.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$("body").removeClass("nopadding");
}
});
$("#mainNavBar").on("hide.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$("body").addClass("nopadding");
}
});
$(function () {
$("#mainNavBar").on("show.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$("body").removeClass("nopadding");
}
});
$("#mainNavBar").on("hide.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$("body").addClass("nopadding");
}
});
});

View file

@ -1,45 +1,45 @@
var autoHidingNavbarTimeout;
function autoHideNavbar() {
//console.log("autoHidingNavbar");
autoHidingNavbarTimeout = setTimeout(function () {
$("#mainNavBar").on("show.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').removeClass('nopadding');
}
});
$("#mainNavBar").on("hide.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').addClass('nopadding');
}
});
$("#mainNavBar").autoHidingNavbar("hide");
}, autoHidingNavbarTimeoutMiliseconds);
}
$(function () {
if ($("#mainNavBar").length) {
autoHideNavbar();
$("#mainNavBar").mouseover(function () {
//console.log("clearTimeout autoHidingNavbar");
clearTimeout(autoHidingNavbarTimeout);
});
$("#mainNavBar").mouseout(function () {
autoHideNavbar();
});
$(document).mousemove(function (event) {
if (event.pageY - $(document).scrollTop() <= 10) {
$("#mainNavBar").autoHidingNavbar("show");
}
});
$("#mainNavBar").on("show.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').removeClass('nopadding');
}
});
$("#mainNavBar").on("hide.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').addClass('nopadding');
}
});
}
var autoHidingNavbarTimeout;
function autoHideNavbar() {
//console.log("autoHidingNavbar");
autoHidingNavbarTimeout = setTimeout(function () {
$("#mainNavBar").on("show.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').removeClass('nopadding');
}
});
$("#mainNavBar").on("hide.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').addClass('nopadding');
}
});
$("#mainNavBar").autoHidingNavbar("hide");
}, autoHidingNavbarTimeoutMiliseconds);
}
$(function () {
if ($("#mainNavBar").length) {
autoHideNavbar();
$("#mainNavBar").mouseover(function () {
//console.log("clearTimeout autoHidingNavbar");
clearTimeout(autoHidingNavbarTimeout);
});
$("#mainNavBar").mouseout(function () {
autoHideNavbar();
});
$(document).mousemove(function (event) {
if (event.pageY - $(document).scrollTop() <= 10) {
$("#mainNavBar").autoHidingNavbar("show");
}
});
$("#mainNavBar").on("show.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').removeClass('nopadding');
}
});
$("#mainNavBar").on("hide.autoHidingNavbar", function () {
if ($(window).scrollTop() < 10) {
$('body').addClass('nopadding');
}
});
}
});

View file

@ -1,96 +1,96 @@
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
$images = Video::getImageFromFilename($video['filename']);
$img = $images->poster;
if (!empty($images->posterPortrait) && strpos($images->posterPortrait, 'notfound_portrait') === false) {
$img = $images->posterPortrait;
}
$imgw = 1280;
$imgh = 720;
$metaDescription = $title = str_replace('"', '', $video['title']);
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<title><?php echo __("Confirm Rating") . $config->getPageTitleSeparator() . $title; ?></title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<link rel="image_src" href="<?php echo $img; ?>" />
<meta property="fb:app_id" content="774958212660408" />
<meta property="og:url" content="<?php echo $global['webSiteRootURL'], "video/", $video['clean_title']; ?>" />
<meta property="og:type" content="video.other" />
<meta property="og:title" content="<?php echo str_replace('"', '', $video['title']); ?> - <?php echo $config->getWebSiteTitle(); ?>" />
<meta property="og:description" content="<?php echo!empty($custom) ? $custom : str_replace('"', '', $video['title']); ?>" />
<meta property="og:image" content="<?php echo $img; ?>" />
<meta property="og:image:width" content="<?php echo $imgw; ?>" />
<meta property="og:image:height" content="<?php echo $imgh; ?>" />
<meta property="video:duration" content="<?php echo Video::getItemDurationSeconds($video['duration']); ?>" />
<meta property="duration" content="<?php echo Video::getItemDurationSeconds($video['duration']); ?>" />
<style>
body {
padding-top: 0;
}
footer{
display: none;
}
#bg{
position: fixed;
width: 100%;
height: 100%;
background-image: url('<?php echo $images->poster; ?>');
background-size: cover;
opacity: 0.3;
filter: alpha(opacity=30); /* For IE8 and earlier */
}
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
//include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div id="bg"></div>
<!-- Modal -->
<div id="myModal" class="modal fade in" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title: <?php echo $video['title']; ?></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-6">
<img src="<?php echo $img; ?>" class="img img-responsive"/>
</div>
<div class="col-sm-6">
<center>
<?php
include $global['systemRootPath'] . 'view/rrating/rating-'.$video['rrating'].'_text.php';
?>
</center>
</div>
</div>
</div>
<div class="modal-footer" >
<a href="<?php echo $_SERVER['REQUEST_URI'],strpos($_SERVER['REQUEST_URI'], "?")===false?"?":"&"; ?>rrating=1" class="btn btn-success pull-right"><i class="fas fa-check-circle"></i> <?php echo __("Confirm"); ?></a>
<a href="<?php echo $global['webSiteRootURL']; ?>" class="btn btn-danger pull-right"><i class="fas fa-times-circle"></i> <?php echo __("Cancel"); ?></a>
</div>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script type="text/javascript">
$(window).on('load', function () {
$('#myModal').modal('show');
});
</script>
</body>
</html>
<?php
require_once dirname(__FILE__) . '/../../videos/configuration.php';
$images = Video::getImageFromFilename($video['filename']);
$img = $images->poster;
if (!empty($images->posterPortrait) && strpos($images->posterPortrait, 'notfound_portrait') === false) {
$img = $images->posterPortrait;
}
$imgw = 1280;
$imgh = 720;
$metaDescription = $title = str_replace('"', '', $video['title']);
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>">
<head>
<title><?php echo __("Confirm Rating") . $config->getPageTitleSeparator() . $title; ?></title>
<?php
include $global['systemRootPath'] . 'view/include/head.php';
?>
<link rel="image_src" href="<?php echo $img; ?>" />
<meta property="fb:app_id" content="774958212660408" />
<meta property="og:url" content="<?php echo $global['webSiteRootURL'], "video/", $video['clean_title']; ?>" />
<meta property="og:type" content="video.other" />
<meta property="og:title" content="<?php echo str_replace('"', '', $video['title']); ?> - <?php echo $config->getWebSiteTitle(); ?>" />
<meta property="og:description" content="<?php echo!empty($custom) ? $custom : str_replace('"', '', $video['title']); ?>" />
<meta property="og:image" content="<?php echo $img; ?>" />
<meta property="og:image:width" content="<?php echo $imgw; ?>" />
<meta property="og:image:height" content="<?php echo $imgh; ?>" />
<meta property="video:duration" content="<?php echo Video::getItemDurationSeconds($video['duration']); ?>" />
<meta property="duration" content="<?php echo Video::getItemDurationSeconds($video['duration']); ?>" />
<style>
body {
padding-top: 0;
}
footer{
display: none;
}
#bg{
position: fixed;
width: 100%;
height: 100%;
background-image: url('<?php echo $images->poster; ?>');
background-size: cover;
opacity: 0.3;
filter: alpha(opacity=30); /* For IE8 and earlier */
}
</style>
</head>
<body class="<?php echo $global['bodyClass']; ?>">
<?php
//include $global['systemRootPath'] . 'view/include/navbar.php';
?>
<div id="bg"></div>
<!-- Modal -->
<div id="myModal" class="modal fade in" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title: <?php echo $video['title']; ?></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-6">
<img src="<?php echo $img; ?>" class="img img-responsive"/>
</div>
<div class="col-sm-6">
<center>
<?php
include $global['systemRootPath'] . 'view/rrating/rating-'.$video['rrating'].'_text.php';
?>
</center>
</div>
</div>
</div>
<div class="modal-footer" >
<a href="<?php echo $_SERVER['REQUEST_URI'],strpos($_SERVER['REQUEST_URI'], "?")===false?"?":"&"; ?>rrating=1" class="btn btn-success pull-right"><i class="fas fa-check-circle"></i> <?php echo __("Confirm"); ?></a>
<a href="<?php echo $global['webSiteRootURL']; ?>" class="btn btn-danger pull-right"><i class="fas fa-times-circle"></i> <?php echo __("Cancel"); ?></a>
</div>
</div>
</div>
</div>
<?php
include $global['systemRootPath'] . 'view/include/footer.php';
?>
<script type="text/javascript">
$(window).on('load', function () {
$('#myModal').modal('show');
});
</script>
</body>
</html>

View file

@ -1,24 +1,24 @@
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if (!User::isAdmin()) {
$obj->msg = __("Permission denied");
die(json_encode($obj));
}
if(empty($_POST['videos_id'])){
$obj->msg = __("Video Not found");
die(json_encode($obj));
}
$videos_id = intval($_POST['videos_id']);
$video = new Video("","", $videos_id);
$obj->error = empty(Video::deleteThumbs($video->getFilename()));
die(json_encode($obj));
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if (!User::isAdmin()) {
$obj->msg = __("Permission denied");
die(json_encode($obj));
}
if(empty($_POST['videos_id'])){
$obj->msg = __("Video Not found");
die(json_encode($obj));
}
$videos_id = intval($_POST['videos_id']);
$video = new Video("","", $videos_id);
$obj->error = empty(Video::deleteThumbs($video->getFilename()));
die(json_encode($obj));

View file

@ -1,31 +1,31 @@
<?php
$obj = AVideoPlugin::getObjectDataIfEnabled('Subscription');
?>
<li>
<hr>
<h3 class="text-danger">
<i class="fas fa-filter"></i> <?php echo __("R Rating"); ?>
</h3>
<ul style="margin: 0; padding-left: 15px; list-style-type: none;">
<?php
foreach (Video::$rratingOptions as $value) {
if (empty($value)) {
$label = __("Not Rated");
$value = 0;
} else {
$label = strtoupper($value);
}
?>
<li>
<a href="<?php echo $global['webSiteRootURL']; ?>?rrating=<?php echo $value; ?>">
<?php echo $label; ?>
</a>
</li>
<?php
}
?>
</ul>
</li>
<?php
$obj = AVideoPlugin::getObjectDataIfEnabled('Subscription');
?>
<li>
<hr>
<h3 class="text-danger">
<i class="fas fa-filter"></i> <?php echo __("R Rating"); ?>
</h3>
<ul style="margin: 0; padding-left: 15px; list-style-type: none;">
<?php
foreach (Video::$rratingOptions as $value) {
if (empty($value)) {
$label = __("Not Rated");
$value = 0;
} else {
$label = strtoupper($value);
}
?>
<li>
<a href="<?php echo $global['webSiteRootURL']; ?>?rrating=<?php echo $value; ?>">
<?php echo $label; ?>
</a>
</li>
<?php
}
?>
</ul>
</li>

View file

@ -1,28 +1,28 @@
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if (!User::isAdmin()) {
$obj->msg = __("Permission denied");
die(json_encode($obj));
}
if(empty($_POST['videos_id'])){
$obj->msg = __("Video Not found");
die(json_encode($obj));
}
$obj->videos_id = intval($_POST['videos_id']);
$obj->error = empty(Video::updateFilesize($obj->videos_id));
$v = new Video('', '', $obj->videos_id);
$obj->filename = $v->getFilename();
$obj->filesize = $v->getFilesize();
$obj->filesize_human = humanFileSize($obj->filesize);
die(json_encode($obj));
<?php
header('Content-Type: application/json');
require_once '../../videos/configuration.php';
$obj = new stdClass();
$obj->error = true;
$obj->msg = "";
if (!User::isAdmin()) {
$obj->msg = __("Permission denied");
die(json_encode($obj));
}
if(empty($_POST['videos_id'])){
$obj->msg = __("Video Not found");
die(json_encode($obj));
}
$obj->videos_id = intval($_POST['videos_id']);
$obj->error = empty(Video::updateFilesize($obj->videos_id));
$v = new Video('', '', $obj->videos_id);
$obj->filename = $v->getFilename();
$obj->filesize = $v->getFilesize();
$obj->filesize_human = humanFileSize($obj->filesize);
die(json_encode($obj));

File diff suppressed because it is too large Load diff

View file

@ -1,223 +1,223 @@
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Categories_has_users_groups extends ObjectYPT
{
protected $id;
protected $categories_id;
protected $users_groups_id;
protected $status;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'categories_has_users_groups';
}
public static function getAllCategories()
{
global $global;
$table = "categories";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
_error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getAllUsers_groups()
{
global $global;
$table = "users_groups";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
_error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public function setId($id)
{
$this->id = intval($id);
}
public function setCategories_id($categories_id)
{
$this->categories_id = intval($categories_id);
}
public function setUsers_groups_id($users_groups_id)
{
$this->users_groups_id = intval($users_groups_id);
}
public function setStatus($status)
{
$this->status = $status;
}
public function getId()
{
return intval($this->id);
}
public function getCategories_id()
{
return intval($this->categories_id);
}
public function getUsers_groups_id()
{
return intval($this->users_groups_id);
}
public function getStatus()
{
return $this->status;
}
public static function getAll()
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$sql = "SELECT c.*, ug.*, cug.* FROM " . static::getTableName() . " cug "
. " LEFT JOIN categories c ON cug.categories_id = c.id "
. " LEFT JOIN users_groups ug ON cug.users_groups_id = ug.id "
. " WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getAllFromCategory($categories_id)
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return false;
}
$sql = "SELECT c.*, ug.*, cug.* FROM " . static::getTableName() . " cug "
. " LEFT JOIN categories c ON cug.categories_id = c.id "
. " LEFT JOIN users_groups ug ON cug.users_groups_id = ug.id "
. " WHERE cug.categories_id = {$categories_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 static function getUserGroupsIdsFromCategory($categories_id){
global $global;
if (!static::isTableInstalled()) {
return array();
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return array();
}
$sql = "SELECT * FROM " . static::getTableName() . " cug "
. " WHERE cug.categories_id = {$categories_id} ";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
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 static function deleteAllFromCategory($categories_id) {
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return false;
}
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE categories_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", array($categories_id));
}
public static function saveUsergroup($categories_id, $users_groups_id) {
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return false;
}
$users_groups_id = intval($users_groups_id);
if (empty($users_groups_id)) {
return false;
}
$cug = new Categories_has_users_groups(0);
$cug->setCategories_id($categories_id);
$cug->setUsers_groups_id($users_groups_id);
$cug->setStatus('a');
return $cug->save();
}
}
<?php
require_once dirname(__FILE__) . '/../../../videos/configuration.php';
class Categories_has_users_groups extends ObjectYPT
{
protected $id;
protected $categories_id;
protected $users_groups_id;
protected $status;
public static function getSearchFieldsNames()
{
return [];
}
public static function getTableName()
{
return 'categories_has_users_groups';
}
public static function getAllCategories()
{
global $global;
$table = "categories";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
_error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getAllUsers_groups()
{
global $global;
$table = "users_groups";
$sql = "SELECT * FROM {$table} WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
_error_log($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public function setId($id)
{
$this->id = intval($id);
}
public function setCategories_id($categories_id)
{
$this->categories_id = intval($categories_id);
}
public function setUsers_groups_id($users_groups_id)
{
$this->users_groups_id = intval($users_groups_id);
}
public function setStatus($status)
{
$this->status = $status;
}
public function getId()
{
return intval($this->id);
}
public function getCategories_id()
{
return intval($this->categories_id);
}
public function getUsers_groups_id()
{
return intval($this->users_groups_id);
}
public function getStatus()
{
return $this->status;
}
public static function getAll()
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$sql = "SELECT c.*, ug.*, cug.* FROM " . static::getTableName() . " cug "
. " LEFT JOIN categories c ON cug.categories_id = c.id "
. " LEFT JOIN users_groups ug ON cug.users_groups_id = ug.id "
. " WHERE 1=1 ";
$sql .= self::getSqlFromPost();
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
if ($res != false) {
foreach ($fullData as $row) {
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getAllFromCategory($categories_id)
{
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return false;
}
$sql = "SELECT c.*, ug.*, cug.* FROM " . static::getTableName() . " cug "
. " LEFT JOIN categories c ON cug.categories_id = c.id "
. " LEFT JOIN users_groups ug ON cug.users_groups_id = ug.id "
. " WHERE cug.categories_id = {$categories_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 static function getUserGroupsIdsFromCategory($categories_id){
global $global;
if (!static::isTableInstalled()) {
return array();
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return array();
}
$sql = "SELECT * FROM " . static::getTableName() . " cug "
. " WHERE cug.categories_id = {$categories_id} ";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = [];
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 static function deleteAllFromCategory($categories_id) {
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return false;
}
$sql = "DELETE FROM " . static::getTableName() . " ";
$sql .= " WHERE categories_id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", array($categories_id));
}
public static function saveUsergroup($categories_id, $users_groups_id) {
global $global;
if (!static::isTableInstalled()) {
return false;
}
$categories_id = intval($categories_id);
if (empty($categories_id)) {
return false;
}
$users_groups_id = intval($users_groups_id);
if (empty($users_groups_id)) {
return false;
}
$cug = new Categories_has_users_groups(0);
$cug->setCategories_id($categories_id);
$cug->setUsers_groups_id($users_groups_id);
$cug->setStatus('a');
return $cug->save();
}
}

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