function getLanguage($text)
{
    #Sample Response: {"responseData": {"language":"en","isReliable":false,"confidence":0.0867152}, "responseDetails": null, "responseStatus": 200}
    #URL http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=
    $URL = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=" . urlencode($text);
    $downloaded_page = http_get($URL, "");
    $lang = $downloaded_page['FILE'];
    $lang = return_between($lang, "\"language\":\"", "\",", EXCL);
    echo "LANGUAGE IS: {$lang}\n\n";
    return $lang;
}
function download_parse_rss($target)
{
    # download tge rss page
    $news = http_get($target, "");
    # Parse title & copyright notice
    $rss_array['TITLE'] = return_between($news['FILE'], "<title>", "</title>", EXCL);
    $rss_array['COPYRIGHT'] = return_between($news['FILE'], "<copyright>", "</copyright>", EXCL);
    # Parse the items
    $item_array = parse_array($news['FILE'], "<item>", "</item>");
    for ($xx = 0; $xx < count($item_array); $xx++) {
        $rss_array['ITITLE'][$xx] = return_between($item_array[$xx], "<title>", "</title>", EXCL);
        $rss_array['ILINK'][$xx] = return_between($item_array[$xx], "<link>", "</link>", EXCL);
        $rss_array['IDESCRIPTION'][$xx] = return_between($item_array[$xx], "<description>", "</description>", EXCL);
        $rss_array['IPUBDATE'][$xx] = return_between($item_array[$xx], "<pubDate>", "</pubDate>", EXCL);
    }
    return $rss_array;
}
function get_attribute($tag, $attribute)
{
    # Use Tidy library to 'clean' input
    $cleaned_html = tidy_html($tag);
    # Remove all line feeds from the string
    $cleaned_html = str_replace("\r", "", $cleaned_html);
    $cleaned_html = str_replace("\n", "", $cleaned_html);
    # Use return_between() to find the properly quoted value for the attribute
    return return_between($cleaned_html, strtoupper($attribute) . "=\"", "\"", EXCL);
}
// Your POP3 email address
define("PASS", YOUR_PASSWORD);
// Your POP3 password
// Connect to POP3 server
$connection_array = POP3_connect(SERVER, USER, PASS);
$POP3_connection = $connection_array['handle'];
$list_array = POP3_list($POP3_connection);
$message = POP3_retr($POP3_connection, 1);
$ret_path = return_between($message, "Return-Path: ", "\n", EXCL);
$deliver_to = return_between($message, "Delivered-To: ", "\n", EXCL);
$date = return_between($message, "Date: ", "\n", EXCL);
$from = return_between($message, "From: ", "\n", EXCL);
$subject = return_between($message, "Subject: ", "\n", EXCL);
$content_type = return_between($message, "Content-Type: ", "\n", EXCL);
$boundary = get_attribute($content_type, "boundary");
$raw_msg = return_between($message, "--" . $boundary, "--" . $boundary, EXCL);
$clean_msg = return_between($raw_msg, chr(13) . chr(10) . chr(13) . chr(10), chr(13) . chr(10) . chr(13) . chr(10), EXCL);
echo "<xmp>ret_path   = {$ret_path}</xmp>";
echo "<xmp>deliver_to   = {$deliver_to}</xmp>";
echo "<xmp>date   = {$date}</xmp>";
echo "<xmp>subject  = {$subject}</xmp>";
echo "<xmp>content_type   = {$content_type} </xmp>";
echo "<xmp>boundary  = {$boundary} </xmp>";
echo "<xmp>clean_msg = {$clean_msg}</xmp>";
?>
<xmp><?php 
var_dump($message);
?>
</xmp>
</body>
</html>
Example #5
0
The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the 
software without specific, written prior permission. Title to copyright in this software and any associated 
documentation will at all times remain with copyright holders.

Copyright 2007, Michael Schrenk

THIS SCRIPT IS FOR DEMONSTRATION PURPOSES ONLY! 
    It is not suitable for any use other than demonstrating 
    the concepts presented in Webbots, Spiders and Screen Scrapers. 
########################################################################
*/
?>



