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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,35 +1,35 @@
<?php <?php
header('Content-type: application/xml'); header('Content-type: application/xml');
require_once '../../videos/configuration.php'; require_once '../../videos/configuration.php';
allowOrigin(); allowOrigin();
$ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server'); $ad_server = AVideoPlugin::loadPluginIfEnabled('AD_Server');
if (empty($ad_server)) { if (empty($ad_server)) {
die("not enabled"); die("not enabled");
} }
if (empty($_GET['video_length'])) { if (empty($_GET['video_length'])) {
$_GET['video_length'] = 300; $_GET['video_length'] = 300;
} }
if (empty($_GET['vmap_id'])) { if (empty($_GET['vmap_id'])) {
$_GET['vmap_id'] = uniqid(); $_GET['vmap_id'] = uniqid();
} }
$vmaps = AD_Server::getVMAPSFromRequest(); $vmaps = AD_Server::getVMAPSFromRequest();
?> ?>
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<vmap:VMAP xmlns:vmap="http://www.iab.net/videosuite/vmap" version="1.0"> <vmap:VMAP xmlns:vmap="http://www.iab.net/videosuite/vmap" version="1.0">
<?php <?php
foreach ($vmaps as $value) { foreach ($vmaps as $value) {
if (empty($value['VAST']['campaing'])) { if (empty($value['VAST']['campaing'])) {
continue; continue;
} ?> } ?>
<vmap:AdBreak timeOffset="<?php echo $value['timeOffset']; ?>" breakType="linear"> <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: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: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:AdSource>
</vmap:AdBreak> </vmap:AdBreak>
<?php <?php
} }
?> ?>
</vmap:VMAP> </vmap:VMAP>

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,34 +1,34 @@
<?php <?php
require_once '../../videos/configuration.php'; require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.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/VastCampaigns.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php'; require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsLogs.php';
require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php'; require_once $global['systemRootPath'] . 'plugin/AD_Server/Objects/VastCampaignsVideos.php';
if (empty($_GET['campaign_has_videos_id'])) { if (empty($_GET['campaign_has_videos_id'])) {
die('campaign_has_videos_id Can not be empty'); die('campaign_has_videos_id Can not be empty');
} }
$users_id = 'null'; $users_id = 'null';
if (User::isLogged()) { if (User::isLogged()) {
$users_id = User::getId(); $users_id = User::getId();
} }
$log = new VastCampaignsLogs(0); $log = new VastCampaignsLogs(0);
$log->setType($_GET['label']); $log->setType($_GET['label']);
$log->setUsers_id($users_id); $log->setUsers_id($users_id);
$log->setVast_campaigns_has_videos_id($_GET['campaign_has_videos_id']); $log->setVast_campaigns_has_videos_id($_GET['campaign_has_videos_id']);
$log->save(); $log->save();
$campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']); $campaignVideo = new VastCampaignsVideos($_GET['campaign_has_videos_id']);
if ($_GET['label'] === 'Impression') { if ($_GET['label'] === 'Impression') {
$campaign = new VastCampaigns($campaignVideo->getVast_campaigns_id()); $campaign = new VastCampaigns($campaignVideo->getVast_campaigns_id());
$campaign->addView(); $campaign->addView();
} }
if ($_GET['label'] === 'ClickThrough') { if ($_GET['label'] === 'ClickThrough') {
// get the URL // get the URL
$link = $campaignVideo->getLink(); $link = $campaignVideo->getLink();
if (filter_var($link, FILTER_VALIDATE_URL)) { if (filter_var($link, FILTER_VALIDATE_URL)) {
header("Location: ".$link); 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 { .vjs-marker {
position: absolute; position: absolute;
left: 0; left: 0;
bottom: 0em; bottom: 0em;
opacity: 1; opacity: 1;
height: 100%; height: 100%;
transition: opacity .2s ease; transition: opacity .2s ease;
-webkit-transition: opacity .2s ease; -webkit-transition: opacity .2s ease;
-moz-transition: opacity .2s ease; -moz-transition: opacity .2s ease;
z-index: 100; z-index: 100;
} }
.vjs-marker:hover { .vjs-marker:hover {
cursor: pointer; cursor: pointer;
-webkit-transform: scale(1.3, 1.3); -webkit-transform: scale(1.3, 1.3);
-moz-transform: scale(1.3, 1.3); -moz-transform: scale(1.3, 1.3);
-o-transform: scale(1.3, 1.3); -o-transform: scale(1.3, 1.3);
-ms-transform: scale(1.3, 1.3); -ms-transform: scale(1.3, 1.3);
transform: scale(1.3, 1.3); transform: scale(1.3, 1.3);
} }
.vjs-tip { .vjs-tip {
visibility: hidden; visibility: hidden;
display: block; display: block;
opacity: 0.8; opacity: 0.8;
padding: 5px; padding: 5px;
font-size: 10px; font-size: 10px;
position: absolute; position: absolute;
bottom: 14px; bottom: 14px;
z-index: 100000; z-index: 100000;
} }
.vjs-tip .vjs-tip-arrow { .vjs-tip .vjs-tip-arrow {
background: url(data:image/gif;base64,R0lGODlhCQAJAIABAAAAAAAAACH5BAEAAAEALAAAAAAJAAkAAAIRjAOnwIrcDJxvwkplPtchVQAAOw==) no-repeat top left; background: url(data:image/gif;base64,R0lGODlhCQAJAIABAAAAAAAAACH5BAEAAAEALAAAAAAJAAkAAAIRjAOnwIrcDJxvwkplPtchVQAAOw==) no-repeat top left;
bottom: 0; bottom: 0;
left: 50%; left: 50%;
margin-left: -4px; margin-left: -4px;
background-position: bottom left; background-position: bottom left;
position: absolute; position: absolute;
width: 9px; width: 9px;
height: 5px; height: 5px;
} }
.vjs-tip .vjs-tip-inner { .vjs-tip .vjs-tip-inner {
border-radius: 3px; border-radius: 3px;
-moz-border-radius: 3px; -moz-border-radius: 3px;
-webkit-border-radius: 3px; -webkit-border-radius: 3px;
padding: 5px 8px 4px 8px; padding: 5px 8px 4px 8px;
background-color: black; background-color: black;
color: white; color: white;
max-width: 200px; max-width: 200px;
text-align: center; text-align: center;
} }
.vjs-break-overlay { .vjs-break-overlay {
visibility: hidden; visibility: hidden;
position: absolute; position: absolute;
z-index: 100000; z-index: 100000;
top: 0; top: 0;
} }
.vjs-break-overlay .vjs-break-overlay-text { .vjs-break-overlay .vjs-break-overlay-text {
padding: 9px; padding: 9px;
text-align: center; text-align: center;
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,112 +1,112 @@
<?php <?php
global $global, $config; global $global, $config;
if (!isset($global['systemRootPath'])) { if (!isset($global['systemRootPath'])) {
require_once '../../videos/configuration.php'; require_once '../../videos/configuration.php';
} }
if (!User::isAdmin()) { if (!User::isAdmin()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this")); header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit; exit;
} }
require_once $global['systemRootPath'] . 'plugin/API/API.php'; require_once $global['systemRootPath'] . 'plugin/API/API.php';
$plugin = AVideoPlugin::loadPluginIfEnabled("API"); $plugin = AVideoPlugin::loadPluginIfEnabled("API");
if (empty($plugin)) { if (empty($plugin)) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this")); header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit; exit;
} }
$obj = AVideoPlugin::getObjectData("API"); $obj = AVideoPlugin::getObjectData("API");
$reflector = new ReflectionClass('API'); $reflector = new ReflectionClass('API');
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>"> <html lang="<?php echo $_SESSION['language']; ?>">
<head> <head>
<?php <?php
echo getHTMLTitle(__("API")); echo getHTMLTitle(__("API"));
?> ?>
<?php <?php
include $global['systemRootPath'] . 'view/include/head.php'; include $global['systemRootPath'] . 'view/include/head.php';
?> ?>
<style> <style>
pre a{ pre a{
color: #333; color: #333;
font-weight: bolder; font-weight: bolder;
} }
</style> </style>
</head> </head>
<body class="<?php echo $global['bodyClass']; ?>"> <body class="<?php echo $global['bodyClass']; ?>">
<?php <?php
include $global['systemRootPath'] . 'view/include/navbar.php'; include $global['systemRootPath'] . 'view/include/navbar.php';
$class_methods = get_class_methods('API'); $class_methods = get_class_methods('API');
foreach ($class_methods as $key => $method_name) { foreach ($class_methods as $key => $method_name) {
if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) { if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) {
unset($class_methods[$key]); unset($class_methods[$key]);
} }
} }
usort($class_methods, function ($a, $b) { usort($class_methods, function ($a, $b) {
if (!preg_match("/(get|set)_api_(.*)/", $a, $matchesA)) { if (!preg_match("/(get|set)_api_(.*)/", $a, $matchesA)) {
return 0; return 0;
} }
if (!preg_match("/(get|set)_api_(.*)/", $b, $matchesB)) { if (!preg_match("/(get|set)_api_(.*)/", $b, $matchesB)) {
return 0; return 0;
} }
return strcasecmp($matchesA[2], $matchesB[2]); return strcasecmp($matchesA[2], $matchesB[2]);
}); });
?> ?>
<div class="container-fluid"> <div class="container-fluid">
<ul class="list-group"> <ul class="list-group">
<li class="list-group-item"> <li class="list-group-item">
<details> <details>
<summary style="cursor: pointer;"><i class="fas fa-file-upload"></i> Upload a Video</summary> <summary style="cursor: pointer;"><i class="fas fa-file-upload"></i> Upload a Video</summary>
<br> <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> 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> <br>
Your HTML Form should looks like this. The user and the pass values on the action URL will be the video owner Your HTML Form should looks like this. The user and the pass values on the action URL will be the video owner
<pre><?php <pre><?php
$frm = '<form enctype="multipart/form-data" method="post" action="' . $global['webSiteRootURL'] . 'plugin/MobileManager/upload.php?user=' . urlencode(User::getUserName()) . '&pass=' . User::getUserPass() . '"> $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> <input name="title" type="text" /><br>
<textarea name="description"></textarea><br> <textarea name="description"></textarea><br>
<input name="categories_id" type="hidden" value="1" /> <input name="categories_id" type="hidden" value="1" />
<input name="upl" type="file" accept="video/mp4" /><br> <input name="upl" type="file" accept="video/mp4" /><br>
<input type="submit" value="submit" id="submit"/> <input type="submit" value="submit" id="submit"/>
</form>'; </form>';
echo htmlentities($frm); echo htmlentities($frm);
?> ?>
</pre> </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 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> </details>
</li> </li>
<?php <?php
foreach ($class_methods as $method_name) { foreach ($class_methods as $method_name) {
if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) { if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) {
continue; continue;
} ?> } ?>
<li class="list-group-item"> <li class="list-group-item">
<details> <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> <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> <br>
<pre><?php <pre><?php
$comment = $reflector->getMethod($method_name)->getDocComment(); $comment = $reflector->getMethod($method_name)->getDocComment();
$comment = str_replace(['{webSiteRootURL}', '{getOrSet}', '{APIName}', '{APISecret}'], [$global['webSiteRootURL'], $matches[1], $matches[2], $obj->APISecret], $comment); $comment = str_replace(['{webSiteRootURL}', '{getOrSet}', '{APIName}', '{APISecret}'], [$global['webSiteRootURL'], $matches[1], $matches[2], $obj->APISecret], $comment);
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $comment, $match2); preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $comment, $match2);
//var_dump($match2[0]); //var_dump($match2[0]);
$link = "<a target='_blank' href='{$match2[0][0]}'>" . htmlentities($match2[0][0]) . "</a>"; $link = "<a target='_blank' href='{$match2[0][0]}'>" . htmlentities($match2[0][0]) . "</a>";
$comment = str_replace([$match2[0][0], " *"], [$link, "*"], $comment); $comment = str_replace([$match2[0][0], " *"], [$link, "*"], $comment);
echo($comment); echo($comment);
//{webSiteRootURL}plugin/API/{getOrSet}.json.php?name={name} //{webSiteRootURL}plugin/API/{getOrSet}.json.php?name={name}
?> ?>
</pre> </pre>
</details> </details>
</li> </li>
<?php <?php
} }
?> ?>
</ul> </ul>
</div> </div>
<?php <?php
include $global['systemRootPath'] . 'view/include/footer.php'; include $global['systemRootPath'] . 'view/include/footer.php';
?> ?>
</body> </body>
</html> </html>

