-
Notifications
You must be signed in to change notification settings - Fork 4
/
NWS_Placefile_Alerts.php
1628 lines (1468 loc) · 55.4 KB
/
NWS_Placefile_Alerts.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
error_reporting(E_ALL);
ini_set('display_errors','1');
/*
* Name: NWS_Placefile_Alerts.php
* Author(s): Mike Davis 0617 , Ken True saratoga-weather.org
* Description: Reads NWS CAP1.1 ATOM RSS Alert Feeds for one or more states
* and displays a GR2 placefile describing affected polygons.
* rewritten to use api.weather.gov/alerts/active JSON from original XML by Ken True 29-Aug-2023
*/
# Version 2.00 - 29-Aug-2023 - initial release
# Version 2.01 - 30-Aug-2023 - improved popup display and area display
# Version 2.02 - 01-Sep-2023 - added icons to alert area displays (where available)
# Versoon 2.04 - 02-Sep-2023 - added timezone times to popup display
# Version 2.05 - 05-Sep-2023 - fix unclosed polygon info from shapefile
# Version 2.06 - 05-Sep-2023 - replace $Geometry->getWKT() with $Geometry->getArray() processing
# Version 2.07 - 06-Sep-2023 - use multiple Polygon: and Line: for each multipoint coord set
# Version 2.08 - 19-Sep-2023 - sort alerts by severity with most severe drawn on top (last)
# Version 2.09 - 20-Sep-2023 - added additional sort to have better displays for alerts
# Version 2.10 - 22-Sep-2023 - added plotting by ring data to improve area displays
# Version 2.11 - 09-Oct-2023 - added zone info to placefile output for debugging
# Version 2.12 - 16-Oct-2023 - change to alert query URLs
# Version 2.13 - 19-Oct-2023 - add Ramer-Douglas-Peucker functions to simplify coordinates where needed
# Version 2.14 - 20-Oct-2023 - remove > 9999 limit with prune_polygon active
# Version 2.15 - 20-Oct-2023 - remove > 9999 limit with multi-pass simplify_RDP calls to prune points
# Version 2.16 - 22-Oct-2023 - add debug and sce=view, correct severity sorting issue
# Version 2.17 - 26-Oct-2023 - find crude centroid of NWS supplied alert polygons to position Icon
$Version = "NWS_Placefile_Alerts.php - V2.17 - 26-Oct-2023 - saratoga-weather.org";
# -----------------------------------------------
# Settings:
# excludes:
$excludeAlerts = array(
"Severe Thunderstorm Warning",
"Severe Weather Statement",
"Tornado Warning",
"Flash Flood Warning",
"Special Weather Statement"
);
$excludeAlerts = array(); /* debug */
$TZ = 'UTC'; # default timezone for display
$timeFormat = "d-M-Y g:ia T"; # display format for times
$maxDistance = 350; # generate entries only within this distance
$cacheFilename = 'response_land.json'; # store json here
$cacheTimeMax = 480; # number of seconds cache is 'fresh'
$alertsURL = 'https://api.weather.gov/alerts/active?status=actual®ion_type=land';
$showDetails = true; # =false, show areas only; =true, show lines with popups
$showMarine = true; # =true; for marine alerts, =false for land alerts
#
$pruneThreshold = 0.0005; # lat/long threshold for pruning points from polygons
$prunePoints = 1000; # prune coords with more than this number of points
#
$latitude = 37.155;
$longitude = -121.898;
$version = 1.5;
$doLogging = true;
$doDebug = false; # =true; turn on additional display, may break placefile for GRLevelX
# NWS timezone abbreviations used per https://www.weather.gov/gis/Counties
# appears in Forecast, County and Fire zones (not in Marine)
$NWStimeZones = array (
'A' => 'America/Anchorage', // alaska
'Ah' => 'America/Anchorage', // alaska islands
'C' => 'America/Chicago', // central
'CE' => 'America/Chicago', // florida west
'CM' => 'America/Chicago', // north dakota
'E' => 'America/New_York', // eastern
'F' => 'Pacific/Fiji', // Fiji and Yap
'G' => 'Pacific/Guam', // guam and marianas
'H' => 'Pacific/Honolulu', // hawaii - no DST
'J' => 'Asia/Tokyo', // japan
'K' => 'Pacific/Kwajalein', // Marshall islands
'M' => 'America/Denver', // mountain
'MC' => 'America/Denver', // nebraska
'MP' => 'America/Los_Angeles', // idaho - western
'Mm' => 'America/Denver', // arizona/reservations with DST
'P' => 'America/Los_Angeles',// pacific
'S' => 'Pacific/Pago_Pago', // samoa
'V' => 'America/St_Thomas', // Puerto Rico/St Thomas etc.
'h' => 'America/Adak', // hawaii with DST observed
'm' => 'America/Phoenix', // mountain-no DST
);
# -----------------------------------------------
header("Content-Type: text/plain");
global $pruneThreshold,$prunePoints;
//--self downloader --
if(isset($_REQUEST['sce']) and strtolower($_REQUEST['sce']) == 'view') {
$filenameReal = __FILE__;
$download_size = filesize($filenameReal);
header('Pragma: public');
header('Cache-Control: private');
header('Cache-Control: no-cache, must-revalidate');
header("Content-type: text/plain,charset=ISO-8859-1");
header("Accept-Ranges: bytes");
header("Content-Length: $download_size");
header('Connection: close');
readfile($filenameReal);
exit;
}
if(isset($doShowDetails)) {$showDetails = $doShowDetails;}
if(isset($doShowMarine)) {$showMarine = $doShowMarine;}
$titleExtra = ($showDetails)?'Details':'Areas';
if($showMarine) {
$titleExtra = 'Marine '.$titleExtra;
$alertsURL = 'https://api.weather.gov/alerts/active?status=actual®ion_type=marine';
$cacheFilename = str_replace('land','marine',$cacheFilename);
}
if(isset($_GET['debug']) and $_GET['debug'] == 'y') {$doDebug = true;}
if(isset($_GET['lat'])) {$latitude = $_GET['lat'];}
if(isset($_GET['lon'])) {$longitude = $_GET['lon'];}
if(isset($_GET['version'])) {$GRversion = $_GET['version'];}
if(isset($latitude) and !is_numeric($latitude)) {
print "Bad latitude spec.";
exit;
}
if(isset($latitude) and $latitude >= -90.0 and $latitude <= 90.0) {
# OK latitude
} else {
print "Latitude outside range -90.0 to +90.0\n";
exit;
}
if(isset($longitude) and !is_numeric($longitude)) {
print "Bad longitude spec.";
exit;
}
if(isset($longitude) and $longitude >= -180.0 and $longitude <= 180.0) {
# OK longitude
} else {
print "Longitude outside range -180.0 to +180.0\n";
exit;
}
if(!isset($latitude) or !isset($longitude) or !isset($GRversion)) {
print "This script only runs via a GRlevelX placefile manager.";
exit();
}
//*/
if(isset($doLogging) and $doLogging) {
$fn = "NWS-placefile-log-".gmdate('Y-m-d').'.txt';
$log = gmdate('H:i:s'). " ";
$log .= isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']." ":"x.x.x.x ";
$log .= isset($_SERVER['SCRIPT_URI'])?$_SERVER['SCRIPT_URI']:'(no-URI)';
$log .= isset($_SERVER['QUERY_STRING'])?"?".$_SERVER['QUERY_STRING']:"?(no-QUERY)";
file_put_contents($fn,$log.PHP_EOL,FILE_APPEND);
}
// Register autoloader
require_once('php-shapefile/src/Shapefile/ShapefileAutoloader.php');
Shapefile\ShapefileAutoloader::register();
// Import classes
use Shapefile\Shapefile;
use Shapefile\ShapefileException;
use Shapefile\ShapefileReader;
include_once("NWS-zones-inc.txt"); # Master zone:shapefiles lookup table
global $zoneLookup, $showDetails,$doDebug;
include_once('WWAColors.php'); # colors array indexed by alert headline
date_default_timezone_set($TZ);
# Note: we accumulate placefile output into $output as various parts are appended
# then the whole shebang is printed as the placefile.
#
$today = date("D M j G:i:s T Y");
$output = "; $Version\n";
$output .= "; running on PHP ".phpversion()."\n";
$output .= "Title: NWS Alert $titleExtra - $today\n";
$output .= "Refresh: 8\n";
$output .= "Font: 1, 11, 1, \"Arial\"\n\n";
if(!$showDetails) { # display icons in middle of areas
$output .= "IconFile: 1, 17, 17, 8, 8, alerts-icons.png\n";
}
if($doDebug) { $output .= "; main calling JSONread\n"; }
$output .= JSONread($alertsURL);
if($doDebug) { $output .= "; main ends\n"; }
echo $output;
# -----------------------------------------------------
# functions
function JSONread($url) {
global $zoneLookup, $cacheFilename,$cacheTimeMax,$latitude,$longitude, $maxDistance,$showDetails,$titleExtra,$doDebug ;
# read alerts.weather.gov for active alerts and process the JSON return
# author: Ken True - [email protected]
# Version 1.00 - 24-Aug-2023 - initial release
$out = ''; #collector for GRLevelX placefile statements
if($doDebug) {$out .= "; JSONread entered\n"; }
$STRopts = array(
'http' => array(
'method' => "GET",
'protocol_version' => 1.1,
'header' => "Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (NWS_Polygon_Alerts_Colored - saratoga-weather.org)\r\n" .
"Accept: application/json,application/xml\r\n"
) ,
'ssl' => array(
'method' => "GET",
'protocol_version' => 1.1,
'verify_peer' => false,
'header' => "Cache-Control: no-cache, must-revalidate\r\n" .
"Cache-control: max-age=0\r\n" .
"Connection: close\r\n" .
"User-agent: Mozilla/5.0 (NWS_Polygon_Alerts_Colored - saratoga-weather.org)\r\n" .
"Accept: application/json,application/xml\r\n"
)
);
$STRcontext = stream_context_set_default($STRopts);
if(!file_exists($cacheFilename) or
(file_exists($cacheFilename) and filemtime($cacheFilename)+$cacheTimeMax < time()) ) {
$rawJSON = file_get_contents($url);
if(strpos($rawJSON,'geocode') !== false) {
file_put_contents($cacheFilename,$rawJSON);
$out .= "; cache file '$cacheFilename' refreshed from $url \n\n";
} else {
$out .= "; cache refresh failed to get good content\n";
if(file_exists($cacheFilename)) {
$rawJSON = file_get_contents($cacheFilename);
$out .= "; cache '$cacheFilename' reloaded\n";
}
}
} else {
$rawJSON = file_get_contents($cacheFilename);
$age = time()-filemtime($cacheFilename);
$out .= "; cache file '$cacheFilename' loaded. age=$age seconds.\n\n";
}
$JSON = json_decode($rawJSON,true,512,JSON_BIGINT_AS_STRING+JSON_OBJECT_AS_ARRAY);
#var_export($JSON,false);
#return;
if(function_exists('json_last_error')) {
switch (json_last_error()) {
case JSON_ERROR_NONE:
$JSONerror = '- No errors';
break;
case JSON_ERROR_DEPTH:
$JSONerror = '- Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$JSONerror = '- Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$JSONerror = '- Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$JSONerror = '- Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$JSONerror = '- Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$JSONerror = '- Unknown error';
break;
}
$out .= "; JSON decode - $JSONerror\n";
}
if (!isset($JSON['features'][0])) {
$out .= "; .. no data found\n";
if($doDebug) {$out .= "; JSONread returned\n"; }
return($out);
}
$out .= "; ".count($JSON['features'])." alerts found\n\n";
$out .= "\n; Sorting JSON by severity\n";
$Jseverity = array(); # keyed index by severity
foreach ($JSON['features'] as $i => $A) { # scan for severity
$severity = $A['properties']['severity'];
$event = $A['properties']['event'];
$level = get_priority($event);
if(isset($Jseverity["$level|$severity"])) {
$Jseverity["$level|$severity"] .= "|$i";
} else {
$Jseverity["$level|$severity"] = "$i";
}
}
$JSORTED = array();
ksort($Jseverity);
foreach ($Jseverity as $key => $idxlist) {
$vals = explode('|',$Jseverity[$key]);
$out .= "; severity='$key' has ".count($vals)." alerts\n";
foreach($vals as $j => $idx) {
if($idx >= 0) {$JSORTED[] = $idx;}
}
}
$out .= "; Sorting complete.\n\n";
if($doDebug) { file_put_contents('sorted-json.txt',var_export($JSORTED,true)); }
foreach ($JSORTED as $i => $idx) { # do the heavy lifting.. decode each alert in severity sort order
$A = $JSON['features'][$idx];
if($doDebug) {$out .= "\n; JSONread: idx=$idx calling decodeAlert\n";}
$out .= decodeAlert($A);
if($doDebug) {$out .= ";--------------\n; JSONread: decodeAlert returns\n";}
}
if($doDebug) {$out .= "\n; JSONread returns\n"; }
return($out); # this will be appended to $output in main
} // end JSONread function
#---------------------------------------------------------------------------
function decodeAlert($A) {
global $color,$zoneLookup,$excludeAlerts,$timeFormat,$latitude,$longitude,$maxDistance,$showDetails,$titleExtra,$doDebug;
global $NWStimeZones;
# Decode a specific alert
# return out as the full entry for the alert to JSONread for appending (uttimately) to $output for printing the placefile
#
# depending on $showDetails, either a Line:,coords,End: or a Polygon,coords,End:,Icon: will be returned for
# each active.
#
# Placefile comments (prepended with ;) will be returned for any issues found (expired, not in range, no coords availabl)
# Input JSON looks like:
/*
0 =>
array (
'id' => 'https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.f00965605f5fc6071fd73d662b77bb966ae93ad5.001.1',
'type' => 'Feature',
'geometry' =>
array (
'type' => 'Polygon',
'coordinates' =>
array (
0 =>
array (
0 =>
array (
0 => -80.23,
1 => 26.59,
),
1 =>
array (
0 => -80.12,
1 => 26.669999999999998,
),
2 =>
array (
0 => -79.98,
1 => 26.52,
),
3 =>
array (
0 => -80.12,
1 => 26.4,
),
4 =>
array (
0 => -80.23,
1 => 26.59,
),
),
),
),
'properties' =>
array (
'@id' => 'https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.f00965605f5fc6071fd73d662b77bb966ae93ad5.001.1',
'@type' => 'wx:Alert',
'id' => 'urn:oid:2.49.0.1.840.0.f00965605f5fc6071fd73d662b77bb966ae93ad5.001.1',
'areaDesc' => 'Inland Palm Beach County; Metro Palm Beach County; Coastal Palm Beach County',
'geocode' =>
array (
'SAME' =>
array (
0 => '012099',
),
'UGC' =>
array (
0 => 'FLZ067',
1 => 'FLZ068',
2 => 'FLZ168',
),
),
'affectedZones' =>
array (
0 => 'https://api.weather.gov/zones/forecast/FLZ067',
1 => 'https://api.weather.gov/zones/forecast/FLZ068',
2 => 'https://api.weather.gov/zones/forecast/FLZ168',
),
'references' =>
array (
),
'sent' => '2023-09-01T14:04:00-04:00',
'effective' => '2023-09-01T14:04:00-04:00',
'onset' => '2023-09-01T14:04:00-04:00',
'expires' => '2023-09-01T14:30:00-04:00',
'ends' => NULL,
'status' => 'Actual',
'messageType' => 'Alert',
'category' => 'Met',
'severity' => 'Moderate',
'certainty' => 'Observed',
'urgency' => 'Expected',
'event' => 'Special Weather Statement',
'sender' => '[email protected]',
'senderName' => 'NWS Miami FL',
'headline' => 'Special Weather Statement issued September 1 at 2:04PM EDT by NWS Miami FL',
'description' => 'At 203 PM EDT, National Weather Service meteorologists were tracking
a strong thunderstorm over Greenacres, or near Wellington, moving
southeast at 15 mph.
HAZARD...Winds in excess of 30 mph.
SOURCE...Radar indicated.
IMPACT...Gusty winds could knock down tree limbs and blow around
unsecured objects.
Locations impacted include...
Boca Raton, Boynton Beach, Delray Beach, Lake Worth, Ocean Ridge,
Greenacres, Palm Springs, Lantana, Atlantis, Village Of Golf, Kings
Point, Dunes Road, Hypoluxo, Gulf Stream, Briny Breezes, Manalapan,
Aberdeen, Lake Worth Corridor, Aberdeen Golf Course and Florida
Gardens.',
'instruction' => 'These winds can down small tree limbs and branches, and blow around
unsecured small objects. Seek shelter in a safe building until the
storm passes.',
'response' => 'Execute',
'parameters' =>
array (
'AWIPSidentifier' =>
array (
0 => 'SPSMFL',
),
'WMOidentifier' =>
array (
0 => 'WWUS82 KMFL 011804',
),
'NWSheadline' =>
array (
0 => 'A strong thunderstorm will impact portions of east central Palm Beach County through 230 PM EDT',
),
'eventMotionDescription' =>
array (
0 => '2023-09-01T18:03:00-00:00...storm...330DEG...13KT...26.6,-80.17',
),
'maxWindGust' =>
array (
0 => '30 MPH',
),
'maxHailSize' =>
array (
0 => '0.00',
),
'BLOCKCHANNEL' =>
array (
0 => 'EAS',
1 => 'NWEM',
2 => 'CMAS',
),
'EAS-ORG' =>
array (
0 => 'WXR',
),
),
),
),
*/
/* produce:
Color: 225 185 135
Line: 2, 0, "... <alert text>"
35.18, -83.34
35.22, -83.20
34.97, -82.98
34.88, -83.30
35.18, -83.34
End:
or
Polygon:
35.18, -83.34
35.22, -83.20
34.97, -82.98
34.88, -83.30
35.18, -83.34
End:
Icon: 2, 0, "... <alert text>"
*/
$isoDate = "Y-m-d\TH:i:s";
$out = ''; # used for accumulation of return output
if($doDebug) {$out .= "\n;--------------\n; decodeAlert entered\n"; }
$P = $A['properties']; # just to make the following simpler
# gather common boilerplate
$event = $P["event"];
$headline = str_replace("\n",'\n',$P["headline"]); # convert embedded newline into \n chars
$headline = str_replace('"','\"',$headline); # swap embedded " with \"
if(!empty($P['description'])) {
$description = str_replace("\n",'\n',$P["description"]); # convert embedded newline into \n chars
$description = str_replace('"','\"',$description); # swap embedded " with \"
} else {
$description = '';
}
$event_onset = $P["onset"];
$onset = date($timeFormat,strtotime($event_onset));
$event_expires = $P["expires"];
$UTCexpires = strtotime($P["expires"]);
$expires = date($timeFormat,$UTCexpires);
$severity = $P['severity'];
$certainty = $P['certainty'];
$urgency = $P['urgency'];
$senderName = $P['senderName'];
$NWSheadline = isset($P['parameters']['NWSheadline'][0])?
str_replace("\n",'\n',join(' ',$P['parameters']['NWSheadline'])):'';
if(!empty($P['ends'])) {
$UTCexpires = strtotime($P["ends"]);
$ends = date($timeFormat,$UTCexpires);
} else {
$ends = $event_expires;
}
$cLat = '';
$cLon = '';
if($doDebug) {
$out .= "; decodeAlert: ";
$out .= isset($A['geometry']['coordinates'])?" geometry polygon exists\n":" geometry polygon not found\n";
#$out .= "; \$A=".var_export($A,true)."\n;--------------\n";
}
if(isset($A['geometry']['coordinates'])) { # not all events include NWS polygons
$coords = ''; # accumulate list of coordinates
foreach ($A['geometry']['coordinates'] as $n => $item) {
foreach ($item as $j => $latlon) {
$lat = sprintf("%01.4f",$latlon[1]);
$long = sprintf("%01.4f",$latlon[0]);
$coords .= "$lat,$long\n";
}
}
$nCoords = explode("\n",$coords);
$firstCoord = $nCoords[0]; # used for placement of icon if geometry is provided
$out .= "; NWS polygon starting $firstCoord for ".count($nCoords)." points.\n";
list($tFC,$tMsg) = get_center($nCoords);
if($tFC !== false) {$firstCoord = $tFC;}
$out .= $tMsg;
if($showDetails) {
$coordsFrom = '\n(lines are around NWS alert area)\n';
} else {
$coordsFrom = '\n(shading is NWS alert area)\n';
}
if($doDebug) {$out .= "; decodeAlert: ".count($nCoords)." polygon coords found. firstCoord='$firstCoord'\n"; }
} else { # no geometry provided .. will create later from Zone entries
$coords = '';
$nCoords = array();
$firstCoord = '';
$coordsFrom = '';
if($doDebug) {$out .= "; decodeAlert: no polygon coords found\n"; }
}
# get list of all Zones in the alert
if(isset($P['geocode']['UGC'][0]) ) {
$fZone = $P['geocode']['UGC'][0];
if(isset($zoneLookup[$fZone])) { # check that we have info on this Zone
# 'FLC133' => 'C|2380|Washington, FL|30.6106|-85.6656|C',
# 'FLZ010' => 'F|2897|Washington|30.6106|-85.6656|C\tW|2397|Washington|30.6106|-85.6656|C',
$v = explode("\t",$zoneLookup[$fZone]."\t"); # Forecast and Fire Zones may have been merged
$v = explode('|',$v[0].'|');
$cLat = $v[3];
$cLon = $v[4];
$TZ = $v[5];
# see if we're keeping this alert or not based on distance from current radar selected in GRLevel3
list($miles,$km,$bearingDeg,$bearingWR) =
GML_distance((float)$latitude, (float)$longitude,(float)$v[3], (float)$v[4]);
if($miles > $maxDistance) {
$out .= "; $headline \n";
$out .= "; severity=$severity\n";
$tZones = implode(', ',$P['geocode']['UGC']);
$out .= "; zone(s) '$tZones'\n";
$out .= "; active: $onset to $expires\n";
$out .= "; excluded by distance $miles > $maxDistance max.\n\n";
if($doDebug) { $out .= "; decodeAlert: returned-#2\n"; }
return($out); # nope.. to far away, return with that result.
}
}
}
# see if we need to skip this event type
if(in_array($event,$excludeAlerts)) {
$out .= "; $headline \n";
$out .= "; active: $onset to $expires\n";
$out .= "; severity=$severity\n";
$tZones = implode(', ',$P['geocode']['UGC']);
$out .= "; zone(s) '$tZones'\n";
$out .= "; excluded in \$excludeAlerts\n\n";
if($doDebug) { $out .= "; decodeAlert: returned-#3\n"; }
return($out); # yes, excluded by event
}
# see if the event has expired (unlikely, I hope)
if(time() > $UTCexpires) {
$out .= "; $headline \n";
$out .= "; active: $onset to $expires\n";
foreach (array("sent","effective","onset","expires","ends") as $i => $key) {
if(isset($P[$key])) {
$out .= "; ".str_pad("$key:",10)." ".$P[$key]."\n";
} else {
$out .= "; ".str_pad("$key:",10)." n/a\n";
}
}
$out .= "; severity=$severity\n";
$tZones = implode(', ',$P['geocode']['UGC']);
$out .= "; zone(s) '$tZones'\n";
$out .= "; excluded as expired. Now=".gmdate($timeFormat)."\n\n";
if($doDebug) { $out .= "; decodeAlert: returned-#4\n"; }
return($out); # avoid the expired alert
}
if(substr($coords,0,1) == ';') { # likely error message from Shapefile listing
$tOut .= $coords."\n";
if($doDebug) { $tOut .= "; decodeAlert: returned-#5\n"; }
return($out.$tOut); # can't display due to bad coords
}
# Now complete decode of event data
$UGC = '';
$UGC_array = array();
# get list of Zones
if(isset($P['geocode']['UGC'])){
$UGC = implode(',',$P['geocode']['UGC']);
$UGC_array = $P['geocode']['UGC'];
}
$UGC_list = str_replace(',',', ',$UGC);
$tOut = ''; # Main event text comments
if(isset($color[$event])) {
list($css,$colors,$csshex) = $color[$event];
} else {
list($css,$colors,$csshex) = array('lightgrey','128 128 128',"F0F0F0");
}
$prefix = "; $event\n";
$prefix .= "; active: $onset to $ends\n";
$timeMarker = '%times%';
$popup_template = "$event\\n\\n";
$popup_template .= $timeMarker."\\n"; # replaced by str_replace('%times',get_popup_local_times($P,$zone),$popup_template);
$popup_template .= "Zone(s): $UGC_list\\n".
"Severity: $severity\\n".
"Urgency: $urgency\\n".
"Certainty: $certainty\\n".
"Sender: $senderName\\n".
"\\n$headline\\n\\n".
"$NWSheadline" . "\"\n";
# "\\n\\n$headline\\n\\n$description"."\"\n";
if($doDebug) {
$out .= "; decodeAlert: coords length= ".strlen($coords)."\n";
$out .= "; decodeAlert: coords='".str_replace("\n",' ',$coords)."'\n";
}
if($doDebug) { $out .= "; decodeAlert: before UGS processing\n"; }
if(strlen($coords) < 10) { # no main coords.. get the Zone coords instead
if($doDebug) { $out .= "; decodeAlert: begin UGS processing\n"; }
$out .= "; $event .. no coords, generating zone coords UGC='$UGC'\n";
$out .= "; severity=$severity\n";
$tZones = implode(', ',$P['geocode']['UGC']);
$out .= "; zone(s) '$tZones'\n";
foreach ($UGC_array as $k => $zone) {
if(isset($zoneLookup[$zone])) {
# would lookup
$prefix .= "; zone=$zone '".$zoneLookup[$zone]."'\n";
} else {
$prefix .= "; zone=$zone not found.\n\n";
if($doDebug) { $prefix .= "; decodeAlert: returned-#6\n"; }
return($out.$prefix); # oops.. an Unknown-to-us zone
}
}
}
if($doDebug) { $out .= "; decodeAlert: after UGS processing\n"; }
if($doDebug) { $out .= "; decodeAlert: before coords processing\n"; }
if(strlen($coords) > 10) {
if($doDebug) { $out .= "; decodeAlert: coords processing\n"; }
if(!$showDetails) { # for areas, change the first coordinate to have the color scheme
list($cLat,$cLon) = explode(',',$firstCoord);
$coords = $firstCoord.",".str_replace(' ',',',$colors).",150\n".$coords;
}
if(empty($tCmd)) { # tCmd is used for the main command
$tCmd = '';
if($showDetails) { # do Line
$tCmd .= "Color: $colors\n";
$tCmd .= 'Line: 2, 0, "' . str_replace($timeMarker,get_popup_local_times($P,$UGC_array[0]),$popup_template);
} else { # do Polygon
$colors = str_replace(' ',',',$colors);
$icon = get_iconnumber($event);
$tCmd .= "Polygon:\n";
}
}
if($showDetails) { # a Line: command
$out .= $prefix.str_replace("\"\n",$coordsFrom."\"\n",$tOut.$tCmd).$coords;
$out .= "End:\n";
} else { # a Polygon: command
$out .= $prefix.$tOut.$tCmd.$coords;
$out .= "End:\n";
$popup = str_replace($timeMarker,get_popup_local_times($P,$UGC_array[0]),$popup_template);
$out .= "Icon: $cLat,$cLon,0,1,$icon,\"".str_replace("\"\n",$coordsFrom."\"\n",$popup);
}
$out .= "; end geometry entry\n\n";
if($doDebug) { $out .= "; decodeAlert returned-#7\n"; }
return($out); # finished an entry for alert with geometry
}
if($doDebug) { $out .= "; decodeAlert: after coords processing\n"; }
# oops.. havent returned, so handle no coords.. use Zones and generate a dup for each listed zone
foreach ($UGC_array as $k => $zone) { # loop zones and create entries
# 'FLZ141' => 'F|3729|Coastal Volusia|29.0917|-80.9840|E\tW|3307|Coastal Volusia|29.0917|-80.9840|E',
# 'GMZ335' => 'M|92|Galveston Bay|29.4906|-94.8590|HGX',
$v = explode("\t",$zoneLookup[$zone]."\t"); # split off forecast/fire zones if needed
$v = explode('|',$v[0].'|'); # add a delimiter for marine zones with no TZ
$cLat = $v[3];
$cLon = $v[4];
$TZ = $v[5];
list($coords,$errors,$coordsArray) = get_shape_coords($zone); # this does a coordinate retrieval from the shapefile
$nCoords = explode("\n",$coords);
if($showDetails) {
$coordsFrom = '\n(lines are around Zone '.$zone.')\n';
} else {
$coordsFrom = '\n(shading is Zone '.$zone.')\n';
}
$tCmd = "; this zone is $zone with ".count($nCoords)." coordinates.\n";
if($showDetails) { # do Line: command
$tCmd .= "Color: $colors\n";
$popup = str_replace($timeMarker,get_popup_local_times($P,$zone),$popup_template);
$LineCmd = 'Line: 2, 0, "' . $popup;
$tCmd .= $LineCmd;
if(count($coordsArray) > 1) {
$coords = $coordsArray[0]; # multiple segments.. use first one.
$nCoords = explode("\n",$coords);
}
} else { # do Polygon and Icon commands
$colors = str_replace(' ',',',$colors);
if(!empty($cLat) and !empty($cLon)) {
$icon = get_iconnumber($event);
}
$LineCmd = '';
$tCmd .= "Polygon:\n";
}
$firstCoord = $nCoords[0];
if(count($nCoords) > 99999) { # disabled after adding prune_polygon function
$out .= $prefix."; too many coordinates to plot on GRLevel3 for ".$zone." (".count($nCoords).") .. skipping.\n\n";
unset($nCoords);
$coords = '';
continue; # skip to next Zone
}
if(count($nCoords) < 3) {
$out .= $prefix."; too few coordinates to plot on GRLevel3 for ".$UGC_array[0]." (".count($nCoords).") .. skipping.\n\n";
unset($nCoords);
continue; # skip to next Zone
}
unset($nCoords);
if(!$showDetails and count($coordsArray) > 1) { # Polygon .. needs color info on first coordinate
foreach ($coordsArray as $kk => $coords) {
$tC = explode("\n",$coords);
$firstCoord = $tC[0];
$coords = $firstCoord.",".str_replace(' ',',',$colors).",150\n".$coords;
$out .= "; polygon $kk has ".count($tC)." points.\n";
$out .= "Polygon:\n";
$out .= $coords;
$out .= "End:\n";
}
$out .= "; --- end multipolygon for area ---\n";
} else {
$coords = $firstCoord.",".str_replace(' ',',',$colors).",150\n".$coords;
$out .= $prefix.str_replace("\"\n",$coordsFrom."\"\n",$tOut.$tCmd).$coords;
$out .= "End:\n";
}
if($showDetails and count($coordsArray) > 1) {
$out .= "; --- multipolygon for line ---\n";
foreach ($coordsArray as $kk => $coords) {
if($kk == 0) {continue;} # already emitted it above
$out .= "; line $kk\n";
$out .= str_replace("\"\n",$coordsFrom."\"\n",$LineCmd);
$out .= $coords;
$out .= "End:\n";
}
$out .= "; --- end multipolygon for line ---\n";
}
if(strlen($errors) > 0) {
$out .= $errors;
}
if(!$showDetails) { # Polygon.. place Icon after so it will show on top of area in GRLevel3
$popup = str_replace($timeMarker,get_popup_local_times($P,$zone),$popup_template);
$out .= "Icon: $cLat,$cLon,0,1,$icon,\"".str_replace("\"\n",$coordsFrom."\"\n",$popup);
}
$out .= "; coords have ".count($coordsArray)." polygon rings \n";
$out .= "; end end zone $zone\n\n";
$coords = '';
}# end foreach zones - Rinse and repeat for each zone in alert
if($doDebug) { $out .= "; decodeAlert returned-#at end of script\n"; }
return($out);
} # end decodeAlert
#---------------------------------------------------------------------------
function get_popup_local_times ($P,$zone) {
global $zoneLookup,$NWStimeZones,$timeFormat,$doDebug;
# $P is the locl array of properties for the alert
$TZ = 'UTC';
$TZabbrev = '';
if(isset($zoneLookup[$zone])) {
$v = explode("\t",$zoneLookup[$zone]."\t"); # split off forecast/fire zones if needed
$v = explode('|',$v[0].'|'); # add a delimiter for marine zones with no TZ
$TZabbrev = $v[5];
if(isset($NWStimeZones[$TZabbrev])) {
$TZ = $NWStimeZones[$TZabbrev];
}
}
date_default_timezone_set($TZ);
$popup = '';
if($doDebug) {$popup = "TZabbrev='$TZabbrev' TZ='$TZ' for '$zone'\\n";}
foreach (array("sent","effective","onset","expires","ends") as $i => $key) {
if(isset($P[$key])) {
$timestamp = strtotime($P[$key]);
$popup .= ucfirst(str_pad("$key:",10))." ".date($timeFormat,$timestamp);
if($TZ !== 'UTC') {
$popup .= ' ('.gmdate('Hi',$timestamp).'Z)';
}
$popup .= "\\n";
} else {
$popup .= ucfirst(str_pad("$key:",10))." n/a\\n";
}
}
return($popup);
}
#---------------------------------------------------------------------------
function get_shape_coords ($zone) {
global $zoneLookup;
if(isset($zoneLookup[$zone])) {
# 'AKC013' => 'C|3331|Aleutians East, AK|55.4039|-161.8631',
list($db,$idx,$name,$clat,$clon) = explode('|',$zoneLookup[$zone]);
} else {
return(array(
"; get_shape_coords: '$zone' not found.\n",
"; get_shape_coords: '$zone' not found.\n") );
}
try {
// Open Shapefile
$filename = $zoneLookup['_'.$db];
$Shapefile = new ShapefileReader($filename, array(
Shapefile::OPTION_POLYGON_CLOSED_RINGS_ACTION => Shapefile::ACTION_FORCE,
Shapefile::OPTION_SUPPRESS_M => true,
Shapefile::OPTION_SUPPRESS_Z => true,
));
$fields = $Shapefile->getFieldsNames();
try {
$Shapefile->setCurrentRecord($idx);
// Fetch a Geometry
$Geometry = $Shapefile->fetchRecord();
// Skip deleted records
if ($Geometry->isDeleted()) {
return( array(
"; get_shape_coords -- deleted record idx=$idx\n",
"; get_shape_coords -- deleted record idx=$idx\n" ));
}
$GDATA = $Geometry->getArray();
$vals = array();
foreach ($fields as $i => $name) {
$vals[$name] = $Geometry->getData($name);
}
list($GRdata,$errors,$outArray) = convert_array_to_lines($GDATA);
return(array($GRdata,$errors,$outArray));
} catch (ShapefileException $e) {
// Handle some specific errors types or fallback to default
switch ($e->getErrorType()) {
// We're crazy and we don't care about those invalid geometries... Let's skip them!
case Shapefile::ERR_GEOM_RING_AREA_TOO_SMALL:
case Shapefile::ERR_GEOM_RING_NOT_ENOUGH_VERTICES:
break;
// Let's handle this case differently... :)
case Shapefile::ERR_GEOM_POLYGON_WRONG_ORIENTATION:
return(array(
"; get_shape_coords: Do you want the Earth to change its rotation direction?!?\n",
"; get_shape_coords: Do you want the Earth to change its rotation direction?!?\n",
));
break;
// A fallback is always a nice idea
default:
$str = "; get_shape_coords: Error Type: " . $e->getErrorType()
. " Message: " . $e->getMessage()
. " Details: " . $e->getDetails()
. "\n";
return(array($str,$str));
break;
}
}
} catch (ShapefileException $e) {
/*
Something went wrong during Shapefile opening!
*/
return ( array(
"; get_shape_coords: unable to open Shapefile $filename \n",
"; get_shape_coords: unable to open Shapefile $filename \n"
));
}
} # end get_shape_coords
#---------------------------------------------------------------------------
function convert_array_to_lines($GDATA) {
global $doDebug;
# convert the array-format shapefile to GRLevel3 usage
# Uses process_polygon to extract the point coordinated
# from each ring of data from the shapefile $Geography->getArray() format
/*
Polygon
array (
'numrings' => 16,
'rings' =>
array (
0 =>
array (
'numpoints' => 8556,
'points' =>
array (
0 =>
array (
'x' => -67.72191619899996,
'y' => 45.68241500900007,
),
Multipoint -
array (
'numparts' => 13,
'parts' =>
array (
0 =>
array (
'numrings' => 111,
'rings' =>
array (