<?php 
#PHP_LIBRARY_PATH
$PHP_LIBRARY_PATH = "../phplibs";
# Include libraries
include "{$PHP_LIBRARY_PATH}/LIB_parse.php";
include "{$PHP_LIBRARY_PATH}/LIB_http.php";
# Download a web page
$web_page = http_get($target = "http://www.nostarch.com", $referer = "");
# Parse the title of the web page, inclusive of the title tags
$title_incl = return_between($web_page['FILE'], "<title>", "</title>", INCL);
# Parse the title of the web page, exclusive of the title tags
$title_excl = return_between($web_page['FILE'], "<title>", "</title>", EXCL);
# Display the parsed text
echo "title_incl = " . $title_incl;
echo "\n";
echo "title_excl = " . $title_excl;
 $Swagger_BasePath = $Swagger['basePath'];
 $Swagger_Scheme = $Swagger['schemes'][0];
 $Swagger_Produces = $Swagger['produces'][0];
 //echo $Swagger_Title . "<br />";
 $Swagger_Definitions = $Swagger['definitions'];
 $Swagger_Paths = $Swagger['paths'];
 foreach ($Swagger_Paths as $key => $value) {
     $Path_Route = $key;
     //echo $Path_Route . "<br />";
     // Each Path Variable
     $id = 0;
     $Path_Variable_Count = 1;
     $Path_Variables = "";
     $Begin_Tag = "{";
     $End_Tag = "}";
     $path_variables_array = return_between($Path_Route, $Begin_Tag, $End_Tag, EXCL);
     $Path_Route = str_replace("{", ":", $Path_Route);
     $Path_Route = str_replace("}", "", $Path_Route);
     // Each Path
     foreach ($value as $key2 => $value2) {
         $Definition = "";
         $Path = "";
         $Path_Verb = $key2;
         $Path_Summary = $value2['summary'];
         $Path_Desc = $value2['description'];
         $Path_OperationID = $value2['operationId'];
         $Path_Parameters = $value2['parameters'];
         $Path_Responses = $value2['responses'];
         //echo $Path_Verb . "<br />";
         //echo $Path_Summary . "<br />";
         // Each Verb
function get_attribute($tag, $attribute)
{
    #Use \" and not ' to denote fields //Added by SAH
    $cleaned_html = $tag;
    //str_replace("'", "\"", $tag);
    //Don't do this incase someone has an unescaped ' inside an attributedelimiated with \" \"
    # Use Tidy library to 'clean' input
    $cleaned_html = tidy_html($cleaned_html);
    # Remove all line feeds from the string
    $cleaned_html = str_replace("\r", "", $cleaned_html);
    $cleaned_html = str_replace("\n", "", $cleaned_html);
    //print "CLEANED: $cleaned_html \n";
    # Use return_between() to find the properly quoted value for the attribute
    $t = return_between($cleaned_html, strtoupper($attribute) . "=\"", "\"", EXCL);
    if (strlen($t) == 0) {
        $t = return_between($cleaned_html, strtoupper($attribute) . "='", "'", EXCL);
    }
    if (strlen($t) == 0) {
        $t = false;
    }
    //SAH explicitly return false if not found
    return $t;
}
Example #8
0
         if ($i == 0) {
             echo "StartStop:" . $startStop . "," . "EndStop:" . $endStop . ",depotErrorCode:" . intval($depotErrorCode) . "n";
         }
         echo "<br/>";
         //echo "Route#".$i;
         echo "ErrorCode:" . intval(return_between($indirectRouteErrorCodeArray[$i], "<ErrorCode>", "</ErrorCode>", EXCL)) . "\t";
         //echo "StartStop:".$indirectStartStopsArray[$i]."\t";
         //echo "StartBuses:".$indirectStartBusesArray[$i]."\t";
         //echo "FirstJunction:".$indirectFirstJunctionsArray[$i]."\t";
         echo "DistanceBetweenJucntion:" . $indirectDistanceBetweenJunctionArray[$i] . "\t";
         //echo "SecondJunction:".$indirectSecondJunctionsArray[$i]."\t";
         //echo "EndBuses:".$indirectEndBusesArray[$i]."\t";
         //echo "EndStop:".$indirectEndStopsArray[$i]."\t";
         echo "TotalIndirectRouteDistance:" . $indirectTotalIndirectRouteDistanceArray[$i] . "\t";
         echo "TotalRouteDistance" . $indirectTotalRouteDistanceArray[$i] . "\t";
         $sql = "INSERT INTO depotbusroutes (DepotErrorCode,\r\n\t\t\t\t\t\t\t\t\t\t\t  SourceStartStop,\r\n\t\t\t\t\t\t\t\t\t\t\t  DestinationEndStop,\r\n\t\t\t\t\t\t\t\t\t\t\t  DepotNameString,\r\n\t\t\t\t\t\t\t\t\t\t\t  BusesBetweenStopAndDepot,\r\n\t\t\t\t\t\t\t\t\t\t\t  DistanceBetweenDepotAndStop,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectRouteErrorCode,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectStartStop,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectStartBuses,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectFirstJunction,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectSecondJunction,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectDistanceBetweenJunction,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectEndStop,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectEndBuses,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectTotalIndirectRouteDistance,\r\n\t\t\t\t\t\t\t\t\t\t\t  IndirectTotalRouteDistance) Values('" . intval($depotErrorCode) . "','" . $startStop . "','" . $endStop . "','" . $depotNameString . "','" . $busesBetweenStopAndDepot . "','" . floatval($distanceBetweenDepotAndStop) . "','" . intval(return_between($indirectRouteErrorCodeArray[$i], "<ErrorCode>", "</ErrorCode>", EXCL)) . "','" . return_between($indirectStartStopsArray[$i], "<StartStop>", "</StartStop>", EXCL) . "','" . return_between($indirectStartBusesArray[$i], "<StartBuses>", "</StartBuses>", EXCL) . "','" . return_between($indirectFirstJunctionsArray[$i], "<FirstJunction>", "</FirstJunction>", EXCL) . "','" . return_between($indirectSecondJunctionsArray[$i], "<SecondJunction>", "</SecondJunction>", EXCL) . "','" . floatval(return_between($indirectDistanceBetweenJunctionArray[$i], "<DistanceBetweenJunction>", "</DistanceBetweenJunction>", EXCL)) . "','" . return_between($indirectEndStopsArray[$i], "<EndStop>", "</EndStop>", EXCL) . "','" . return_between($indirectEndBusesArray[$i], "<EndBuses>", "</EndBuses>", EXCL) . "','" . floatval(return_between($indirectTotalIndirectRouteDistanceArray[$i], "<TotalIndirectRouteDistance>", "</TotalIndirectRouteDistance>", EXCL)) . "','" . floatval(return_between($indirectTotalRouteDistanceArray[$i], "<TotalRouteDistance>", "</TotalRouteDistance>", EXCL)) . "')";
         echo $sql;
         /*$result=mysql_query($sql);	
         		if($result)
         			echo "insert is successful";
         		else
         			echo "<b>INSERT ERROR: ".mysql_error()."</b>". $sql."<br/>";
         		*/
     }
 } else {
     echo "StartStop:" . $startStop . "," . "EndStop:" . $endStop . ",depotErrorCode:" . $depotErrorCode . "n";
     $sql = "INSERT INTO depotbusroutes (DepotErrorCode,SourceStartStop,DestinationEndStop)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tValues('" . intval($depotErrorCode) . "','" . $startStop . "','" . $endStop . "')";
     echo $sql;
     /*$result=mysql_query($sql);	
     		if($result)
     				echo "insert 411 is successful";
         foreach ($routes as $route) {
             $numRouteCount++;
             $indirectRouteErrorCodeArray = parse_array($str, "<ErrorCode>", "</ErrorCode>");
             $indirectStartStopsArray = parse_array($str, "<StartStop>", "</StartStop>");
             $indirectStartBusesArray = parse_array($str, "<StartBuses>", "</StartBuses>");
             $indirectDepotArray = parse_array($str, "<FirstJunction>", "</FirstJunction>");
             $indirectEndBusesArray = parse_array($str, "<EndBuses>", "</EndBuses>");
             $indirectEndStopsArray = parse_array($str, "<EndStop>", "</EndStop>");
         }
         for ($i = 0; $i < $numRouteCount; $i++) {
             $depotNameString = return_between($indirectDepotArray[$i], "<FirstJunction>", "</FirstJunction>", EXCL);
             list($depotName, $lat, $lon) = explode(":", $depotNameString);
             $distanceBetweenDepotAndStartStop = distanceBetweenStops($startStop, $depotName);
             $distanceBetweenDepotAndEndStop = distanceBetweenStops($endStop, $depotName);
             $totalRouteDistance = floatval($distanceBetweenDepotAndStartStop) + floatval($distanceBetweenDepotAndEndStop);
             $sql = "INSERT INTO directdepotbusroutes (DepotErrorCode,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  StartStop,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  EndStop,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  DepotNameString,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  BusesBetweenStartStopAndDepot,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  BusesBetweenEndStopAndDepot,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  DistanceBetweenDepotAndStartStop,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  DistanceBetweenDepotAndEndStop,\r\n\t\t\t\t\t\t\t\t\t\t\t\t  TotalRouteDistance) Values('" . intval(return_between($indirectRouteErrorCodeArray[$i], "<ErrorCode>", "</ErrorCode>", EXCL)) . "','" . $startStop . "','" . $endStop . "','" . $depotNameString . "','" . return_between($indirectStartBusesArray[$i], "<StartBuses>", "</StartBuses>", EXCL) . "','" . return_between($indirectEndBusesArray[$i], "<EndBuses>", "</EndBuses>", EXCL) . "','" . floatval($distanceBetweenDepotAndStartStop) . "','" . floatval($distanceBetweenDepotAndEndStop) . "','" . floatval($totalRouteDistance) . "')";
             echo $sql;
             /*$result=mysql_query($sql);
             		if($result)
             			echo "insert is successful";
             		else
             			echo "<b>INSERT ERROR: ".mysql_error()."</b>". $sql."<br/>";
             		*/
         }
     }
 } else {
     echo "StartStop:" . $startStop . "," . "EndStop:" . $endStop . ",depotErrorCode:" . $depotErrorCode . "n";
     $sql = "INSERT INTO depotbusroutes (DepotErrorCode,SourceStartStop,DestinationEndStop)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tValues('" . intval($depotErrorCode) . "','" . $startStop . "','" . $endStop . "')";
     echo $sql;
     /*$result=mysql_query($sql);	
     		if($result)
Example #10
0
//to do - read about wiki api and how its handled
//only first para displayed
$s = $_POST['keyword'];
$ch = curl_init();
$url = "http://en.wikipedia.org/wiki/" . urlencode($s);
include "LIB_parse.php";
//here we created connection with login page to get verification code
include "LIB_http.php";
$reffer = "http://en.wikipedia.org/wiki/Main_Page";
$cookie_file_path = "C:/cookie.txt";
//cokie ki path dekh liyo
$agent = "Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//yahan inki kuch zarurat nhi hai
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec($ch);
curl_close($ch);
$title_excl = return_between($result, '<p><b>', "</p>", EXCL);
# Display the parsed text
echo $title_excl;
//lib_parse aur lib_http use karna padegi
//kar ke chala ke dhek
//strip tag use kar sakte hain
				$Begin_Tag = 'id="';
				$End_Tag = '"';
				$inputid = return_between($Input, $Begin_Tag, $End_Tag, EXCL);
				$inputid = str_replace(chr(34),"",$inputid);

				//$inputid = get_attribute($Input,'id');
				//echo "input id: " . $inputid . "<br />";
				$pos = strpos($inputid, '=');
				if ($pos !== false)
					{
					$inputid = "no id";
					}

				$Begin_Tag = 'name="';
				$End_Tag = '"';
				$inputname = return_between($Input, $Begin_Tag, $End_Tag, EXCL);
				$inputname = str_replace(chr(34),"",$inputname);

				//$inputname = get_attribute($Input,'name');
				//echo "input name: " . $inputname . "<br />";
				$pos = strpos($inputname, '=');
				if ($pos !== false)
					{
					$inputname = "no name";
					}

				$inputtype = get_attribute($Input,'type');
				//echo "input type: " . $inputtype . "<br />";

				$inputvalue = get_attribute($Input,'value');
				//echo "input value: " . $inputvalue . "<br />";
//cokie ki path dekh liyo
$agent = "Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec($ch);
curl_close($ch);
//ise bina lib_parse aur lib_http use kiye kar ke dekhiyo,preg_match_all mein regex galat aa riya tha use thik
//kar ke chala ke dhek
$title_excl = return_between($result, '<font face="verdana" size=3>', "</font>", EXCL);
# Display the parsed text
echo "title_excl = " . $title_excl;
$x = str_replace(" ", "", $title_excl);
echo "{$x}";
//dalte waqt ise hata lena
//here we login     jo upar $x ya vrfication code nikala tha use yahan par use karliyo
$LOGINURL = "https://academics.vit.ac.in/student/stud_login_submit.asp";
$POSTFIELDS = "message=&regno=" . $regno . "&passwd=" . $passwd . "&vrfcd=" . $x;
//kisi ko dene se pehle change kar liyo
$reffer = "https://academics.vit.ac.in/student/stud_login.asp";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
Example #13
0
function crawlStatus($currElement)
{
    $src = $hyperlink = $locn = $userURL = $followers = $rts = $rtu = null;
    //$currElement = $statusArray[$i];
    $createdAt = return_between($currElement, "<created_at>", "</created_at>", EXCL);
    //format the date to Database datetime type (for date based comparisons)
    $dtFormat = dateFormat($createdAt);
    $tempsid = split_string($currElement, "</created_at>", AFTER, EXCL);
    $tempsid = split_string($tempsid, "</id>", BEFORE, EXCL);
    $sid = split_string($tempsid, "<id>", AFTER, EXCL);
    $text = return_between($currElement, "<text>", "</text>", EXCL);
    //this and next functions called to handle unicode characters or non english text
    $text = utf8_to_unicode($text);
    $text = unicode_to_entities_preserving_ascii($text);
    //preg match to extract URL from tweets, if present (currently for http), match string can be modified for better handling
    $do = preg_match('@(https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?)@', $text, $matches);
    if ($do = true) {
        //if url present
        $hyperlink = expandTinyURL(htmlentities($matches['0']));
    }
    //tweets usually contain tiny urls ->expansion needed
    $src = return_between($currElement, "<source>", "</source>", EXCL);
    $src = strip_tags($src);
    //gathering reply to information, if the tweet is a reply
    $rts = return_between($currElement, "<in_reply_to_status_id>", "</in_reply_to_status_id>", EXCL);
    $rtu = return_between($currElement, "<in_reply_to_user_id>", "</in_reply_to_user_id>", EXCL);
    //extracting user information as an array
    $userprofile = return_between($currElement, "<user>", "</user>", EXCL);
    $flag = 0;
    insertDB($sid, $text, $hyperlink, $dtFormat, $rts, $rtu, $src, $userprofile);
}
/**
The xml should be
<Address>
<Value></Value>
<Info></Info>
<Stops>
<Stop>
<Name></Name>
<Latitude></Latitude>
<Longitude></Longitude>
<Distance></Distance>
<Buses></Buses>
</Stop>
.
.
</Stops>
<Result>
<BusStop></BusStop>
<BusStopLatitude></BusStopLatitude>
<BusStopLongitude></BusStopLongitude>
<Offset></Offset>
</Result>
</Address>
 **/
function getStopForAddress($addr, $log, $mediaType)
{
    //echo $addr;
    $stopDataString = '';
    $originalRequestedLatitude = 0;
    $originalRequestedLongitude = 0;
    // create a xml string
    $stopXMLString = '<Address>';
    $query = "Select StopName, Latitude, Longitude from Stops Where StopName = '" . $addr . "'";
    $result = mysql_query($query);
    $rowsnum = mysql_num_rows($result);
    //find from the stop table..more than one stop found
    //	if($rowsnum>1)
    //	{
    //		if($DEBUG)
    //			echo "more than one stops are found with your search criteria <br/>";
    //		$log->LogDebug("[".$mediaType."] The address ".$addr." matches more than one in stops table. taking the first one ");
    //		$stopXMLString=$stopXMLString."<Info>More than one stops are found with your search criteria</Info>";
    //		$stopXMLString=$stopXMLString."<ErrorCode>MS</ErrorCode>";
    //		$stopXMLString=$stopXMLString."<Stops>";
    //		// this is the case wehre we can check which is the best choice in terms of buses coming thourgh..E.g. Marathahalli
    //		$maxBus=0;
    //		for($i=0;$i<$rowsnum;$i++)
    //		{
    //			$row=mysql_fetch_row($result);
    //			$stopXMLString=$stopXMLString."<Stop>";
    //		   if($DEBUG)
    //			 echo $row[0]."<br/>";
    //
    //			$stopXMLString=$stopXMLString."<Name>".htmlentities($row[0])."</Name>";
    //			$stopXMLString=$stopXMLString."<Latitude>".$row[1]."</Latitude>";
    //			$stopXMLString=$stopXMLString."<Longitude>".$row[2]."</Longitude>";
    //			$stopXMLString=$stopXMLString."<Distance>-1</Distance>";
    //			$stopXMLString=$stopXMLString."<Buses>".getBusesForStop($row[0])."</Buses>";
    //
    //			// $stopDetails=$row[0];
    //			//$map->addMarkerByCoords($row[2],$row[1],$row[0],getBusesForStop($row[0]),'');
    //			$NumberOfBus=getNumberOfBusesForStop($row[0]);
    //			if($NumberOfBus>$maxBus)
    //			{
    //				$maxBus=$NumberOfBus;
    //				$stopDataString=$row[0].":".$row[1].":".$row[2].":0";
    //			}
    //			$stopXMLString=$stopXMLString."</Stop>";
    //		}
    //		$stopXMLString=$stopXMLString."</Stops>";
    //	}
    //	else //only one stop is found
    // if the stop is found
    if ($rowsnum == 1) {
        $stopXMLString = $stopXMLString . "<Info>Your address matches the correct stop name</Info>";
        $stopXMLString = $stopXMLString . "<ErrorCode>OS</ErrorCode>";
        $stopXMLString = $stopXMLString . "<Stops>";
        $stopXMLString = $stopXMLString . "<Stop>";
        $row = mysql_fetch_row($result);
        //        if($DEBUG)
        //            echo " Your stop is ".$row[0]."<br/>";
        $log->LogDebug("[" . $mediaType . "] The address " . $addr . " is a valid stopname ");
        $stopXMLString = $stopXMLString . "<Name>" . htmlentities($row[0]) . "</Name>";
        $stopXMLString = $stopXMLString . "<Latitude>" . $row[1] . "</Latitude>";
        $stopXMLString = $stopXMLString . "<Longitude>" . $row[2] . "</Longitude>";
        $stopXMLString = $stopXMLString . "<Distance>-1</Distance>";
        $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($row[0]) . "</Buses>";
        $stopXMLString = $stopXMLString . "</Stop>";
        // $map->addMarkerByCoords($row[2],$row[1],$row[0],getBusesForStop($row[0]),'');
        $stopDataString = $row[0] . ":" . $row[1] . ":" . $row[2] . ":0";
        $stopXMLString = $stopXMLString . "</Stops>";
    } else {
        //no stop found..user must have entered some free string
        if ($rowsnum == 0) {
            //First check in the road database if the address meets
            //echo "going to the roads database"."<br/>";
            // Checking in the road database
            $query = "Select * from newRoadAddresses Where Address ='" . $addr . "'";
            $result = mysql_query($query);
            $rowsnum = mysql_num_rows($result);
            //the address was not found in the road database so get it from internet
            if ($rowsnum == 0) {
                //                if($DEBUG)
                //                    echo "The address not found in the database so fetching from internet <br/>";
                //$stopXMLString=$stopXMLString."<Info>The address ".$addr." not found in the database so fetching from internet</Info>";
                $logString = "[" . $mediaType . "] The address " . $addr . " not found in the database so fetching from internet ";
                //$log->LogDebug("[".$mediaType."] The address ".$addr." not found in the database so fetching from internet ");
                // fimd from the net
                $addressString = "http://maps.google.com/maps/api/geocode/json?address=" . urlencode($addr) . ",+Bangalore,+Karnataka,+India&sensor=false";
                $geocode = file_get_contents($addressString);
                $formattedAddress = return_between($geocode, "formatted_address", "\",", EXCL);
                $formattedAddressNoiseRemoved = return_between($formattedAddress, ":", "India", INCL);
                $place = substr($formattedAddressNoiseRemoved, 3);
                //echo $place."<br/>";
                //exit(0);
                ///echo $place."<br/>";
                //$arr=array();
                $arr = explode(",", $place);
                //the address was not at all valid
                if (strcmp(trim($arr[0]), "Bangalore") == 0 && strcmp(trim($arr[1]), "Karnataka") == 0 && strcmp(trim($arr[2]), "India") == 0) {
                    $log->LogDebug($logString . ". Invalid Address provided ");
                    $stopXMLString = $stopXMLString . "<Info>Address is not valid. Try giving some locality name</Info>";
                    $stopXMLString = $stopXMLString . "<ErrorCode>AM</ErrorCode>";
                    $stopXMLString = $stopXMLString . "<Stops>";
                    $stopXMLString = $stopXMLString . "<Stop>";
                    $stopXMLString = $stopXMLString . "</Stop>";
                    $stopXMLString = $stopXMLString . "</Stops>";
                    //                    if($DEBUG)
                    //                        echo "<h3>".trim($addr)."  Address is not valid"."</h3><br/>";
                    $stopDataString = "0:0:0:0";
                } else {
                    $locations = return_between($geocode, "location", "}", EXCL);
                    //echo $locations;
                    $latitude = return_between($locations, "lat\"", ",", EXCL);
                    $latitude = substr($latitude, 3);
                    //echo $latitude;
                    list($lat, $long) = explode(",", $locations);
                    list($cap, $val) = explode(":", $long);
                    //echo trim($val);
                    $addrLat = trim($latitude);
                    $addrLong = trim($val);
                    $originalRequestedLatitude = $addrLat;
                    $originalRequestedLongitude = $addrLong;
                    // add the marker for the searched address
                    //$map->addMarkerIcon("marker_star.png","marker_shadow.png",15,29,15,3);
                    //$map->addMarkerByCoords($addrLong,$addrLat,$addr,'','');
                    //Now check that we have any stop that is within 1 km of the stop.
                    //we need to use the direct method to calculate the distance
                    // we could have used the heversine formaula also but this is OK
                    $query = "SELECT  StopName, Latitude, Longitude FROM Stops WHERE (Latitude - " . $addrLat . " < .009) AND (Latitude - " . $addrLat . " > - .009) AND (Longitude - " . $addrLong . " > - .009) AND (Longitude - " . $addrLong . " < 0.009)";
                    //echo $query."<br/>";
                    $result = mysql_query($query);
                    $rowsnum = mysql_num_rows($result);
                    //we could not find any stops near to this address.
                    if ($rowsnum == 0) {
                        // this is the case when you gave an address that even could not be found usign the internet search
                        $log->LogDebug($logString . ". No Stops nearby");
                        $stopXMLString = $stopXMLString . "<Info>Sorry we could not find any stops nearby</Info>";
                        $stopXMLString = $stopXMLString . "<ErrorCode>AM</ErrorCode>";
                        $stopXMLString = $stopXMLString . "<Stops>";
                        $stopXMLString = $stopXMLString . "<Stop>";
                        $stopXMLString = $stopXMLString . "</Stop>";
                        $stopXMLString = $stopXMLString . "</Stops>";
                        //                        if($DEBUG)
                        //                            echo "<h3>".trim($addr)."  Address is not valid"."</h3><br/>";
                        $stopDataString = "0:0:0:0";
                    } else {
                        $arrBusStops = array();
                        for ($i = 0; $i < $rowsnum; $i++) {
                            $row = mysql_fetch_row($result);
                            //echo $row[0];
                            $dist = distance($addrLat, $addrLong, $row[1], $row[2], "K");
                            $BDS = new BusDataStructure($row[0], $row[1], $row[2], $dist);
                            array_push($arrBusStops, $BDS);
                            //echo distance($addrLat, $addrLong, $row[1],$row[2], "K") . " kilometers<br>";
                            //$map->addMarkerByCoords($row[2],$row[1],$row[0].distance($addrLat, $addrLong, $row[1],$row[2], "K"),'','');
                        }
                        // now do the comparison of the data
                        //sort the stops in the order of some preference
                        $tempSortedArray = BubbleSort($arrBusStops, $rowsnum);
                        // this is the place to do One more level of filtering based on the number of buses
                        $sortedArray = applyFilterForAddress($tempSortedArray);
                        //print_r($sortedArray);
                        $log->LogDebug($logString . ". Valid Address found via internet");
                        $stopXMLString = $stopXMLString . "<Info>Address Found via Internet</Info>";
                        $formattedPlace = preg_replace('/Bangalore, Karnataka, India$/', '', $place);
                        $formattedPlaceRemovingTrailingComma = rtrim(trim($formattedPlace), ",");
                        $stopXMLString = $stopXMLString . "<InternetAddress>" . $formattedPlaceRemovingTrailingComma . "</InternetAddress>";
                        $stopXMLString = $stopXMLString . "<ErrorCode>IA</ErrorCode>";
                        $stopXMLString = $stopXMLString . "<Stops>";
                        for ($i = 0; $i < sizeof($sortedArray); $i++) {
                            //echo $sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance()."<br/>";
                            $stopXMLString = $stopXMLString . "<Stop>";
                            //$map->addMarkerByCoords($sortedArray[$i]->getLongitude(),$sortedArray[$i]->getLatitude(),$sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance(),getBusesForStop($sortedArray[$i]->getStopName()),'');
                            $stopXMLString = $stopXMLString . "<Name>" . htmlentities($sortedArray[$i]->getStopName()) . "</Name>";
                            $stopXMLString = $stopXMLString . "<Latitude>" . $sortedArray[$i]->getLatitude() . "</Latitude>";
                            $stopXMLString = $stopXMLString . "<Longitude>" . $sortedArray[$i]->getLongitude() . "</Longitude>";
                            $stopXMLString = $stopXMLString . "<Distance>" . $sortedArray[$i]->getDistance() . "</Distance>";
                            $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($sortedArray[$i]->getStopName()) . "</Buses>";
                            $stopXMLString = $stopXMLString . "</Stop>";
                        }
                        $stopXMLString = $stopXMLString . "</Stops>";
                        $stopDataString = $sortedArray[0]->getStopName() . ":" . $sortedArray[0]->getLatitude() . ":" . $sortedArray[0]->getLongitude() . ":" . $sortedArray[0]->getDistance();
                    }
                }
            } else {
                if ($rowsnum > 1) {
                    $stopXMLString = $stopXMLString . "<Info>More than one matching address found in road database. Kindly add some more specifics</Info>";
                    $stopXMLString = $stopXMLString . "<ErrorCode>MA</ErrorCode>";
                    $stopXMLString = $stopXMLString . "<Stops>";
                    $stopXMLString = $stopXMLString . "<Stop>";
                    $stopXMLString = $stopXMLString . "</Stop>";
                    $stopXMLString = $stopXMLString . "</Stops>";
                    //                if($DEBUG)
                    //                    echo "More than one matching address found in road database. Kindly add some more specifics";
                    $stopDataString = "m:m:m:m";
                } else {
                    //                if($DEBUG)
                    //                    echo "Found in the road database"."<br/>";
                    // we found the address in th road data base but unfortunately all the stops are more than KM .
                    // this issue will not be there after we have the pegging of the stops.
                    // in the first sql itself we will know the stop that is meant for this road address
                    $log->LogDebug("[" . $mediaType . "] The address " . $addr . " found in the road database ");
                    $row = mysql_fetch_row($result);
                    $addrLat = $row[3];
                    $addrLong = $row[4];
                    $stopNumber = $row[5];
                    $stopName = $row[6];
                    $vicinityDistance = $row[7];
                    $originalRequestedLatitude = $addrLat;
                    $originalRequestedLongitude = $addrLong;
                    //get the latutude/logitude of the stop
                    $sqlStop = "Select * from Stops where SNo='" . $stopNumber . "'";
                    $resultStop = mysql_query($sqlStop);
                    $rowStop = mysql_fetch_row($resultStop);
                    $stopLat = $rowStop[2];
                    $stopLon = $rowStop[3];
                    $stopXMLString = $stopXMLString . "<Info>Address Found in the Road Database</Info>";
                    $stopXMLString = $stopXMLString . "<ErrorCode>RA</ErrorCode>";
                    $stopXMLString = $stopXMLString . "<Stops>";
                    $stopXMLString = $stopXMLString . "<Stop>";
                    //$map->addMarkerByCoords($sortedArray[$i]->getLongitude(),$sortedArray[$i]->getLatitude(),$sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance(),getBusesForStop($sortedArray[$i]->getStopName()),'');
                    $stopXMLString = $stopXMLString . "<Name>" . htmlentities($stopName) . "</Name>";
                    $stopXMLString = $stopXMLString . "<Latitude>" . $stopLat . "</Latitude>";
                    $stopXMLString = $stopXMLString . "<Longitude>" . $stopLon . "</Longitude>";
                    $stopXMLString = $stopXMLString . "<Distance>" . $vicinityDistance . "</Distance>";
                    $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($stopName) . "</Buses>";
                    $stopXMLString = $stopXMLString . "</Stop>";
                    $stopXMLString = $stopXMLString . "</Stops>";
                    $stopDataString = $stopName . ":" . $stopLat . ":" . $stopLon . ":" . $vicinityDistance;
                    //echo $addrLat;
                    //$map->addMarkerByCoords($addrLong,$addrLat,$addr,'','');
                    /*$query="SELECT  StopName, Latitude, Longitude FROM Stops WHERE (Latitude - ".$addrLat." < .009) AND (Latitude - ".$addrLat." > - .009) AND (Longitude - ".$addrLong." > - .009) AND (Longitude - ".$addrLong." < 0.009)";
                                    //echo $query."<br/>";
                                    $result= mysql_query($query);
                                    $rowsnum = mysql_num_rows($result);
                                    if($rowsnum==0)
                                    {
                                        $stopXMLString=$stopXMLString."<Info>All stops are more then 1 km far</Info>";
                                        $stopXMLString=$stopXMLString."<ErrorCode>KM</ErrorCode>";
                                        $stopXMLString=$stopXMLString."<Stops>";
                                        $stopXMLString=$stopXMLString."<Stop>";
                                        $stopXMLString=$stopXMLString."</Stop>";
                                        $stopXMLString=$stopXMLString."</Stops>";
                                        //echo "All stops are more then 1 km far";
                                    }
                                    else
                                    {
                                        // we should try to show nearest 5 at the max
                                        // one way is to create a array of datastructure and then sort them on the basis of distance.
                                        // also find the buses for the finalised stops
                                        $arrBusStops= array();
                                        $stopXMLString=$stopXMLString."<Info>Address Found in the Road Database</Info>";
                                        $stopXMLString=$stopXMLString."<ErrorCode>RA</ErrorCode>";
                                        for($i=0;$i<$rowsnum;$i++)
                                        {
                                            $row=mysql_fetch_row($result);
                                            $dist=distance($addrLat, $addrLong, $row[1],$row[2], "K");
                                            $BDS= new BusDataStructure($row[0],$row[1],$row[2],$dist);
                                            array_push($arrBusStops,$BDS);
                    
                                        }
                                        // now do the comparison of the data
                                        $tempSortedArray=BubbleSort($arrBusStops,$rowsnum);
                                        // this is the place to do One more level of filtering based on the number of buses
                                        $sortedArray=applyFilterForAddress($tempSortedArray);
                                        //print_r($sortedArray);
                                        $stopXMLString=$stopXMLString."<Stops>";
                                        for($i=0;$i<sizeof($sortedArray);$i++)
                                        {
                                            //echo $sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance()."<br/>";
                                        $stopXMLString=$stopXMLString."<Stop>";	//$map->addMarkerByCoords($sortedArray[$i]->getLongitude(),$sortedArray[$i]->getLatitude(),$sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance(),getBusesForStop($sortedArray[$i]->getStopName()),'');
                                        $stopXMLString=$stopXMLString."<Name>".htmlentities($sortedArray[$i]->getStopName())."</Name>";
                                        $stopXMLString=$stopXMLString."<Latitude>".$sortedArray[$i]->getLatitude()."</Latitude>";
                                        $stopXMLString=$stopXMLString."<Longitude>".$sortedArray[$i]->getLongitude()."</Longitude>";
                                        $stopXMLString=$stopXMLString."<Distance>".$sortedArray[$i]->getDistance()."</Distance>";
                                        $stopXMLString=$stopXMLString."<Buses>".getBusesForStop($sortedArray[$i]->getStopName())."</Buses>";
                                        $stopXMLString=$stopXMLString."</Stop>";
                    
                                        }
                                        $stopXMLString=$stopXMLString."</Stops>";
                                        $stopDataString=$sortedArray[0]->getStopName().":".$sortedArray[0]->getLatitude().":".$sortedArray[0]->getLongitude().":".$sortedArray[0]->getDistance();
                    
                                    }*/
                }
            }
        }
    }
    $stopXMLString = $stopXMLString . "<Result>";
    list($BusStop, $BusLatitude, $BusLongitude, $BusOffset) = explode(":", $stopDataString);
    $stopXMLString = $stopXMLString . "<BusStop>" . htmlentities($BusStop) . "</BusStop>";
    $stopXMLString = $stopXMLString . "<BusStopLatitude>" . $BusLatitude . "</BusStopLatitude>";
    $stopXMLString = $stopXMLString . "<BusStopLongitude>" . $BusLongitude . "</BusStopLongitude>";
    $stopXMLString = $stopXMLString . "<Offset>" . $BusOffset . "</Offset>";
    $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStopWithFrequency($BusStop) . "</Buses>";
    $stopXMLString = $stopXMLString . "<OriginalStopLatitude>" . $originalRequestedLatitude . "</OriginalStopLatitude>";
    $stopXMLString = $stopXMLString . "<OriginalStopLongitude>" . $originalRequestedLongitude . "</OriginalStopLongitude>";
    $stopXMLString = $stopXMLString . "</Result>";
    $stopXMLString = $stopXMLString . "</Address>";
    return $stopXMLString;
}
Example #15
0
$handle = opecc_convert("input.txt");
$input_str = iconv("utf-8", "big5", $handle);
$input_str = trim($input_str);
$action = "http://sunlight.iis.sinica.edu.tw/cgi-bin/text.cgi";
$data_arr = array();
$data_arr["query"] = $input_str;
$result = http($action, $ref = "", $method = "POST", $data_arr, EXCL_HEAD);
$result_str = $result["FILE"];
$result_arr = parse_array($result_str, "<META ", ">");
$res_url = get_attribute($result_arr[1], "CONTENT");
$res_url = explode("=", $res_url);
$res_url = trim($res_url[1], "'");
echo "\n" . "response_url: http://sunlight.iis.sinica.edu.tw/" . $res_url . "\n";
//parse response url
$web_page = http_get("http://sunlight.iis.sinica.edu.tw/" . $res_url, $ref = "");
$web_page = trim($web_page["FILE"], "<br>");
$response_link = parse_array($web_page, "<a ", "</a>");
$response_link2 = parse_array($web_page, "<a ", ">");
$search_arr = array("'", '"');
$counter = count($response_link);
for ($count = 0; $count < $counter; $count++) {
    $temp_str = return_between($response_link[$count], "<a>", "</a>", EXCL);
    $temp_str = explode(">", $temp_str);
    $link = "http://sunlight.iis.sinica.edu.tw/" . get_attribute(str_replace($search_arr, '"', $response_link2[$count]), "HREF");
    $web_page = http_get($link, $ref = "");
    $web_page = $web_page["FILE"];
    $plain_text = return_between($web_page, "<pre>", "</pre>", EXCL);
    $plain_text = str_replace("-", "", trim($plain_text));
    echo "\n" . $plain_text . "\n";
    echo "\n" . $plain_text . "\n";
}
Example #16
0
$fh = fopen("bmtcerrordata\\testBusroutesForError411.txt", "r");
$count = 0;
while (($str = fgets($fh)) != null) {
    //  echo $str."<br/>";
    $startStop = return_between($str, "<StartStop>", "</StartStop>", EXCL);
    $endStop = return_between($str, "<EndStop>", "</EndStop>", EXCL);
    $depotErrorCode = return_between($str, "<ErrorCode>", "</ErrorCode>", EXCL);
    if ($depotErrorCode != "411") {
        if ($depotErrorCode == "1") {
            echo $str;
        } else {
            $depotNameString = return_between($str, "<Depot>", "</Depot>", EXCL);
            //need to further process the depot name string to find the depot name, buses and the lat/lon values
            $busesBetweenStopAndDepot = return_between($str, "<BusesBetweenStopAndDepot>", "</BusesBetweenStopAndDepot>", EXCL);
            $distanceBetweenDepotAndStop = return_between($str, "<DistanceBetweenDepotAndStop>", "</DistanceBetweenDepotAndStop>", EXCL);
            $indirectRoute = return_between($str, "<indirectRoutes>", "</indirectRoutes>", EXCL);
            $routes = parse_array($indirectRoute, "<Route>", "</Route>");
            //print_r($routes);
            $indirectRouteErrorCodeArray = array();
            $indirectStartStopsArray = array();
            $indirectStartBusesArray = array();
            $indirectFirstJunctionsArray = array();
            $indirectDistanceBetweenJunctionArray = array();
            $indirectSecondJunctionsArray = array();
            $indirectEndBusesArray = array();
            $indirectEndStopsArray = array();
            $indirectTotalIndirectRouteDistanceArray = array();
            $indirectTotalRouteDistanceArray = array();
            $numRoutes = 0;
            //parse the routes
            foreach ($routes as $route) {
Example #17
0
/**
The xml should be
<Address>
<Value></Value>
<Info></Info>
<Stops>
<Stop>
<Name></Name>
<Latitude></Latitude>
<Longitude></Longitude>
<Distance></Distance>
<Buses></Buses>
</Stop>
.
.
</Stops>
<Result>
<BusStop></BusStop>
<BusStopLatitude></BusStopLatitude>
<BusStopLongitude></BusStopLongitude>
<Offset></Offset>
</Result>
</Address>
**/
function getStopForAddress($addr, $log)
{
    //echo $addr;
    $stopDataString = '';
    $originalRequestedLatitude = 0;
    $originalRequestedLongitude = 0;
    // create a xml string
    $stopXMLString = '<Address>';
    $query = "Select StopName, Latitude, Longitude from Stops Where StopName LIKE '" . $addr . "%'";
    $result = mysql_query($query);
    $rowsnum = mysql_num_rows($result);
    if ($rowsnum > 1) {
        if ($DEBUG) {
            echo "more than one stops are found with your search criteria <br/>";
        }
        $log->LogDebug("The address " . $addr . " matches more than one in stops table. taking the first one ");
        $stopXMLString = $stopXMLString . "<Info>More than one stops are found with your search criteria</Info>";
        $stopXMLString = $stopXMLString . "<ErrorCode>MS</ErrorCode>";
        $stopXMLString = $stopXMLString . "<Stops>";
        // this is the case wehre we can check which is the best choice in terms of buses coming thourgh..E.g. Marathahalli
        $maxBus = 0;
        for ($i = 0; $i < $rowsnum; $i++) {
            $row = mysql_fetch_row($result);
            $stopXMLString = $stopXMLString . "<Stop>";
            if ($DEBUG) {
                echo $row[0] . "<br/>";
            }
            $stopXMLString = $stopXMLString . "<Name>" . htmlentities($row[0]) . "</Name>";
            $stopXMLString = $stopXMLString . "<Latitude>" . $row[1] . "</Latitude>";
            $stopXMLString = $stopXMLString . "<Longitude>" . $row[2] . "</Longitude>";
            $stopXMLString = $stopXMLString . "<Distance>-1</Distance>";
            $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($row[0]) . "</Buses>";
            // $stopDetails=$row[0];
            //$map->addMarkerByCoords($row[2],$row[1],$row[0],getBusesForStop($row[0]),'');
            $NumberOfBus = getNumberOfBusesForStop($row[0]);
            if ($NumberOfBus > $maxBus) {
                $maxBus = $NumberOfBus;
                $stopDataString = $row[0] . ":" . $row[1] . ":" . $row[2] . ":0";
            }
            $stopXMLString = $stopXMLString . "</Stop>";
        }
        $stopXMLString = $stopXMLString . "</Stops>";
    } else {
        if ($rowsnum == 1) {
            $stopXMLString = $stopXMLString . "<Info>Your address matches the correct stop name</Info>";
            $stopXMLString = $stopXMLString . "<ErrorCode>OS</ErrorCode>";
            $stopXMLString = $stopXMLString . "<Stops>";
            $stopXMLString = $stopXMLString . "<Stop>";
            $row = mysql_fetch_row($result);
            if ($DEBUG) {
                echo " Your stop is " . $row[0] . "<br/>";
            }
            $log->LogDebug("The address " . $addr . " is a valid stopname ");
            $stopXMLString = $stopXMLString . "<Name>" . htmlentities($row[0]) . "</Name>";
            $stopXMLString = $stopXMLString . "<Latitude>" . $row[1] . "</Latitude>";
            $stopXMLString = $stopXMLString . "<Longitude>" . $row[2] . "</Longitude>";
            $stopXMLString = $stopXMLString . "<Distance>-1</Distance>";
            $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($row[0]) . "</Buses>";
            $stopXMLString = $stopXMLString . "</Stop>";
            // $map->addMarkerByCoords($row[2],$row[1],$row[0],getBusesForStop($row[0]),'');
            $stopDataString = $row[0] . ":" . $row[1] . ":" . $row[2] . ":0";
            $stopXMLString = $stopXMLString . "</Stops>";
        } else {
            if ($rowsnum == 0) {
                //echo "going to the roads database"."<br/>";
                // Checking in the road database
                $query = "Select * from RoadAddresses Where Address ='" . $addr . "'";
                $result = mysql_query($query);
                $rowsnum = mysql_num_rows($result);
                if ($rowsnum == 0) {
                    if ($DEBUG) {
                        echo "The address not found in the database so fetching from internet <br/>";
                    }
                    //$stopXMLString=$stopXMLString."<Info>The address ".$addr." not found in the database so fetching from internet</Info>";
                    $log->LogDebug("The address " . $addr . " not found in the database so fetching from internet ");
                    // fimd from the net
                    $addressString = "http://maps.google.com/maps/api/geocode/json?address=" . urlencode($addr) . ",+Bangalore,+Karnataka,+India&sensor=false";
                    $geocode = file_get_contents($addressString);
                    //echo $geocode;
                    $formattedAddress = return_between($geocode, "formatted_address", "\",", EXCL);
                    $formattedAddressNoiseRemoved = return_between($formattedAddress, ":", "India", INCL);
                    $place = substr($formattedAddressNoiseRemoved, 3);
                    //	echo $place."<br/>";
                    ///echo $place."<br/>";
                    $arr = array();
                    $arr = split(",", $place);
                    if (strcmp(trim($arr[0]), "Bengaluru") == 0 && strcmp(trim($arr[1]), "Karnataka") == 0 && strcmp(trim($arr[2]), "India") == 0) {
                        $stopXMLString = $stopXMLString . "<Info>Address is not valid</Info>";
                        $stopXMLString = $stopXMLString . "<ErrorCode>AM</ErrorCode>";
                        $stopXMLString = $stopXMLString . "<Stops>";
                        $stopXMLString = $stopXMLString . "<Stop>";
                        $stopXMLString = $stopXMLString . "</Stop>";
                        $stopXMLString = $stopXMLString . "</Stops>";
                        if ($DEBUG) {
                            echo "<h3>" . trim($roadName) . "  Address is not valid" . "</h3><br/>";
                        }
                        $stopDataString = "0:0:0:0";
                    } else {
                        $locations = return_between($geocode, "location", "}", EXCL);
                        //echo $locations;
                        $latitude = return_between($locations, "lat\"", ",", EXCL);
                        $latitude = substr($latitude, 3);
                        //echo $latitude;
                        list($lat, $long) = split(",", $locations);
                        list($cap, $val) = split(":", $long);
                        //echo trim($val);
                        $addrLat = trim($latitude);
                        $addrLong = trim($val);
                        $originalRequestedLatitude = $addrLat;
                        $originalRequestedLongitude = $addrLong;
                        // add the marker for the searched address
                        //$map->addMarkerIcon("marker_star.png","marker_shadow.png",15,29,15,3);
                        //$map->addMarkerByCoords($addrLong,$addrLat,$addr,'','');
                        $query = "SELECT  StopName, Latitude, Longitude FROM Stops WHERE (Latitude - " . $addrLat . " < .009) AND (Latitude - " . $addrLat . " > - .009) AND (Longitude - " . $addrLong . " > - .009) AND (Longitude - " . $addrLong . " < 0.009)";
                        //echo $query."<br/>";
                        $result = mysql_query($query);
                        $rowsnum = mysql_num_rows($result);
                        if ($rowsnum == 0) {
                            // this is the case when you gave an address that even could not be found usign the internet search
                            $stopXMLString = $stopXMLString . "<Info>Address is not valid</Info>";
                            $stopXMLString = $stopXMLString . "<ErrorCode>AM</ErrorCode>";
                            $stopXMLString = $stopXMLString . "<Stops>";
                            $stopXMLString = $stopXMLString . "<Stop>";
                            $stopXMLString = $stopXMLString . "</Stop>";
                            $stopXMLString = $stopXMLString . "</Stops>";
                            if ($DEBUG) {
                                echo "<h3>" . trim($roadName) . "  Address is not valid" . "</h3><br/>";
                            }
                            $stopDataString = "0:0:0:0";
                        } else {
                            $arrBusStops = array();
                            for ($i = 0; $i < $rowsnum; $i++) {
                                $row = mysql_fetch_row($result);
                                //echo $row[0];
                                $dist = distance($addrLat, $addrLong, $row[1], $row[2], "K");
                                $BDS = new BusDataStructure($row[0], $row[1], $row[2], $dist);
                                array_push($arrBusStops, $BDS);
                                //echo distance($addrLat, $addrLong, $row[1],$row[2], "K") . " kilometers<br>";
                                //$map->addMarkerByCoords($row[2],$row[1],$row[0].distance($addrLat, $addrLong, $row[1],$row[2], "K"),'','');
                            }
                            // now do the comparison of the data
                            $tempSortedArray = BubbleSort($arrBusStops, $rowsnum);
                            // this is the place to do One more level of filtering based on the number of buses
                            $sortedArray = applyFilterForAddress($tempSortedArray);
                            //print_r($sortedArray);
                            $stopXMLString = $stopXMLString . "<Info>Address Found via Internet</Info>";
                            $stopXMLString = $stopXMLString . "<ErrorCode>IA</ErrorCode>";
                            $stopXMLString = $stopXMLString . "<Stops>";
                            for ($i = 0; $i < sizeof($sortedArray); $i++) {
                                //echo $sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance()."<br/>";
                                $stopXMLString = $stopXMLString . "<Stop>";
                                //$map->addMarkerByCoords($sortedArray[$i]->getLongitude(),$sortedArray[$i]->getLatitude(),$sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance(),getBusesForStop($sortedArray[$i]->getStopName()),'');
                                $stopXMLString = $stopXMLString . "<Name>" . htmlentities($sortedArray[$i]->getStopName()) . "</Name>";
                                $stopXMLString = $stopXMLString . "<Latitude>" . $sortedArray[$i]->getLatitude() . "</Latitude>";
                                $stopXMLString = $stopXMLString . "<Longitude>" . $sortedArray[$i]->getLongitude() . "</Longitude>";
                                $stopXMLString = $stopXMLString . "<Distance>" . $sortedArray[$i]->getDistance() . "</Distance>";
                                $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($sortedArray[$i]->getStopName()) . "</Buses>";
                                $stopXMLString = $stopXMLString . "</Stop>";
                            }
                            $stopXMLString = $stopXMLString . "</Stops>";
                            $stopDataString = $sortedArray[0]->getStopName() . ":" . $sortedArray[0]->getLatitude() . ":" . $sortedArray[0]->getLongitude() . ":" . $sortedArray[0]->getDistance();
                        }
                    }
                } else {
                    if ($rowsnum > 1) {
                        $stopXMLString = $stopXMLString . "<Info>More than one matching address found in road database. Kindly add some more specifics</Info>";
                        $stopXMLString = $stopXMLString . "<ErrorCode>MA</ErrorCode>";
                        $stopXMLString = $stopXMLString . "<Stops>";
                        $stopXMLString = $stopXMLString . "<Stop>";
                        $stopXMLString = $stopXMLString . "</Stop>";
                        $stopXMLString = $stopXMLString . "</Stops>";
                        if ($DEBUG) {
                            echo "More than one matching address found in road database. Kindly add some more specifics";
                        }
                        $stopDataString = "m:m:m:m";
                    } else {
                        if ($DEBUG) {
                            echo "Found in the road database" . "<br/>";
                        }
                        $log->LogDebug("The address " . $addr . " found in the road database ");
                        $row = mysql_fetch_row($result);
                        $addrLat = $row[3];
                        $addrLong = $row[4];
                        $originalRequestedLatitude = $addrLat;
                        $originalRequestedLongitude = $addrLong;
                        //echo $addrLat;
                        //$map->addMarkerByCoords($addrLong,$addrLat,$addr,'','');
                        $query = "SELECT  StopName, Latitude, Longitude FROM Stops WHERE (Latitude - " . $addrLat . " < .009) AND (Latitude - " . $addrLat . " > - .009) AND (Longitude - " . $addrLong . " > - .009) AND (Longitude - " . $addrLong . " < 0.009)";
                        //echo $query."<br/>";
                        $result = mysql_query($query);
                        $rowsnum = mysql_num_rows($result);
                        if ($rowsnum == 0) {
                            $stopXMLString = $stopXMLString . "<Info>All stops are more then 1 km far</Info>";
                            $stopXMLString = $stopXMLString . "<ErrorCode>KM</ErrorCode>";
                            $stopXMLString = $stopXMLString . "<Stops>";
                            $stopXMLString = $stopXMLString . "<Stop>";
                            $stopXMLString = $stopXMLString . "</Stop>";
                            $stopXMLString = $stopXMLString . "</Stops>";
                            //echo "All stops are more then 1 km far";
                        } else {
                            // we should try to show nearest 5 at the max
                            // one way is to create a array of datastructure and then sort them on the basis of distance.
                            // also find the buses for the finalised stops
                            $arrBusStops = array();
                            $stopXMLString = $stopXMLString . "<Info>Address Found in the Road Database</Info>";
                            $stopXMLString = $stopXMLString . "<ErrorCode>RA</ErrorCode>";
                            for ($i = 0; $i < $rowsnum; $i++) {
                                $row = mysql_fetch_row($result);
                                $dist = distance($addrLat, $addrLong, $row[1], $row[2], "K");
                                $BDS = new BusDataStructure($row[0], $row[1], $row[2], $dist);
                                array_push($arrBusStops, $BDS);
                            }
                            // now do the comparison of the data
                            $tempSortedArray = BubbleSort($arrBusStops, $rowsnum);
                            // this is the place to do One more level of filtering based on the number of buses
                            $sortedArray = applyFilterForAddress($tempSortedArray);
                            //print_r($sortedArray);
                            $stopXMLString = $stopXMLString . "<Stops>";
                            for ($i = 0; $i < sizeof($sortedArray); $i++) {
                                //echo $sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance()."<br/>";
                                $stopXMLString = $stopXMLString . "<Stop>";
                                //$map->addMarkerByCoords($sortedArray[$i]->getLongitude(),$sortedArray[$i]->getLatitude(),$sortedArray[$i]->getStopName().$sortedArray[$i]->getDistance(),getBusesForStop($sortedArray[$i]->getStopName()),'');
                                $stopXMLString = $stopXMLString . "<Name>" . htmlentities($sortedArray[$i]->getStopName()) . "</Name>";
                                $stopXMLString = $stopXMLString . "<Latitude>" . $sortedArray[$i]->getLatitude() . "</Latitude>";
                                $stopXMLString = $stopXMLString . "<Longitude>" . $sortedArray[$i]->getLongitude() . "</Longitude>";
                                $stopXMLString = $stopXMLString . "<Distance>" . $sortedArray[$i]->getDistance() . "</Distance>";
                                $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($sortedArray[$i]->getStopName()) . "</Buses>";
                                $stopXMLString = $stopXMLString . "</Stop>";
                            }
                            $stopXMLString = $stopXMLString . "</Stops>";
                            $stopDataString = $sortedArray[0]->getStopName() . ":" . $sortedArray[0]->getLatitude() . ":" . $sortedArray[0]->getLongitude() . ":" . $sortedArray[0]->getDistance();
                        }
                    }
                }
            }
        }
    }
    $stopXMLString = $stopXMLString . "<Result>";
    list($BusStop, $BusLatitude, $BusLongitude, $BusOffset) = split(":", $stopDataString);
    $stopXMLString = $stopXMLString . "<BusStop>" . htmlentities($BusStop) . "</BusStop>";
    $stopXMLString = $stopXMLString . "<BusStopLatitude>" . $BusLatitude . "</BusStopLatitude>";
    $stopXMLString = $stopXMLString . "<BusStopLongitude>" . $BusLongitude . "</BusStopLongitude>";
    $stopXMLString = $stopXMLString . "<Offset>" . $BusOffset . "</Offset>";
    $stopXMLString = $stopXMLString . "<Buses>" . getBusesForStop($BusStop) . "</Buses>";
    $stopXMLString = $stopXMLString . "<OriginalStopLatitude>" . $originalRequestedLatitude . "</OriginalStopLatitude>";
    $stopXMLString = $stopXMLString . "<OriginalStopLongitude>" . $originalRequestedLongitude . "</OriginalStopLongitude>";
    $stopXMLString = $stopXMLString . "</Result>";
    $stopXMLString = $stopXMLString . "</Address>";
    return $stopXMLString;
}
function describe_zipcode($zipcode)
{
    # Get required libraries and declare the target
    include "../util/LIB_http.php";
    include "../util/LIB_parse.php";
    $target = "http://www.schrenk.com/nostarch/webbots/zip_code_form.php";
    # Download the target
    $page = http_get($target, $ref = "");
    # Parse the session hidden tag from the downloaded page
    # <input type="hidden" name="session" value="xxxxxxxxxx">
    $session_tag = return_between($string = $page['FILE'], $start = "<input type=\"hidden\" name=\"session\"", $end = ">", $type = EXCL);
    # Remove the "'s and "value=" text to reveal the session value
    $session_value = str_replace("\"", "", $session_tag);
    $session_value = str_replace("value=", "", $session_value);
    # Submit the form
    $data_array['session'] = $session_value;
    $data_array['zipcode'] = $zipcode;
    $data_array['Submit'] = "Submit";
    $form_result = http_post_form($target, $ref = $target, $data_array);
    $landmark = "Information about " . $zipcode;
    $table_array = parse_array($form_result['FILE'], "<table", "</table>");
    for ($xx = 0; $xx < count($table_array); $xx++) {
        # Parse the table containing the parsing landmark
        if (stristr($table_array[$xx], $landmark)) {
            $ret['CITY'] = return_between($table_array[$xx], "CITY", "</tr>", EXCL);
            $ret['CITY'] = strip_tags($ret['CITY']);
            $ret['STATE'] = return_between($table_array[$xx], "STATE", "</tr>", EXCL);
            $ret['STATE'] = strip_tags($ret['STATE']);
            $ret['COUNTY'] = return_between($table_array[$xx], "COUNTY", "</tr>", EXCL);
            $ret['COUNTY'] = strip_tags($ret['COUNTY']);
            $ret['LATITUDE'] = return_between($table_array[$xx], "LATITUDE", "</tr>", EXCL);
            $ret['LATITUDE'] = strip_tags($ret['LATITUDE']);
            $ret['LONGITUDE'] = return_between($table_array[$xx], "LONGITUDE", "</tr>", EXCL);
            $ret['LONGITUDE'] = strip_tags($ret['LONGITUDE']);
        }
    }
    # Return the parsed data
    return $ret;
}
    $ReturnObject = array();
    $dir = "/var/www/html/api_evangelist/plans/api/methods/";
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if ('.' === $file) {
                continue;
            }
            if ('..' === $file) {
                continue;
            }
            $filename = substr($file, 0, 2);
            if ($filename == 'm-') {
                //echo $file . "<br />";
                $openpath = $dir . $file;
                //echo $openpath . "<br />";
                $myfile = fopen($openpath, "r") or die("Unable to open file!");
                $content = fread($myfile, filesize($openpath));
                $Begin_Tag = chr(36) . "route = '";
                $End_Tag = "';";
                $path = return_between($content, $Begin_Tag, $End_Tag, EXCL);
                //echo $path . " - ";
                array_push($ReturnObject, $path);
                fclose($myfile);
            }
        }
        closedir($handle);
    }
    //$ReturnObject['done'] = 1;
    $app->response()->header("Content-Type", "application/json");
    echo stripslashes(format_json(json_encode($ReturnObject)));
});