Build you own webservice

Build you own webservices in php using nusoap library.

<?php

ini_set("soap.wsdl_cache_enabled", "0");

require_once('./common.php');
require_once('./lib/nusoap.php');

$server = new soap_server;
global $common, $device_id, $start, $end;

$server->configureWSDL('trackn', 'urn:tracknwsdl');

$server->register('update_location',
    array(
		'device_number' => 'xsd:string', 
		'latitude' => 'xsd:string', 
		'longitude' => 'xsd:string', 
		'battery_status' => 'xsd:string',
		'speed' => 'xsd:string'),
    array('return' => 'xsd:boolean'),
    'urn:tracknwsdl',
    'urn:tracknwsdl#locate_device',
    'rpc',
    'encoded',
    'Find the location of device'
);
// Define the method as a PHP function
function update_location($device_number, $latitude, $longitude, $battery_status, $speed=0) {
	
	global $common;
	
	// Finding Entity Id from device number
	$sql = "select EntityId FROM jos_tbl_entity WHERE DeviceNumber='".$device_number."'";
	$rows = $common->get_result($sql);
	
	if($common->check_array($rows))
	{
		$entity_id = $rows[0]['EntityId'];
		
		$address = findAddress($latitude, $longitude);
		
		$arr = array(
					'EntityId' 			=> $entity_id,
					'Longitude'			=> $longitude,
					'Latitude'			=> $latitude,
					'address'			=> $address,
					'Battery_status' 	=> $battery_status,
					'Speed'				=> $speed,
					'bActive'			=> '1'
				);
		$common->insert('jos_tbl_entity_position', $arr);
		
		return true;
	}
	else {
		return false;
	}
}

$server->register('user_action',
    array(
		'device_number' => 'xsd:string',
		'latitude' => 'xsd:string', 
		'longitude' => 'xsd:string', 
		'action_type' => 'xsd:string',
		'notes' => 'xsd:string'
		),
    array('return' => 'xsd:boolean'),
    'urn:tracknwsdl',
    'urn:tracknwsdl#locate_device',
    'rpc',
    'encoded',
    'Find the location of device'
);
// Define the method as a PHP function
function user_action($device_number, $latitude, $longitude, $action_type, $notes='') {
	
	global $common, $device_id, $start, $end;

	/*
	$mtime = explode(" ", microtime());
	$start = doubleval($mtime[1]) + doubleval($mtime[0]); 
	
	$mtime = explode(" ", microtime());
	$end   = doubleval($mtime[1]) + doubleval($mtime[0]);
	$time_elapsed = round(number_format(abs($start - $end), 5, '.', ''));
	*/

	$common->log_msg("User Action Method");
	
	// Finding Entity Id from device number
	$sql = "select EntityId FROM jos_tbl_entity WHERE DeviceNumber='".$device_number."'";
	$rows = $common->get_result($sql);
	
	if($common->check_array($rows)) {
		
		$entity_id = $rows[0]['EntityId'];
		
		// Finding previous status to stop
		$sql_find_status = "select * FROM jos_tbl_user_action WHERE EntityId=$entity_id order by UserActionId desc limit 0,1";
		$rows_find_status = $common->get_result($sql_find_status);
		
		$address = findAddress($latitude, $longitude);
		
		// changing the status of previous record to "stop"
		if($common->check_array($rows_find_status)) {
				
			$row = $rows_find_status[0];
			
			$prev_row = array(
				'EntityId' 		=> $entity_id,
				'ActionType' 	=> $row['ActionType'],
				'Latitude' 		=> $latitude,
				'Longitude' 	=> $longitude,
				'address' 		=> $address,
				'Notes' 		=> $notes
			);

			$common->insert('jos_tbl_user_action', $prev_row);

		}
		
		
		$arr = array(
				'EntityId' 				=> $entity_id,
				'ActionType' 			=> $action_type,
				'Latitude'				=> $latitude,
				'Longitude'				=> $longitude,
				'address'				=> $address,
				'Notes'					=> $notes,
				'Action_status'			=> 1
			);
		$common->insert('jos_tbl_user_action', $arr);
		
		return true;
	}
	else {
		return false;
	}
}

$server->register('sos',
    array(
		'device_number' => 'xsd:string', 
		'latitude' => 'xsd:string', 
		'longitude' => 'xsd:string', 
		),
    array('return' => 'xsd:boolean'),
    'urn:tracknwsdl',
    'urn:tracknwsdl#sos',
    'rpc',
    'encoded',
    'Sending sos message.'
);
function sos($device_number, $latitude, $longitude) {

	global $common;
	
	$sql = "select EntityId FROM jos_tbl_entity WHERE DeviceNumber='".$device_number."'";
	$rows = $common->get_result($sql);
	
	if($common->check_array($rows))
	{
		$entity_id = $rows[0]['EntityId'];
		
		$address = findAddress($latitude, $longitude);
		
		// Inserting data into sos table
		$arr = array(
			'EntityId' 				=> $entity_id,
			'Latitude'				=> $latitude,
			'Longitude'				=> $longitude,
			'address'				=> $address
		);
		
		$common->insert('jos_tbl_send_sos', $arr);
		
		$rs = true;
	}
	else {
		$rs = false;
	}

	return $rs;
}

