/
HelperFunctionsAjaxRevamp.php
executable file
·2308 lines (1996 loc) · 102 KB
/
HelperFunctionsAjaxRevamp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
require_once 'loginDetailsV2.php';
require('GoogleMapAPI.class.php');
require_once('BusDataStructure.php');
require_once('IndirectBusStructure.php');
require_once('IndirectBusStructureWithFrequency.php');
require_once 'KLogger.php';
require_once 'DisplayJunctionsDataV2.php';
require_once 'DisplaySortedJunctionData.php';
//require('GoogleApiAdvancedClass.php');
//require('JSMin.php');
set_time_limit(60);
//$DEBUG=false;
$map = new GoogleMapAPI('map');
// setup database for geocode caching
// $map->setDSN('mysql://USER:PASS@localhost/GEOCODES');
// enter YOUR Google Map Key
//$map->setAPIKey('ABQIAAAA1c1sWAqiVfYVo2H2uZO3DRSWrvxHdeTKbGAggAmAoqEyMU0eFRSTrS7LnHnkyvA93YPmiuF_C-0r7Q');
// this is registered for mygann.com
// new key ABQIAAAA1c1sWAqiVfYVo2H2uZO3DRSdbZxIVjTSMKDiD-iCCeLYxJJn_BTfNn4DtNyckPujCTOcXysH3Glq9g
$map->setAPIKey('ABQIAAAA1c1sWAqiVfYVo2H2uZO3DRSdbZxIVjTSMKDiD-iCCeLYxJJn_BTfNn4DtNyckPujCTOcXysH3Glq9g');
$log = new KLogger ( "log.txt" , KLogger::DEBUG );
// connect to the database
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MYSQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
//$DEBUG=true;
// increase the time out to infinity default is 60
set_time_limit(0);
/**
* distance(): this function will calcualte the distance between the two points given the latitude and the longitude of the 2 points
* the distance is bas4ed on the straight line and is not the driving distance
**/
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$lat1=doubleval($lat1);
$lon1=doubleval($lon1);
$lat2=doubleval($lat2);
$lon2=doubleval($lon2);
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
//echo $miles."...";
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
/**
* BubbleSort is the function to sort the array on the basis of the distance paramters
**/
function BubbleSort($SortArray,$array_size)
{
for($x = 0; $x < $array_size; $x++) {
for($y = 0; $y < $array_size; $y++) {
if($SortArray[$x]->getDistance() < $SortArray[$y]->getDistance()) {
$hold = $SortArray[$x];
$SortArray[$x] = $SortArray[$y];
$SortArray[$y] = $hold;
}
}
}
return $SortArray;
}
/**
* getBusesForStop is useful to get the buses for the stop
* I wamt that the BIAS and the G series bus to come at the last so if you do the ordering in the
* desc order the buses starting with V will come first
* the fucntion will return the names of the stops in the form of a , seperated string
* this is the reason why peope will not get the G series buses on the top. I think we need to put the frequency in place. Also because of the
* simple order by all 500 series is getting listed before 3XX. We need to bring in the frequency thing
**/
function getBusesForStop($stopName)
{
// for each stop found also get the bus number .. also I want BIAS and G series to be considered last so order by
$busQuery="Select BusNumber from newBusDetails where StopName='".$stopName."'ORDER BY BusNumber DESC";
$busResult= mysql_query($busQuery);
$busRowsnum = mysql_num_rows($busResult);
$buses="";
for($j=0;$j<$busRowsnum;$j++)
{
$busRow=mysql_fetch_row($busResult);
$buses = $buses.$busRow[0].",";
}
return $buses;
//echo $buses;
}
function getBusesForStopWithFrequency($stopName)
{
// for each stop found also get the bus number .. also I want BIAS and G series to be considered last so order by
// $busQuery="Select busnumber, frequency from busfrequency where busnumber in (Select BusNumber from newBusDetails where StopName='".$stopName."') order by frequency Desc";
$busQuery="select busFrequency.BusNumber,Frequency from busFrequency,newBusDetails where StopName='".$stopName."'
and busFrequency.BusNumber=newBusDetails.BusNumber order by Frequency desc";
$busResult= mysql_query($busQuery);
$busRowsnum = mysql_num_rows($busResult);
$buses="";
for($j=0;$j<$busRowsnum;$j++)
{
$busRow=mysql_fetch_row($busResult);
$temp=$busRow[0].":".$busRow[1];
if($j==$busRowsnum-1)
$buses = $buses.$temp;
else
$buses = $buses.$temp.",";
}
return $buses;
//echo $buses;
}
/**
* getArrayBusesForStop is same as the getBusesForSTop. Only difference being that the stops are resturned in the form of an array
**/
function getArrayBusesForStop($stopName)
{
// for each stop found also get the bus number .. also I want BIAS and G series to be considered last so order by
$busQuery="Select BusNumber from newBusDetails where StopName='".$stopName."'ORDER BY BusNumber DESC";
$busResult= mysql_query($busQuery);
$busRowsnum = mysql_num_rows($busResult);
$buses=array();
for($j=0;$j<$busRowsnum;$j++)
{
$busRow=mysql_fetch_row($busResult);
array_push($buses,$busRow[0]);
}
return $buses;
//echo $buses;
}
// function to trace the route...find out all the latitudes and longitudes of the stops inbetween the source and detination.
// this will help in drawing points
function traceRouteForBus($startStop,$endStop,$busNumber)
{
$startStopNumber=getStopNumberOnBusRoute($startStop,$busNumber);
$endStopNumber=getStopNumberOnBusRoute($endStop,$busNumber);
//echo " the start stop is ".$startStop."and the number".$startStopNumber."<br/>";
//echo " the start stop is ".$endStop."and the number".$endStopNumber."<br/>";
if($startStopNumber<$endStopNumber)
{
$query="SELECT newBusDetails.BusNumber, newBusDetails.StopName, newBusDetails.StopNumber, Stops.Latitude,
Stops.Longitude FROM newBusDetails INNER JOIN Stops ON newBusDetails.StopName = Stops.StopName AND newBusDetails.BusNumber = '".$busNumber."'
AND newBusDetails.StopNumber >= '".$startStopNumber."' AND newBusDetails.StopNumber <= '".$endStopNumber."' ORDER BY newBusDetails.StopNumber";
}
else
{
$query="SELECT newBusDetails.BusNumber, newBusDetails.StopName, newBusDetails.StopNumber, Stops.Latitude,
Stops.Longitude FROM newBusDetails INNER JOIN Stops ON newBusDetails.StopName = Stops.StopName AND newBusDetails.BusNumber = '".$busNumber."'
AND newBusDetails.StopNumber >= '".$endStopNumber."' AND newBusDetails.StopNumber <= '".$startStopNumber."' ORDER BY newBusDetails.StopNumber";
}
$result= mysql_query($query);
$rowsnum = mysql_num_rows($result);
$stopXMLString='<TraceRoutes>';
for($i=0;$i<$rowsnum;$i++)
{
$row=mysql_fetch_row($result);
//print_r($row);
$stopXMLString=$stopXMLString.'<Route>';
$stopXMLString=$stopXMLString.'<Latitude>'.$row[3].'</Latitude>';
$stopXMLString=$stopXMLString.'<Longitude>'.$row[4].'</Longitude>';
$stopXMLString=$stopXMLString.'<StopName>'.htmlentities($row[1]).'</StopName>';
$stopXMLString=$stopXMLString.'</Route>';
}
$stopXMLString=$stopXMLString.'</TraceRoutes>';
//echo $stopXMLString;
return $stopXMLString;
}
// this will give you the position of the stop on the bus route
function getStopNumberOnBusRoute($stopName,$busNumber)
{
$query="Select StopNumber From newBusDetails where StopName='".$stopName."' and BusNumber='".$busNumber."'";
$result=mysql_query($query);
$row=mysql_fetch_row($result);
return $row[0];
}
/**
* getNumberOfBusesForStop: This is the function to find out how many buses operate through a stop.
* the number of buses passing through teh stop is one of the criteria of filtering the nearest stop for the user
**/
function getNumberOfBusesForStop($stopName)
{
// for each stop found also get the bus number .. also I want BIAS and G series to be considered last so order by
$busQuery="Select BusNumber from newBusDetails where StopName='".$stopName."'ORDER BY BusNumber DESC";
$busResult= mysql_query($busQuery);
$busRowsnum = mysql_num_rows($busResult);
return $busRowsnum;
}
/*
given the latitudee and longitude of the address, it will find out the bus stops
within the vicinity
*/
function getBusStopsGivenLatLong($addrLat,$addrLong)
{
$stopXMLString='<BusStops>';
$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;
$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>No Stop available in the vicinity</Info>";
$stopXMLString=$stopXMLString."<ErrorCode>NA</ErrorCode>";
$stopXMLString=$stopXMLString."<Stops>";
$stopXMLString=$stopXMLString."<Stop>";
$stopXMLString=$stopXMLString."</Stop>";
$stopXMLString=$stopXMLString."</Stops>";
}
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();
}
$stopXMLString=$stopXMLString.'</BusStops>';
return $stopXMLString;
}
/**
* getStopForAddress: This function will take the address in free string as the input and
* will try to resolve that address to recognized stops.
* There are 3 places where the search is made
1. the search is made in the stops database whihc is the collection of all the valid stops
2. Next the search is made in the roadaddresses which is the database for the valid roads. we have identified a prominenet Latitude/long information
and we try to find the nearest stop to that lat/long based on the stop database
3. Finally we go to the internet using the google api to find the address.
TODO: We need to enter the address in the road address database so that next time we can save on the lookup time
**/
/**
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 // the address was valid and need to extract the location
{
$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 //we have found the stops. a collection of stops in that area
{
$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();
}
}
}
//we found some addresses but more than one was matching. We need some more specific on that
// basically more than one road adress match
// this should not be a case ...should be an error if the address reach here
// I think we need to add the log statement here
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 // the address is found in the road database
{
// 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;
}
//for testing //http://localhost/bmtcroutes/GetBusRouteDetails.php?sourceStopName=Bellandur%20Gate%20(ORR)&destStopName=Marathahalli%20Bridge&sourceOffset=0&destOffset=0&onlyIndirectRout//es=0
function sortBasedOnBusFrequency($SortArray)
{
//print_r($SortArray);//bugtest
$array_size=sizeof($SortArray);
//$arrFrequency=getAllBusFrequency();
for($x = 0; $x < $array_size; $x++)
{
for($y = 0; $y < $array_size; $y++)
{
if(getBusFrequencyScore($SortArray[$x]) > getBusFrequencyScore($SortArray[$y]))
{
$hold = $SortArray[$x];
$SortArray[$x] = $SortArray[$y];
$SortArray[$y] = $hold;
}
}
}
//echo "After sorting";
//print_r($SortArray);
return $SortArray;
}
/**
* The sort function will use the collective frequency value from the indirectBusStructureWithFrequency to sort the
* indirect buses
* The collective frequency can represent the summation of the bus frequency or junction frequency
* @param $SortArray
* @return mixed
*/
function sortBasedOnCollectiveFrequency($SortArray)
{
$array_size=sizeof($SortArray);
//$arrFrequency=getAllBusFrequency();
for($x = 0; $x < $array_size; $x++)
{
for($y = 0; $y < $array_size; $y++)
{
if($SortArray[$x]->getCollectiveFrequency() > $SortArray[$y]->getCollectiveFrequency())
{
$hold = $SortArray[$x];
$SortArray[$x] = $SortArray[$y];
$SortArray[$y] = $hold;
}
}
}
return $SortArray;
}
/*
*
* I think this code needs to be changed as the collective frequency is no longer valid..29/09/2013
*/
function sortBasedOnJunctionFrequency($SortArray)
{
$array_size=sizeof($SortArray);
//$arrFrequency=getAllBusFrequency();
for($x = 0; $x < $array_size; $x++)
{
for($y = 0; $y < $array_size; $y++)
{
//if($SortArray[$x]->getCollectiveFrequency() > $SortArray[$y]->getCollectiveFrequency())
//need to do this only if the junction frequency is high
if($SortArray[$x]->getFirstJunctionFrequency()>5 && $SortArray[$x]->getSecondJunctionFrequency()>5)
{
$totDistanceDiff=$SortArray[$x]->getTotalRouteDistance()-$SortArray[$y]->getTotalRouteDistance();
/*if(((float)$totDistanceDiff > -2 && (float)$totDistanceDiff < 2 ) &&
($SortArray[$x]->getJunctionDistance() < $SortArray[$y]->getJunctionDistance()))*/
if((float)$totDistanceDiff > -2 && (float)$totDistanceDiff < 2 )
{
$hold = $SortArray[$x];
$SortArray[$x] = $SortArray[$y];
$SortArray[$y] = $hold;
}
}
}
}
return $SortArray;
}
/**
* Based on thedistance between the junctions sort the indirect arracy in ascending order
* @param $SortArray
* @return mixed
*/
function sortBasedOnJunctionDistances($SortArray)
{
$array_size=sizeof($SortArray);
//$arrFrequency=getAllBusFrequency();
for($x = 0; $x < $array_size; $x++)
{
for($y = 0; $y < $array_size; $y++)
{
if($SortArray[$x]->getDistanceBetweenJunctions() < $SortArray[$y]->getDistanceBetweenJunctions())
{
$hold = $SortArray[$x];
$SortArray[$x] = $SortArray[$y];
$SortArray[$y] = $hold;
}
}
}
return $SortArray;
}
/**
* Based on the total route distance
* @param $SortArray
* @return mixed
*/
function sortBasedOnTotalRouteDistance($SortArray)
{
$array_size=sizeof($SortArray);
//$arrFrequency=getAllBusFrequency();
for($x = 0; $x < $array_size; $x++)
{
for($y = 0; $y < $array_size; $y++)
{
if($SortArray[$x]->getTotalRouteDistance() < $SortArray[$y]->getTotalRouteDistance())
{
$hold = $SortArray[$x];
$SortArray[$x] = $SortArray[$y];
$SortArray[$y] = $hold;
}
}
}
return $SortArray;
}
// get the frequency on the basis of the frequencies of the two buses
function getBusFrequencyScore($busData)
{
/**
The below code was returning wrong or less number of routes compared to the one that I tested on the
* desktop like Shabari Nagar Cross to Electronic City (Wipro Gate)
*/
//echo $busData."<br/>";
/*list($bus1,$freq1,$bus2,$freq2)=explode(":",$busData);
$freq=$freq1+$freq2;
echo "freq=".$freq;
return $freq1+$freq2;
*/
//copied from the desktop verions
$arrData=explode(":",$busData);
if(sizeof($arrData)>2)
return $arrData[1]+$arrData[3];
else
return $arrData[1];
}
function getBusFrequencyScoreOld($arrFrequency,$busData)
{
list($bus1,$bus2)=explode(":",$busData);
return $arrFrequency[trim($bus1)]+$arrFrequency[trim($bus2)];
}
function getAllBusFrequency()
{
$query="Select BusNumber,Frequency from busFrequency";
$result=mysql_query($query);
$rowsnum=mysql_num_rows($result);
// need to create an associative array that can be easily queried
$arrFrequency=array();
for($j=0;$j<$rowsnum;$j++)
{
$row=mysql_fetch_row($result);
$arrFrequency[$row[0]]=$row[1];
}
return $arrFrequency;
}
/**
*applyFilterForAddress:function to re sort the staions on the basis of the number of the stops and the distance from the
actual address
* this is the function that will decide on the order of the stops
check the number of the buses. If the number of buses in the first stop is >5 then we can return the array without doing any check
else from the array try to find the stop whihc is the minimal distant and has more than 3 buses.
We may have to change it again.
*/
function applyFilterForAddress($arrAddress)
{
//print_r($arrAddress);
if(getNumberOfBusesForStop($arrAddress[0]->getStopName())>5)
return $arrAddress;
$array_size=sizeof($arrAddress);
//echo "arraySize".$array_size;
for($x = 0; $x < $array_size; $x++)
{
for($y = 0; $y < $array_size; $y++)
{
// echo "sdkhkshdkhskhds".getNumberOfBusesForStop($arrAddress[$x]->getStopName())."<br/>";
if((getNumberOfBusesForStop($arrAddress[$x]->getStopName()) > getNumberOfBusesForStop($arrAddress[$y]->getStopName())) &&
($arrAddress[$x]->getDistance()<0.75))
{
//echo "dsdks";
$hold = $arrAddress[$x];
$arrAddress[$x] = $arrAddress[$y];
$arrAddress[$y] = $hold;
}
}
}
//
/*for($i=0;$i<sizeof($arrAddress);$i++)
{
$stopName=$arrAddress[$i]->getStopName();
// find the number of buses
sizeof(getBusesForStop($row[0]));
}*/
//print_r($arrAddress);
return $arrAddress;
}
//If the database is in place then the call should be
function getBusRoutesForRendering($log,$startStop,$endStop,$startOffsetDistance,$endOffsetDistance,$showOnlyIndirectRoutes)
{
//go to the database
//find the route information which is error code, depot name1,depot name2, indirect route, startdepotdistance, endDepotDistance,junction1, junction2
//routetype : direct or indirect
//construct a route string and return to the caling function.
//ifshowonlyINdirectBuses then find only the indirect route else try to find the direct first, if not then indirect
//return the xml.
$startBuses=explode(",",getBusesForStopWithFrequency($startStop));
$endBuses=explode(",",getBusesForStopWithFrequency($endStop));
//print_r($startBuses);
//print_r($endBuses);
// for now pick the first entry as the bus number but we need to do some optimization on choosing the buses based on their frequency, the stop number etc
//$arrCommonBuses=getCommonBuses($startBuses,$endBuses,$showOnlyIndirectRoutes);
// print_r($arrCommonBuses);
//echo getJunctionsForIndirectBuses($arrCommonBuses,$startStop,$endStop,$startDistance,$endDistance);
//I guess pass the log in this function also to print the log message
$status= getJunctionsForIndirectBusesRevamp2($log,$startStop,$endStop,$startBuses,$endBuses,$startOffsetDistance,$endOffsetDistance,$showOnlyIndirectRoutes);
if($status=="404" || $status=="405")
{
$arrRows=array();
$arrDirectRows=array();
//I am assuming that for the given source and end there is only one type of depot error code. So it can be either 7,8,9,10 but not both
//check the database for the error code and output
$sql="Select * from depotBusRoutes where SourceStartStop='".$startStop."' and DestinationEndStop='".$endStop."'";
$result=mysql_query($sql);
$rowsnum=mysql_num_rows($result);
if($rowsnum==0)
{
//check in the other database if the data is present over there
$sqlDirect="Select * from directDepotBusRoutes where StartStop='".$startStop."' and EndStop='".$endStop."'";
$resultDirect=mysql_query($sqlDirect);
$rowsnumDirect=mysql_num_rows($resultDirect);
if($rowsnumDirect==0)
return exceptionalCondition($startStop,$endStop);
else
{
//this will take care of 6,7,8
//echo "Total Routes".$rowsnum;
for($i=0;$i<$rowsnumDirect;$i++)
{
$rowDirect=mysql_fetch_object($resultDirect);
// print_r($row)."<br/>";
if($rowDirect->DepotErrorCode=="411")
{
$strRoute='<Routes>';
$strRoute=$strRoute.'<Route>';
$strRoute=$strRoute.'<IsDirectRoute>N</IsDirectRoute>';
$strRoute=$strRoute.'<ErrorCode>411</ErrorCode>';
$strRoute=$strRoute.'<StartStop>'.$startStop.'</StartStop>';
$strRoute=$strRoute.'<EndStop>'.$endStop.'</EndStop>';
$strRoute=$strRoute.'</Route>';
$strRoute=$strRoute.'</Routes>';
// $log->LogDebug("[".$mediaType."] The result status is 411 between ".$startStop." and ".$endStop);
return $strRoute;
}
else if($rowDirect->DepotErrorCode=="6"||$rowDirect->DepotErrorCode=="7"||$rowDirect->DepotErrorCode=="8")
{
//$log->LogDebug("[".$mediaType."] The result status is ".$rowDirect->DepotErrorCode." between ".$startStop." and ".$endStop);
array_push($arrDirectRows,$rowDirect);
// print_r($arrDirectRows);
}
else
{
echo "something is really wrong 678";
}
}
//add the print
//this is the case which will come if somehow the errorcode1 is missed as it was happening before. the errorcode 6 is
//same as errorcode 1 but these cases are normally getting missed out initially
if($arrDirectRows[0]->DepotErrorCode=="6")