View file

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

View file

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

View file

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

View file

@ -1,47 +1,47 @@
<?php <?php
global $global; global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php'; require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class Articles extends PluginAbstract { class Articles extends PluginAbstract {
public function getTags() { public function getTags() {
return array( return array(
PluginTags::$FREE PluginTags::$FREE
); );
} }
public function getDescription() { public function getDescription() {
global $global; global $global;
$str = "Create rich text articles"; $str = "Create rich text articles";
$alert = ""; $alert = "";
$dir = $global['systemRootPath'] . 'vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer'; $dir = $global['systemRootPath'] . 'vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer';
if (!is_writable($dir)) { if (!is_writable($dir)) {
$alert = "<div class='alert alert-danger'>Your directory must be writable<br><code>sudo chmod 777 {$dir}</code></div>"; $alert = "<div class='alert alert-danger'>Your directory must be writable<br><code>sudo chmod 777 {$dir}</code></div>";
} }
return $str.$alert; return $str.$alert;
} }
public function getName() { public function getName() {
return "Articles"; return "Articles";
} }
public function getUUID() { public function getUUID() {
return "articles-91db-4357-bb10-ee08b0913778"; return "articles-91db-4357-bb10-ee08b0913778";
} }
public function getEmptyDataObject() { public function getEmptyDataObject() {
global $global; global $global;
$obj = new stdClass(); $obj = new stdClass();
$obj->allowAttributes = false; $obj->allowAttributes = false;
$obj->allowCSS = false; $obj->allowCSS = false;
return $obj; return $obj;
} }
public function getPluginMenu() { public function getPluginMenu() {
global $global; 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/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>'; $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; return $btn;
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,150 +1,150 @@
<?php <?php
global $global; global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php'; require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'objects/autoload.php'; require_once $global['systemRootPath'] . 'objects/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth; use Abraham\TwitterOAuth\TwitterOAuth;
class AutoPostOnSocialMedia extends PluginAbstract { class AutoPostOnSocialMedia extends PluginAbstract {
static $scheduleType = 'AutoPostOnSocialMedia'; static $scheduleType = 'AutoPostOnSocialMedia';
public function getDescription() { public function getDescription() {
$desc = "AutoPostOnSocialMedia Plugin $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. 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. 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\". Click the button \"Create New App\".
Fill up Name, Description, Website fields. Fill up Name, Description, Website fields.
Accept agreement and click the button \"Create your Twitter application\". 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. 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\". 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. At this step, copy your Access Token and Access Token Secret. Keep these details safe.
Login in your app: http://dev.twitter.com/apps 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 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."; In the Reset keys tab, press the Reset button, update the consumer key and secret in your application accordingly.";
$desc = nl2br($desc); $desc = nl2br($desc);
return $desc; return $desc;
} }
public function getName() { public function getName() {
return "AutoPostOnSocialMedia"; return "AutoPostOnSocialMedia";
} }
public function getUUID() { public function getUUID() {
return "AutoPostOnSocialMedia-5ee8405eaaa16"; return "AutoPostOnSocialMedia-5ee8405eaaa16";
} }
public function getPluginVersion() { public function getPluginVersion() {
return "1.0"; return "1.0";
} }
public function updateScript() { public function updateScript() {
global $global; global $global;
/* /*
if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) { if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) {
sqlDal::executeFile($global['systemRootPath'] . 'plugin/PayPerView/install/updateV2.0.sql'); sqlDal::executeFile($global['systemRootPath'] . 'plugin/PayPerView/install/updateV2.0.sql');
} }
* *
*/ */
return true; return true;
} }
public function getEmptyDataObject() { public function getEmptyDataObject() {
$obj = new stdClass(); $obj = new stdClass();
/* /*
$obj->textSample = "text"; $obj->textSample = "text";
$obj->checkboxSample = true; $obj->checkboxSample = true;
$obj->numberSample = 5; $obj->numberSample = 5;
$o = new stdClass(); $o = new stdClass();
$o->type = array(0=>__("Default"))+array(1,2,3); $o->type = array(0=>__("Default"))+array(1,2,3);
$o->value = 0; $o->value = 0;
$obj->selectBoxSample = $o; $obj->selectBoxSample = $o;
$o = new stdClass(); $o = new stdClass();
$o->type = "textarea"; $o->type = "textarea";
$o->value = ""; $o->value = "";
$obj->textareaSample = $o; $obj->textareaSample = $o;
*/ */
$obj->TwitterEnable = true; $obj->TwitterEnable = true;
$obj->TwitterAPIKey = ""; $obj->TwitterAPIKey = "";
$obj->TwitterAPIKeySecret = ""; $obj->TwitterAPIKeySecret = "";
$o = new stdClass(); $o = new stdClass();
$o->type = "textarea"; $o->type = "textarea";
$o->value = ""; $o->value = "";
$obj->TwitterBearerToken = $o; $obj->TwitterBearerToken = $o;
$obj->TwitterAccessToken = ""; $obj->TwitterAccessToken = "";
$obj->TwitterAccessTokenSecret = ""; $obj->TwitterAccessTokenSecret = "";
$o = new stdClass(); $o = new stdClass();
$o->type = array( $o->type = array(
0 => __("All time"), 0 => __("All time"),
1 => __("1 Day"), 1 => __("1 Day"),
7 => __("7 Day"), 7 => __("7 Day"),
30 => __("1 Month"), 30 => __("1 Month"),
60 => __("2 Months"), 60 => __("2 Months"),
90 => __("3 Months"), 90 => __("3 Months"),
182 => __("6 Months"), 182 => __("6 Months"),
365 => __("12 Months")); 365 => __("12 Months"));
$o->value = 365; $o->value = 365;
$obj->postARandomVideoFromLastDays = $o; $obj->postARandomVideoFromLastDays = $o;
return $obj; return $obj;
} }
public function getPluginMenu() { public function getPluginMenu() {
global $global; 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="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>'; $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; return $btn;
} }
static function postVideo($videos_id) { static function postVideo($videos_id) {
$url = Video::getLinkToVideo($videos_id, "", false, "permalink", $get); $url = Video::getLinkToVideo($videos_id, "", false, "permalink", $get);
return self::post($url); return self::post($url);
} }
static function post($msg) { static function post($msg) {
$obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia'); $obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia');
//var_dump($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret, $msg);exit; //var_dump($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret, $msg);exit;
if($obj->TwitterEnable){ if($obj->TwitterEnable){
$connection = new TwitterOAuth($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret); $connection = new TwitterOAuth($obj->TwitterAPIKey, $obj->TwitterAPIKeySecret, $obj->TwitterAccessToken, $obj->TwitterAccessTokenSecret);
$post_tweets = $connection->post("statuses/update", ["status" => $msg]); $post_tweets = $connection->post("statuses/update", ["status" => $msg]);
} }
return $post_tweets; return $post_tweets;
} }
public function getVideosManagerListButton() { public function getVideosManagerListButton() {
if (!User::isAdmin()) { if (!User::isAdmin()) {
return ""; 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>'; $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; return $btn;
} }
static function getRandomVideo() { static function getRandomVideo() {
$obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia'); $obj = AVideoPlugin::getDataObject('AutoPostOnSocialMedia');
$days = $obj->postARandomVideoFromLastDays->value; $days = $obj->postARandomVideoFromLastDays->value;
$sql = "SELECT * FROM videos WHERE 1=1 "; $sql = "SELECT * FROM videos WHERE 1=1 ";
$sql .= " AND status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; $sql .= " AND status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
if(!empty($days)){ if(!empty($days)){
$sql .=" AND created >= ( CURDATE() - INTERVAL {$days} DAY ) "; $sql .=" AND created >= ( CURDATE() - INTERVAL {$days} DAY ) ";
} }
$sql .= " ORDER BY RAND() LIMIT 1 "; $sql .= " ORDER BY RAND() LIMIT 1 ";
//echo var_dump($days, $sql); //echo var_dump($days, $sql);
$res = sqlDAL::readSql($sql, "", array(), true); $res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res); $video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res); sqlDAL::close($res);
return $video; return $video;
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,136 +1,136 @@
<?php <?php
require_once '../../videos/configuration.php'; require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isLogged()) { if (!User::isLogged()) {
header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this")); header("Location: {$global['webSiteRootURL']}?error=" . __("You can not do this"));
exit; exit;
} }
$plugin = AVideoPlugin::loadPluginIfEnabled("BlockonomicsYPT"); $plugin = AVideoPlugin::loadPluginIfEnabled("BlockonomicsYPT");
$obj = AVideoPlugin::getObjectData("BlockonomicsYPT"); $obj = AVideoPlugin::getObjectData("BlockonomicsYPT");
$order_id = $plugin->setUpPayment($_GET['value']); $order_id = $plugin->setUpPayment($_GET['value']);
$order = new BlockonomicsOrder($order_id); $order = new BlockonomicsOrder($order_id);
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="<?php echo $_SESSION['language']; ?>"> <html lang="<?php echo $_SESSION['language']; ?>">
<head> <head>
<?php <?php
echo getHTMLTitle( __("Invoice")); echo getHTMLTitle( __("Invoice"));
?> ?>
<?php <?php
include $global['systemRootPath'] . 'view/include/head.php'; include $global['systemRootPath'] . 'view/include/head.php';
?> ?>
<style> <style>
</style> </style>
</head> </head>
<body class="<?php echo $global['bodyClass']; ?>"> <body class="<?php echo $global['bodyClass']; ?>">
<?php <?php
include $global['systemRootPath'] . 'view/include/navbar.php'; include $global['systemRootPath'] . 'view/include/navbar.php';
?> ?>
<div class="container"> <div class="container">
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading"> <div class="panel-heading">
<h1> <h1>
Order#: <?php echo sprintf('%08d', $order->getId()); ?> Order#: <?php echo sprintf('%08d', $order->getId()); ?>
</h1> </h1>
</div> </div>
<div class="panel-body"> <div class="panel-body">
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<h2>Bitcoin Address</h2> <h2>Bitcoin Address</h2>
<a href="bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>"> <a href="bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>">
<div id="qrcode" class="text-center"></div> <div id="qrcode" class="text-center"></div>
</a> </a>
<br/> <br/>
<div class="field"> <div class="field">
<div class="control"> <div class="control">
<input type="text" class="input form-control" value="<?php echo $order->getAddr(); ?>" readonly="readonly"> <input type="text" class="input form-control" value="<?php echo $order->getAddr(); ?>" readonly="readonly">
</div> </div>
</div> </div>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<h2>To pay, send exact amount of BTC to the given address</h2> <h2>To pay, send exact amount of BTC to the given address</h2>
<h3>Amount</h3> <h3>Amount</h3>
<p><strong><?php echo $order->getFormatedBits(); ?></strong> BTC ⇌ <strong><?php echo $order->getTotal_value(); ?></strong> <?php echo $order->getCurrency(); ?></p> <p><strong><?php echo $order->getFormatedBits(); ?></strong> BTC ⇌ <strong><?php echo $order->getTotal_value(); ?></strong> <?php echo $order->getCurrency(); ?></p>
<br/> <br/>
<h2>Payment Details: </h2> <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-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-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="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-warning" id="status1"> Partially Confirmed</h4>
<h4 style="display: none;" class="bstatus label label-success" id="status2" >Confirmed</h4> <h4 style="display: none;" class="bstatus label label-success" id="status2" >Confirmed</h4>
<div> <div>
Received : <strong id="received"><?php echo $order->getFormatedBits_payed(); ?></strong> Received : <strong id="received"><?php echo $order->getFormatedBits_payed(); ?></strong>
<small>BTC</small> <small>BTC</small>
</div> </div>
<div style="margin-bottom:10px;" > <div style="margin-bottom:10px;" >
Transaction : <span id="transaction"></span> Transaction : <span id="transaction"></span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<div class="progress"> <div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" <div class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:100%" id="timeleft"> aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:100%" id="timeleft">
100% 100%
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<?php <?php
include $global['systemRootPath'] . 'view/include/footer.php'; include $global['systemRootPath'] . 'view/include/footer.php';
?> ?>
<script src="<?php echo getCDN(); ?>plugin/BlockonomicsYPT/jquery.qrcode.min.js" type="text/javascript"></script> <script src="<?php echo getCDN(); ?>plugin/BlockonomicsYPT/jquery.qrcode.min.js" type="text/javascript"></script>
<script> <script>
var totalSeconds = <?php echo $obj->ExpireInSeconds; ?>; var totalSeconds = <?php echo $obj->ExpireInSeconds; ?>;
var totalSecondsPassed = <?php echo time() - strtotime($order->getCreated()); ?>; var totalSecondsPassed = <?php echo time() - strtotime($order->getCreated()); ?>;
var totalSecondsleft = totalSeconds - totalSecondsPassed; var totalSecondsleft = totalSeconds - totalSecondsPassed;
$(document).ready(function () { $(document).ready(function () {
$('#qrcode').qrcode({width: 220, height: 220, text: "bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>"}); $('#qrcode').qrcode({width: 220, height: 220, text: "bitcoin:<?php echo $order->getAddr(); ?>?amount=<?php echo $order->getFormatedBits(); ?>"});
setInterval(function () { setInterval(function () {
totalSecondsleft--; totalSecondsleft--;
if (totalSecondsleft < 1) { if (totalSecondsleft < 1) {
totalSecondsleft = 0; totalSecondsleft = 0;
} }
var percent = (totalSecondsleft / totalSeconds) * 100; var percent = (totalSecondsleft / totalSeconds) * 100;
$("#timeleft").css('width', percent + "%").html(totalSecondsleft + " <?php echo __("Seconds Left"); ?>"); $("#timeleft").css('width', percent + "%").html(totalSecondsleft + " <?php echo __("Seconds Left"); ?>");
}, 1000); }, 1000);
check(); check();
}); });
function check() { function check() {
$.ajax({ $.ajax({
url: '<?php echo $global['webSiteRootURL']; ?>plugin/BlockonomicsYPT/check.php?addr=<?php echo $order->getAddr(); ?>', url: '<?php echo $global['webSiteRootURL']; ?>plugin/BlockonomicsYPT/check.php?addr=<?php echo $order->getAddr(); ?>',
success: function (response) { success: function (response) {
console.log(response); console.log(response);
if (response.status < 2) { 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>'); $("#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)); $("#received").html((response.bits_payed / 1.0e8));
setTimeout(function () { setTimeout(function () {
check(); check();
}, 3000); }, 3000);
}else{ }else{
response.status = 2; response.status = 2;
} }
$(".bstatus").not("#status"+response.status).hide(); $(".bstatus").not("#status"+response.status).hide();
$("#status"+response.status).fadeIn(); $("#status"+response.status).fadeIn();
} }
}); });
} }
</script> </script>
</body> </body>
</html> </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}, (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; 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- 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]= 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}, 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= 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- 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, 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= 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&& 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, (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)- 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:"+ 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);}},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+ 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), 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> 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], 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, [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, 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, 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, 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, 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* 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, (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), 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", 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); 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 <?php
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php'; require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/CDN/Storage/CDNStorage.php'; require_once $global['systemRootPath'] . 'plugin/CDN/Storage/CDNStorage.php';
class CDN extends PluginAbstract class CDN extends PluginAbstract
{ {
public function getTags() public function getTags()
{ {
return [ return [
PluginTags::$RECOMMENDED, PluginTags::$RECOMMENDED,
PluginTags::$LIVE, PluginTags::$LIVE,
PluginTags::$PLAYER, PluginTags::$PLAYER,
PluginTags::$STORAGE, PluginTags::$STORAGE,
]; ];
} }
public function getDescription() public function getDescription()
{ {
global $global; 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 " $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 " . "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"; . "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>. " $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"; . "This command will daily check your files and free some space into your server";
$help = ""; $help = "";
return $txt . $help; return $txt . $help;
} }
public function getName() public function getName()
{ {
return "CDN"; return "CDN";
} }
public function getUUID() public function getUUID()
{ {
return "CDN73225-3807-4167-ba81-0509dd280e06"; return "CDN73225-3807-4167-ba81-0509dd280e06";
} }
public function getPluginVersion() public function getPluginVersion()
{ {
return "2.0"; return "2.0";
} }
public function getEmptyDataObject() public function getEmptyDataObject()
{ {
global $global, $config; global $global, $config;
$obj = new stdClass(); $obj = new stdClass();
$obj->key = ""; $obj->key = "";
$obj->CDN = ""; $obj->CDN = "";
$obj->CDN_S3 = ""; $obj->CDN_S3 = "";
$obj->CDN_B2 = ""; $obj->CDN_B2 = "";
$obj->CDN_FTP = ""; $obj->CDN_FTP = "";
// this is a JSON with site_id + URL // this is a JSON with site_id + URL
$obj->CDN_YPTStorage = ""; // array $obj->CDN_YPTStorage = ""; // array
$obj->CDN_Live = ""; $obj->CDN_Live = "";
// this is a JSON with servers_id + URL // this is a JSON with servers_id + URL
$obj->CDN_LiveServers = ""; // array $obj->CDN_LiveServers = ""; // array
$obj->enable_storage = false; $obj->enable_storage = false;
$obj->storage_autoupload_new_videos = true; $obj->storage_autoupload_new_videos = true;
$obj->storage_users_can_choose_storage = true; $obj->storage_users_can_choose_storage = true;
$obj->storage_username = ""; $obj->storage_username = "";
$obj->storage_password = ""; $obj->storage_password = "";
$obj->storage_hostname = ""; $obj->storage_hostname = "";
return $obj; return $obj;
} }
public function getVideosManagerListButton() public function getVideosManagerListButton()
{ {
$btn = ''; $btn = '';
$videoHLSObj = AVideoPlugin::getDataObjectIfEnabled('VideoHLS'); $videoHLSObj = AVideoPlugin::getDataObjectIfEnabled('VideoHLS');
if(!empty($videoHLSObj)){ if(!empty($videoHLSObj)){
if (!empty($videoHLSObj->saveMP4CopyOnCDNStorageToAllowDownload) || !empty($videoHLSObj->saveMP3CopyOnCDNStorageToAllowDownload)) { 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>'; $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()) { 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>'; $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; return $btn;
} }
public function getPluginMenu() public function getPluginMenu()
{ {
global $global; global $global;
$fileAPIName = $global['systemRootPath'] . 'plugin/CDN/pluginMenu.html'; $fileAPIName = $global['systemRootPath'] . 'plugin/CDN/pluginMenu.html';
$content = file_get_contents($fileAPIName); $content = file_get_contents($fileAPIName);
$obj = $this->getDataObject(); $obj = $this->getDataObject();
$url = "https://youphp.tube/marketplace/CDN/iframe.php?hash={hash}"; $url = "https://youphp.tube/marketplace/CDN/iframe.php?hash={hash}";
$url = addQueryStringParameter($url, 'hash', $obj->key); $url = addQueryStringParameter($url, 'hash', $obj->key);
$url = addQueryStringParameter($url, 'webSiteRootURL', $global['webSiteRootURL']); $url = addQueryStringParameter($url, 'webSiteRootURL', $global['webSiteRootURL']);
$cdnMenu = str_replace('{url}', $url, $content); $cdnMenu = str_replace('{url}', $url, $content);
$storageMenu = ''; $storageMenu = '';
if (self::userCanMoveVideoStorage()) { if (self::userCanMoveVideoStorage()) {
$fileStorageMenu = $global['systemRootPath'] . 'plugin/CDN/Storage/pluginMenu.html'; $fileStorageMenu = $global['systemRootPath'] . 'plugin/CDN/Storage/pluginMenu.html';
$storageMenu = file_get_contents($fileStorageMenu); $storageMenu = file_get_contents($fileStorageMenu);
} }
return $cdnMenu.$storageMenu; return $cdnMenu.$storageMenu;
} }
/** /**
* *
* @param type $type enum(CDN, CDN_S3,CDN_B2,CDN_YPTStorage,CDN_Live,CDN_LiveServers) * @param type $type enum(CDN, CDN_S3,CDN_B2,CDN_YPTStorage,CDN_Live,CDN_LiveServers)
* @param type $id the ID of the URL in case the CDN is an array * @param type $id the ID of the URL in case the CDN is an array
* @return boolean * @return boolean
*/ */
public static function getURL($type = 'CDN', $id = 0) public static function getURL($type = 'CDN', $id = 0)
{ {
$obj = AVideoPlugin::getObjectData('CDN'); $obj = AVideoPlugin::getObjectData('CDN');
if (empty($obj->{$type})) { if (empty($obj->{$type})) {
return false; return false;
} }
if (isIPPrivate(getDomain())) { if (isIPPrivate(getDomain())) {
_error_log('The CDN will not work under a private network $type=' . $type); _error_log('The CDN will not work under a private network $type=' . $type);
return false; return false;
} }
$url = ''; $url = '';
switch ($type) { switch ($type) {
case 'CDN': case 'CDN':
case 'CDN_S3': case 'CDN_S3':
case 'CDN_B2': case 'CDN_B2':
case 'CDN_FTP': case 'CDN_FTP':
case 'CDN_Live': case 'CDN_Live':
$url = $obj->{$type}; $url = $obj->{$type};
break; break;
case 'CDN_LiveServers': case 'CDN_LiveServers':
case 'CDN_YPTStorage': case 'CDN_YPTStorage':
if (!empty($id)) { if (!empty($id)) {
$json = _json_decode($obj->{$type}); $json = _json_decode($obj->{$type});
//var_dump(!empty($json), is_object($json), is_array($json));//exit; //var_dump(!empty($json), is_object($json), is_array($json));//exit;
if (!empty($json) && (is_object($json) || is_array($json))) { if (!empty($json) && (is_object($json) || is_array($json))) {
foreach ($json as $value) { foreach ($json as $value) {
if ($value->id == $id) { if ($value->id == $id) {
$url = $value->URLToCDN; $url = $value->URLToCDN;
break; break;
} }
} }
} }
} }
//var_dump($url);exit; //var_dump($url);exit;
break; break;
} }
if (!empty($url) && isValidURL($url)) { if (!empty($url) && isValidURL($url)) {
return addLastSlash($url); return addLastSlash($url);
} }
return false; return false;
} }
public static function getCDN_S3URL() public static function getCDN_S3URL()
{ {
$plugin = AVideoPlugin::getDataObjectIfEnabled('AWS_S3'); $plugin = AVideoPlugin::getDataObjectIfEnabled('AWS_S3');
$CDN_S3 = ''; $CDN_S3 = '';
if (!empty($plugin)) { if (!empty($plugin)) {
$region = trim($plugin->region); $region = trim($plugin->region);
$bucket_name = trim($plugin->bucket_name); $bucket_name = trim($plugin->bucket_name);
$endpoint = trim($plugin->endpoint); $endpoint = trim($plugin->endpoint);
if (!empty($endpoint)) { if (!empty($endpoint)) {
$CDN_S3 = str_replace('https://', "https://{$bucket_name}.", $endpoint); $CDN_S3 = str_replace('https://', "https://{$bucket_name}.", $endpoint);
} elseif (!empty($plugin->region)) { } elseif (!empty($plugin->region)) {
$CDN_S3 = "https://{$bucket_name}.s3-accesspoint.{$region}.amazonaws.com"; $CDN_S3 = "https://{$bucket_name}.s3-accesspoint.{$region}.amazonaws.com";
} }
if (!empty($resp->CDN_S3)) { if (!empty($resp->CDN_S3)) {
$CDN_S3 = addLastSlash($resp->CDN_S3); $CDN_S3 = addLastSlash($resp->CDN_S3);
} }
} }
return $CDN_S3; return $CDN_S3;
} }
public static function getCDN_B2URL() public static function getCDN_B2URL()
{ {
$CDN_B2 = ''; $CDN_B2 = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('Blackblaze_B2'); $plugin = AVideoPlugin::getDataObjectIfEnabled('Blackblaze_B2');
if (!empty($plugin)) { if (!empty($plugin)) {
$b2 = new Blackblaze_B2(); $b2 = new Blackblaze_B2();
$CDN_B2 = $b2->getEndpoint(); $CDN_B2 = $b2->getEndpoint();
if (!empty($resp->CDN_B2)) { if (!empty($resp->CDN_B2)) {
$CDN_B2 = addLastSlash($resp->CDN_B2); $CDN_B2 = addLastSlash($resp->CDN_B2);
} }
} }
return $CDN_B2; return $CDN_B2;
} }
public static function getCDN_FTPURL() public static function getCDN_FTPURL()
{ {
$CDN_FTP = ''; $CDN_FTP = '';
$plugin = AVideoPlugin::getDataObjectIfEnabled('CDN'); $plugin = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (!empty($plugin)) { if (!empty($plugin)) {
$CDN_FTP = addLastSlash($plugin->endpoint); $CDN_FTP = addLastSlash($plugin->endpoint);
} }
return $CDN_FTP; return $CDN_FTP;
} }
public static function getVideoTags($videos_id) public static function getVideoTags($videos_id)
{ {
global $global; global $global;
if (empty($videos_id)) { if (empty($videos_id)) {
return []; return [];
} }
if (!Video::canEdit($videos_id)) { if (!Video::canEdit($videos_id)) {
return []; return [];
} }
$video = Video::getVideoLight($videos_id); $video = Video::getVideoLight($videos_id);
$sites_id = $video['sites_id']; $sites_id = $video['sites_id'];
$obj = new stdClass(); $obj = new stdClass();
$obj->label = 'Storage'; $obj->label = 'Storage';
$isMoving = CDNStorage::isMoving($videos_id); $isMoving = CDNStorage::isMoving($videos_id);
if ($isMoving) { if ($isMoving) {
$obj->type = "danger"; $obj->type = "danger";
$obj->text = '<i class="fas fa-sync fa-spin"></i> ' . __('Moving'); $obj->text = '<i class="fas fa-sync fa-spin"></i> ' . __('Moving');
} elseif (empty($sites_id)) { } elseif (empty($sites_id)) {
$obj->type = "success"; $obj->type = "success";
$obj->text = '<i class="fas fa-map-marker-alt"></i> ' . __('Local'); $obj->text = '<i class="fas fa-map-marker-alt"></i> ' . __('Local');
} else { } else {
$obj->type = "warning"; $obj->type = "warning";
$obj->text = "<i class=\"fas fa-project-diagram\"></i> " . __('Storage'); $obj->text = "<i class=\"fas fa-project-diagram\"></i> " . __('Storage');
} }
//var_dump($obj);exit; //var_dump($obj);exit;
return [$obj]; return [$obj];
} }
public function onEncoderNotifyIsDone($videos_id) public function onEncoderNotifyIsDone($videos_id)
{ {
return $this->processNewVideo($videos_id); return $this->processNewVideo($videos_id);
} }
public function onUploadIsDone($videos_id) public function onUploadIsDone($videos_id)
{ {
return $this->processNewVideo($videos_id); return $this->processNewVideo($videos_id);
} }
private function processNewVideo($videos_id) private function processNewVideo($videos_id)
{ {
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN'); $obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if ($obj->enable_storage) { if ($obj->enable_storage) {
if ($obj->storage_autoupload_new_videos) { if ($obj->storage_autoupload_new_videos) {
CDNStorage::moveLocalToRemote($videos_id, false); CDNStorage::moveLocalToRemote($videos_id, false);
} }
} }
} }
public static function userCanMoveVideoStorage() public static function userCanMoveVideoStorage()
{ {
$obj = AVideoPlugin::getDataObjectIfEnabled('CDN'); $obj = AVideoPlugin::getDataObjectIfEnabled('CDN');
if (empty($obj->enable_storage)) { if (empty($obj->enable_storage)) {
return false; return false;
} }
if (User::isAdmin()) { if (User::isAdmin()) {
return true; return true;
} }
if (!empty($obj->storage_users_can_choose_storage) && User::canUpload()) { if (!empty($obj->storage_users_can_choose_storage) && User::canUpload()) {
return true; return true;
} }
return false; return false;
} }
public function getFooterCode() public function getFooterCode()
{ {
global $global; global $global;
if (self::userCanMoveVideoStorage()) { if (self::userCanMoveVideoStorage()) {
include $global['systemRootPath'] . 'plugin/CDN/Storage/footer.php'; 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 <?php
/* /*
* This file is part of the `nicolab/php-ftp-client` package. * This file is part of the `nicolab/php-ftp-client` package.
* *
* (c) Nicolas Tallefourtane <dev@nicolab.net> * (c) Nicolas Tallefourtane <dev@nicolab.net>
* *
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
* *
* @copyright Nicolas Tallefourtane http://nicolab.net * @copyright Nicolas Tallefourtane http://nicolab.net
*/ */
namespace FtpClient; namespace FtpClient;
/** /**
* The FtpException class. * The FtpException class.
* Exception thrown if an error on runtime of the FTP client occurs. * Exception thrown if an error on runtime of the FTP client occurs.
* @inheritDoc * @inheritDoc
* @author Nicolas Tallefourtane <dev@nicolab.net> * @author Nicolas Tallefourtane <dev@nicolab.net>
*/ */
class FtpException extends \Exception class FtpException extends \Exception
{ {
} }

View file

@ -1,116 +1,116 @@
<?php <?php
/* /*
* This file is part of the `nicolab/php-ftp-client` package. * This file is part of the `nicolab/php-ftp-client` package.
* *
* (c) Nicolas Tallefourtane <dev@nicolab.net> * (c) Nicolas Tallefourtane <dev@nicolab.net>
* *
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
* *
* @copyright Nicolas Tallefourtane http://nicolab.net * @copyright Nicolas Tallefourtane http://nicolab.net
*/ */
namespace FtpClient; namespace FtpClient;
/** /**
* Wrap the PHP FTP functions * Wrap the PHP FTP functions
* *
* @method bool alloc() alloc(int $filesize, string &$result = null) Allocates space for a file to be uploaded * @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 cdup() cdup() Changes to the parent directory
* @method bool chdir() chdir(string $directory) Changes the current directory on a FTP server * @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 int chmod() chmod(int $mode, string $filename) Set permissions on a file via FTP
* @method bool close() close() Closes an FTP connection * @method bool close() close() Closes an FTP connection
* @method bool delete() delete(string $path) Deletes a file on the FTP server * @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 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 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 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 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 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 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 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 string mkdir() mkdir(string $directory) Creates a directory
* @method int nb_continue() nb_continue() Continues retrieving/sending a file (non-blocking) * @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_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_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_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 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 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 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 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 string pwd() pwd() Returns the current directory name
* @method bool quit() quit() Closes an FTP connection * @method bool quit() quit() Closes an FTP connection
* @method array raw() raw(string $command) Sends an arbitrary command to an FTP server * @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 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 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 rmdir() rmdir(string $directory) Removes a directory
* @method bool set_option() set_option(int $option, mixed $value) Set miscellaneous runtime FTP options * @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 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 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 * @method string systype() systype() Returns the system type identifier of the remote FTP server
* *
* @author Nicolas Tallefourtane <dev@nicolab.net> * @author Nicolas Tallefourtane <dev@nicolab.net>
*/ */
class FtpWrapper class FtpWrapper
{ {
/** /**
* The connection with the server * The connection with the server
* *
* @var resource * @var resource
*/ */
protected $conn; protected $conn;
/** /**
* Constructor. * Constructor.
* *
* @param resource &$connection The FTP (or SSL-FTP) connection (takes by reference). * @param resource &$connection The FTP (or SSL-FTP) connection (takes by reference).
*/ */
public function __construct(&$connection) public function __construct(&$connection)
{ {
$this->conn = &$connection; $this->conn = &$connection;
} }
/** /**
* Forward the method call to FTP functions * Forward the method call to FTP functions
* *
* @param string $function * @param string $function
* @param array $arguments * @param array $arguments
* @return mixed * @return mixed
* @throws FtpException When the function is not valid * @throws FtpException When the function is not valid
*/ */
public function __call($function, array $arguments) public function __call($function, array $arguments)
{ {
$function = 'ftp_' . $function; $function = 'ftp_' . $function;
if (function_exists($function)) { if (function_exists($function)) {
array_unshift($arguments, $this->conn); array_unshift($arguments, $this->conn);
return call_user_func_array($function, $arguments); return call_user_func_array($function, $arguments);
} }
throw new FtpException("{$function} is not a valid FTP function"); throw new FtpException("{$function} is not a valid FTP function");
} }
/** /**
* Opens a FTP connection * Opens a FTP connection
* *
* @param string $host * @param string $host
* @param int $port * @param int $port
* @param int $timeout * @param int $timeout
* @return resource * @return resource
*/ */
public function connect($host, $port = 21, $timeout = 90) public function connect($host, $port = 21, $timeout = 90)
{ {
return ftp_connect($host, $port, $timeout); return ftp_connect($host, $port, $timeout);
} }
/** /**
* Opens a Secure SSL-FTP connection * Opens a Secure SSL-FTP connection
* @param string $host * @param string $host
* @param int $port * @param int $port
* @param int $timeout * @param int $timeout
* @return resource * @return resource
*/ */
public function ssl_connect($host, $port = 21, $timeout = 90) public function ssl_connect($host, $port = 21, $timeout = 90)
{ {
return ftp_ssl_connect($host, $port, $timeout); return ftp_ssl_connect($host, $port, $timeout);
} }
} }

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,32 +1,32 @@
<?php <?php
require_once dirname(__FILE__) . '/../../videos/configuration.php'; require_once dirname(__FILE__) . '/../../videos/configuration.php';
if (!isCommandLineInterface()) { if (!isCommandLineInterface()) {
die('Command Line only'); die('Command Line only');
} }
$daysLimit = 3; $daysLimit = 3;
// delete object cache // delete object cache
$cacheDir = ObjectYPT::getCacheDir(); $cacheDir = ObjectYPT::getCacheDir();
if (empty($cacheDir) || !preg_match('/YPTObjectCache/', $cacheDir)) { if (empty($cacheDir) || !preg_match('/YPTObjectCache/', $cacheDir)) {
die('Wrong dir: '.$cacheDir); die('Wrong dir: '.$cacheDir);
} }
_error_log('crontab.php: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); _error_log('crontab.php: '.json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
echo "deleting {$cacheDir}".PHP_EOL; echo "deleting {$cacheDir}".PHP_EOL;
// delete caches 3 days old // delete caches 3 days old
$cmd = "find {$cacheDir}* -mtime +{$daysLimit} -type f -name \"*.cache\" -exec rm {} \;".PHP_EOL; $cmd = "find {$cacheDir}* -mtime +{$daysLimit} -type f -name \"*.cache\" -exec rm {} \;".PHP_EOL;
echo "Command: {$cmd}"; echo "Command: {$cmd}";
exec($cmd); exec($cmd);
//delete site cache //delete site cache
$cacheDir = getCacheDir(); $cacheDir = getCacheDir();
if (empty($cacheDir) || !preg_match('/cache/', $cacheDir)) { if (empty($cacheDir) || !preg_match('/cache/', $cacheDir)) {
die('Wrong dir: '.$cacheDir); die('Wrong dir: '.$cacheDir);
} }
echo "deleting {$cacheDir}".PHP_EOL; echo "deleting {$cacheDir}".PHP_EOL;
// delete caches 3 days old // delete caches 3 days old
$cmd = "find {$cacheDir}* -mtime +{$daysLimit} -type f -name \"*.cache\" -exec rm {} \;".PHP_EOL; $cmd = "find {$cacheDir}* -mtime +{$daysLimit} -type f -name \"*.cache\" -exec rm {} \;".PHP_EOL;
echo "Command: {$cmd}"; echo "Command: {$cmd}";
exec($cmd); exec($cmd);

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,89 +1,89 @@
<?php <?php
global $global; global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php'; require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php'; require_once $global['systemRootPath'] . 'plugin/CloneSite/functions.php';
class CloneSite extends PluginAbstract class CloneSite extends PluginAbstract
{ {
public function getTags() public function getTags()
{ {
return [ return [
PluginTags::$SECURITY, PluginTags::$SECURITY,
PluginTags::$FREE, PluginTags::$FREE,
]; ];
} }
public function getDescription() public function getDescription()
{ {
global $global; global $global;
$obj = $this->getDataObject(); $obj = $this->getDataObject();
$txt = "Clone and Backup AVideo Sites"; $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>"; $txt .= "<br>Crontab every day at 1am:<br><code>0 1 * * * php {$global['systemRootPath']}plugin/CloneSite/cloneClient.json.php {$obj->myKey}</code>";
if (!isRsync()) { if (!isRsync()) {
$txt .= "<div class='alert alert-danger'>To use rsync feature you must install it <code>sudo apt-get install rsync</code></div>"; $txt .= "<div class='alert alert-danger'>To use rsync feature you must install it <code>sudo apt-get install rsync</code></div>";
} }
if (!isSshpass()) { if (!isSshpass()) {
$txt .= "<div class='alert alert-danger'>To use rsync feature you must install sshpass <code>sudo apt-get install sshpass</code></div>"; $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>"; $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; return $txt . $help;
} }
public function getName() public function getName()
{ {
return "CloneSite"; return "CloneSite";
} }
public function getUUID() public function getUUID()
{ {
return "c0731de9-b4f7-4462-bda6-458b0736593d"; return "c0731de9-b4f7-4462-bda6-458b0736593d";
} }
public function getPluginVersion() public function getPluginVersion()
{ {
return "1.1"; return "1.1";
} }
public function getPluginMenu() public function getPluginMenu()
{ {
global $global; global $global;
$filename = $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html'; $filename = $global['systemRootPath'] . 'plugin/CloneSite/pluginMenu.html';
return file_get_contents($filename); return file_get_contents($filename);
} }
public function getEmptyDataObject() public function getEmptyDataObject()
{ {
global $global; global $global;
$obj = new stdClass(); $obj = new stdClass();
$obj->cloneSiteURL = ""; $obj->cloneSiteURL = "";
$obj->cloneSiteSSHIP = ""; $obj->cloneSiteSSHIP = "";
$obj->cloneSiteSSHUser = ""; $obj->cloneSiteSSHUser = "";
$obj->cloneSiteSSHPort = "22"; $obj->cloneSiteSSHPort = "22";
$o = new stdClass(); $o = new stdClass();
$o->type = "encrypted"; $o->type = "encrypted";
$o->value = ""; $o->value = "";
$obj->cloneSiteSSHPassword = $o; $obj->cloneSiteSSHPassword = $o;
$obj->useRsync = true; $obj->useRsync = true;
$obj->MaintenanceMode = false; $obj->MaintenanceMode = false;
$obj->myKey = md5($global['systemRootPath'].$global['salt']); $obj->myKey = md5($global['systemRootPath'].$global['salt']);
return $obj; return $obj;
} }
public function getStart() public function getStart()
{ {
$obj = $this->getDataObject(); $obj = $this->getDataObject();
if ($obj->MaintenanceMode) { if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode"); $m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getStart(); $m->getStart();
} }
} }
public function getFooterCode() public function getFooterCode()
{ {
$obj = $this->getDataObject(); $obj = $this->getDataObject();
if ($obj->MaintenanceMode) { if ($obj->MaintenanceMode) {
$m = AVideoPlugin::loadPlugin("MaintenanceMode"); $m = AVideoPlugin::loadPlugin("MaintenanceMode");
$m->getFooterCode(); $m->getFooterCode();
} }
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,59 +1,59 @@
<?php <?php
global $global; global $global;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php'; require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
class CookieAlert extends PluginAbstract { class CookieAlert extends PluginAbstract {
public function getDescription() { public function getDescription() {
return "EU Cookie Law Notice Plugin"; return "EU Cookie Law Notice Plugin";
} }
public function getName() { public function getName() {
return "CookieAlert"; return "CookieAlert";
} }
public function getUUID() { public function getUUID() {
return "6daca392-7b14-44fb-aa33-51cba620d92e"; return "6daca392-7b14-44fb-aa33-51cba620d92e";
} }
public function getPluginVersion() { public function getPluginVersion() {
return "1.0"; return "1.0";
} }
public function getHeadCode() { public function getHeadCode() {
if($this->doNotShow()){ if($this->doNotShow()){
return ""; return "";
} }
$obj = $this->getDataObject(); $obj = $this->getDataObject();
global $global; global $global;
$css = '<link href="' . getCDN() . 'plugin/CookieAlert/cookiealert.css" rel="stylesheet" type="text/css"/>'; $css = '<link href="' . getCDN() . 'plugin/CookieAlert/cookiealert.css" rel="stylesheet" type="text/css"/>';
$css .= '<style></style>'; $css .= '<style></style>';
return $css; return $css;
} }
private function doNotShow(){ private function doNotShow(){
$baseName = basename($_SERVER["SCRIPT_FILENAME"]); $baseName = basename($_SERVER["SCRIPT_FILENAME"]);
if(isEmbed() || preg_match("/embed/i", $baseName) || !empty($_GET['embed'])){ if(isEmbed() || preg_match("/embed/i", $baseName) || !empty($_GET['embed'])){
return true; return true;
} }
return false; return false;
} }
public function getEmptyDataObject() { public function getEmptyDataObject() {
$obj = new stdClass(); $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->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'; $obj->btnText = 'I agree';
return $obj; return $obj;
} }
public function getFooterCode() { public function getFooterCode() {
if($this->doNotShow()){ if($this->doNotShow()){
return ""; return "";
} }
$obj = $this->getDataObject(); $obj = $this->getDataObject();
global $global; global $global;
include $global['systemRootPath'] . 'plugin/CookieAlert/footer.php'; include $global['systemRootPath'] . 'plugin/CookieAlert/footer.php';
} }
} }

View file

@ -1,11 +1,11 @@
<!-- COOKIES --> <!-- COOKIES -->
<div class="alert alert-dismissible text-center cookiealert" role="alert"> <div class="alert alert-dismissible text-center cookiealert" role="alert">
<div class="cookiealert-container"> <div class="cookiealert-container">
<?php echo $obj->text; ?> <?php echo $obj->text; ?>
<button type="button" class="btn btn-primary btn-sm acceptcookies" aria-label="Close"> <button type="button" class="btn btn-primary btn-sm acceptcookies" aria-label="Close">
<?php echo $obj->btnText; ?> <?php echo $obj->btnText; ?>
</button> </button>
</div> </div>
</div> </div>
<!-- /COOKIES --> <!-- /COOKIES -->
<script src="<?php echo getCDN(); ?>plugin/CookieAlert/cookiealert-standalone.js"></script> <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 <?php
require_once '../../videos/configuration.php'; require_once '../../videos/configuration.php';
session_write_close(); session_write_close();
header('Content-Type: application/json'); header('Content-Type: application/json');
$name = "advancedCustom.json.php"; $name = "advancedCustom.json.php";
$obj = ObjectYPT::getCache($name, 60); $obj = ObjectYPT::getCache($name, 60);
if(empty($obj)){ if(empty($obj)){
$obj = AVideoPlugin::getObjectData("CustomizeAdvanced"); $obj = AVideoPlugin::getObjectData("CustomizeAdvanced");
ObjectYPT::setCache($name, $obj); ObjectYPT::setCache($name, $obj);
} }
echo json_encode($obj); echo json_encode($obj);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

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