$server->wsdl->addComplexType(
    'entity_list',
    'complexType',
    'struct',
    'all',
    '',
   	array(
	        'device_number' 	=> array('name' => 'device_no', 		'type' => 'xsd:string'),
	        'user_name' 		=> array('name' => 'user_name', 		'type' => 'xsd:string'),
	        'longitude' 		=> array('name' => 'longitude', 		'type' => 'xsd:string'),
	        'latitude' 			=> array('name' => 'latitude', 			'type' => 'xsd:string'),
	        'address' 			=> array('name' => 'address', 			'type' => 'xsd:string'),
	        'battery_status' 	=> array('name' => 'battery_status',	'type' => 'xsd:string')
	)
);

$server->wsdl->addComplexType(
    'entity_list2',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
   	array(
		array('ref'=>'SOAP-ENC:arrayType',
		'wsdl:arrayType'=>'tns:entity_list[]')
	),
	'tns:entity_list'
);

$server->register('user_entity_status',
    array('device_number' => 'xsd:string'),
    array('return' => 'tns:entity_list2'),
    'urn:tracknwsdl',
    'urn:tracknwsdl#user_entity_status',
    'rpc',
    'encoded',
    'User detials of a particular user.'
);
function user_entity_status($device_number) {

	global $common;
	$return = array();
	
	$common->log_msg("User_entity_status");

	$sql = "select UserId FROM jos_tbl_entity WHERE DeviceNumber='".$device_number."'";
	$rows = $common->get_result($sql);
	
	if($common->check_array($rows))
	{
		$user_id = $rows[0]['UserId'];
		
		// Searching for the child records
		$sql_child_users = "select EntityId, UserId, DeviceNumber, ObjectTypeId FROM jos_tbl_entity WHERE UserId='".$user_id."' and DeviceNumber != '".$device_number."'";

		$rows_child_users = $common->get_result($sql_child_users);
		
		if($common->check_array($rows_child_users)) {
			
			foreach ($rows_child_users as $row) {

				$arr = array();

				$object_type_key = $common->get_row("jos_tbl_object_type", $row['ObjectTypeId'], 'ObjectKey');
				
				$name='';
				switch($object_type_key) {
					case 'person':
						$name = $common->get_row("jos_tbl_person", $row['EntityId'], 'FirstName');
					break;

					case 'vehicle':
						$name = $common->get_row("jos_tbl_vehicle", $row['EntityId'], 'DriverName');
					break;

					case 'object':
						$name = $common->get_row("jos_tbl_object", $row['EntityId'], 'FirstName');
					break;
				}


				$sql_entity_pos = "select EntityPositionId, Longitude, Latitude, address, Battery_status FROM jos_tbl_entity_position WHERE EntityId='".$row['EntityId']."' order by EntityPositionId desc limit 0,1";
				$rows_entity_pos = $common->get_result($sql_entity_pos);
				$row_entity_pos = $rows_entity_pos[0];
				
				$arr['device_number'] 	= $row['DeviceNumber'];
				$arr['user_name'] 		= $name;
				$arr['longitude'] 		= $row_entity_pos['Longitude'];
				$arr['latitude'] 		= $row_entity_pos['Latitude'];
				$arr['address'] 		= $row_entity_pos['address'];
				$arr['battery_status'] 	= $row_entity_pos['Battery_status'];
		
				$return[] = $arr;
			}
		}
	}

	return $return;
}

function findAddress($Lat, $Lng) {
		
	$address = getGeoname($Lat, $Lng);
	if(empty($address)) {
		$address = getAddress($Lat, $Lng);
	}

	return $address;
}


function getAddress($Lat, $Lng) {

	$ch = curl_init();
	$url = "http://ws.geonames.org/findNearestAddress?lat=$Lat&lng=$Lng"; // For US Only
	curl_setopt($ch, CURLOPT_URL, $url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	//curl_setopt($ch, CURLOPT_POSTFIELDS, '');
	$temp = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$returnData = curl_exec ($ch);
	$error = curl_error( $ch );
	if( !empty( $error )) {

		curl_close ($ch);
		$_SESSION['CURL_ERROR'] = true;
		$_SESSION['CURL_ERROR_TXT'] = $error;

		return "<br/><span class=\"message\"> CURL error: ".$error."</span>";
	}
	curl_close ($ch);

	$arr = xml2array($returnData);
	$arr_address = $arr['geonames']['address'];

	if( (is_array($arr_address)) && (count($arr_address) > 0) ) {

		$address = $arr_address['streetNumber']." ".$arr_address['street'].", ".$arr_address['placename'].", ".$arr_address['adminCode1']." ".$arr_address['postalcode'].", ".$arr_address['countryCode'];

	}
	else {
		$address = '';
	}

	return $address;
}


function getGeoname($Lat, $Lng) {

	$ch = curl_init();
	$url = "http://ws.geonames.org/extendedFindNearby?lat=$Lat&lng=$Lng";
	curl_setopt($ch, CURLOPT_URL, $url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$temp = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$returnData = curl_exec($ch);
	$error = curl_error( $ch );
	if( !empty( $error )) {

		curl_close ($ch);
		$_SESSION['CURL_ERROR'] = true;
		$_SESSION['CURL_ERROR_TXT'] = $error;

		return "<br/><span class=\"message\"> CURL error: ".$error."</span>";
	}
	curl_close ($ch);

	$arr = xml2array($returnData);
	$arr_address = $arr['geonames']['geoname'];

	if( (is_array($arr_address)) && (count($arr_address) > 0) ) {

		$address = $arr_address['4']['name'].", ".$arr_address['3']['name'].", ".$arr_address['3']['countryCode'];

	}
	else {
		$address = '';
	}

	return $address;
}

function xml2array($contents, $get_attributes=1, $priority = 'tag') {
	if(!$contents) return array();

	if(!function_exists('xml_parser_create')) {
		//print "'xml_parser_create()' function not found!";
		return array();
	}

	//Get the XML parser of PHP - PHP must have this module for the parser to work
	$parser = xml_parser_create('');
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	xml_parse_into_struct($parser, trim($contents), $xml_values);
	xml_parser_free($parser);

	if(!$xml_values) return;//Hmm...

	//Initializations
	$xml_array = array();
	$parents = array();
	$opened_tags = array();
	$arr = array();

	$current = &$xml_array; //Refference

	//Go through the tags.
	$repeated_tag_index = array();//Multiple tags with same name will be turned into an array
	foreach($xml_values as $data) {
		unset($attributes,$value);//Remove existing values, or there will be trouble

		//This command will extract these variables into the foreach scope
		// tag(string), type(string), level(int), attributes(array).
		extract($data);//We could use the array by itself, but this cooler.

		$result = array();
		$attributes_data = array();
		
		if(isset($value)) {
			if($priority == 'tag') $result = $value;
			else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
		}

		//Set the attributes too.
		if(isset($attributes) and $get_attributes) {
			foreach($attributes as $attr => $val) {
				if($priority == 'tag') $attributes_data[$attr] = $val;
				else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
			}
		}

		//See tag status and do the needed.
		if($type == "open") {//The starting of the tag '<tag>'
			$parent[$level-1] = &$current;
			if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
				$current[$tag] = $result;
				if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
				$repeated_tag_index[$tag.'_'.$level] = 1;

				$current = &$current[$tag];

			} else { //There was another element with the same tag name

				if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					$repeated_tag_index[$tag.'_'.$level]++;
				} else {//This section will make the value an array if multiple tags with the same name appear together
					$current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
					$repeated_tag_index[$tag.'_'.$level] = 2;
					
					if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
						$current[$tag]['0_attr'] = $current[$tag.'_attr'];
						unset($current[$tag.'_attr']);
					}

				}
				$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
				$current = &$current[$tag][$last_item_index];
			}

		} elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
			//See if the key is already taken.
			if(!isset($current[$tag])) { //New Key
				$current[$tag] = $result;
				$repeated_tag_index[$tag.'_'.$level] = 1;
				if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

			} else { //If taken, put all things inside a list(array)
				if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

					// ...push the new element into that array.
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					
					if($priority == 'tag' and $get_attributes and $attributes_data) {
						$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
					}
					$repeated_tag_index[$tag.'_'.$level]++;

				} else { //If it is not an array...
					$current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
					$repeated_tag_index[$tag.'_'.$level] = 1;
					if($priority == 'tag' and $get_attributes) {
						if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
							
							$current[$tag]['0_attr'] = $current[$tag.'_attr'];
							unset($current[$tag.'_attr']);
						}
						
						if($attributes_data) {
							$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
						}
					}
					$repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
				}
			}

		} elseif($type == 'close') { //End of tag '</tag>'
			$current = &$parent[$level-1];
		}
	}
	
	return($xml_array);
}





// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
exit();

Usage

Steps: 1. Download nusoap library from internet 2. Make Your own functions in this file and enjoy you own webservice.


Comments

Add your comment