-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPW-forecast.php
3069 lines (2652 loc) · 99.2 KB
/
PW-forecast.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
// PW-forecast.php script by Ken True - webmaster@saratoga-weather.org
// Forecast from pirateweather.net - based on DS-forecast.php V1.11 - 27-Dec-2022
//
// Version 1.00 - 16-Nov-2018 - initial release
// Version 1.01 - 17-Nov-2018 - added wind unit translation, fixed -0 temp display, added alerts (only English available)
// Version 1.02 - 19-Nov-2018 - added Updated: and Forecast by: display/translations
// Version 1.03 - 29-Nov-2018 - added fixes for summaries with embedded UTF symbols.
// Version 1.04 - 04-Dec-2018 - added Serbian (sr) language support
// Version 1.05 - 08-Dec-2018 - added optional current conditions display box, cloud-cover now used for better icon choices
// Version 1.06 - 05-Jan-2019 - fixed Hebrew forecast display for Saratoga template
// Version 1.07 - 07-Jan-2019 - formatting fix for Hebrew display in Saratoga template
// Version 1.08 - 15-Jan-2019 - added check for good JSON return before saving cache file
// Version 1.09 - 23-Jan-2019 - added hourly forecast and tabbed display
// Version 1.10 - 19-Jan-2022 - fix for PHP 8.1 Deprecated errata
// Version 1.11 - 27-Dec-2022 - fixes for PHP 8.2
// Version 2.00 - 14-Jan-2023 - repurposed PW-forecast.php to use Pirateweather.net API instead
// Version 2.50 - 18-Jan-2023 - replaced hourly view with merry-timeline 7-day hourly view summary
// Version 2.51 - 19-Jan-2023 - display ampm or 24h on timeline based on $timeFormat/$SITE['timeFormat']
// Version 2.52 - 24-Feb-2023 - removed conditions display 'n miles/km from' message as always zero from API
//
$Version = "PW-forecast.php (ML) Version 2.52 - 24-Feb-2023";
//
// error_reporting(E_ALL); // uncomment to turn on full error reporting
//
// script available at http://saratoga-weather.org/scripts.php
//
// you may copy/modify/use this script as you see fit,
// no warranty is expressed or implied.
//
// This script parses the darksky.net forecast JSON API and loads icons/text into
// arrays so you can use them in your weather website.
//
//
// output: creates XHTML 1.0-Strict HTML page (or inclusion)
//
// Options on URL:
//
// inc=Y - omit <HTML><HEAD></HEAD><BODY> and </BODY></HTML> from output
// heading=n - (default)='y' suppress printing of heading (forecast city/by/date)
// icons=n - (default)='y' suppress printing of the icons+conditions+temp+wind+UV
// text=n - (default)='y' suppress printing of the periods/forecast text
//
//
// You can also invoke these options directly in the PHP like this
//
// $doIncludePW = true;
// include("PW-forecast.php"); for just the text
// or ------------
// $doPrintPW = false;
// include("PW-forecast.php"); for setting up the $PWforecast... variables without printing
//
// or ------------
// $doIncludePW = true;
// $doPrintConditions = true;
// $doPrintHeadingPW = true;
// $doPrintIconsPW = true;
// $doPrintTextPW = false
// include("PW-forecast.php"); include mode, print only heading and icon set
//
// Variables returned (useful for printing an icon or forecast or two...)
//
// $PWforecastcity - Name of city from PW Forecast header
//
// The following variables exist for $i=0 to $i= number of forecast periods minus 1
// a loop of for ($i=0;$i<count($PWforecastday);$i++) { ... } will loop over the available
// values.
//
// $PWforecastday[$i] - period of forecast
// $PWforecasttext[$i] - text of forecast
// $PWforecasttemp[$i] - Temperature with text and formatting
// $PWforecastpop[$i] - Number - Probabability of Precipitation ('',10,20, ... ,100)
// $PWforecasticon[$i] - base name of icon graphic to use
// $PWforecastcond[$i] - Short legend for forecast icon
// $PWforecasticons[$i] - Full icon with Period, <img> and Short legend.
// $PWforecastwarnings = styled text with hotlinks to advisories/warnings
// $PWcurrentConditions = table with current conds at point close to lat/long selected
//
// Settings ---------------------------------------------------------------
// REQUIRED: a Pirateweather.net API KEY.. sign up at https://pirateweather.net
$PWAPIkey = 'specify-for-standalone-use-here'; // use this only for standalone / non-template use
// NOTE: if using the Saratoga template, add to Settings.php a line with:
// $SITE['PWAPIkey'] = 'your-api-key-here';
// and that will enable the script to operate correctly in your template
//
$iconDir ='./forecast/images/'; // directory for carterlake icons './forecast/images/'
$iconType = '.jpg'; // default type='.jpg'
// use '.gif' for animated icons fromhttp://www.meteotreviglio.com/
//
// The forecast(s) .. make sure the first entry is the default forecast location.
// The contents will be replaced by $SITE['PWforecasts'] if specified in your Settings.php
$PWforecasts = array(
// Location|lat,long (separated by | characters)
'Saratoga, CA, USA|37.27465,-122.02295',
'Auckland, NZ|-36.910,174.771', // Awhitu, Waiuku New Zealand
'Assen, NL|53.02277,6.59037',
'Blankenburg, DE|51.8089941,10.9080649',
'Cheyenne, WY, USA|41.144259,-104.83497',
'Carcassonne, FR|43.2077801,2.2790407',
'Braniewo, PL|54.3793635,19.7853585',
'Omaha, NE, USA|41.19043,-96.13114',
'Johanngeorgenstadt, DE|50.439339,12.706085',
'Athens, GR|37.97830,23.715363',
'Haifa, IL|32.7996029,34.9467358',
);
//
$maxWidth = '640px'; // max width of tables (could be '100%')
$maxIcons = 10; // max number of icons to display
$maxForecasts = 14; // max number of Text forecast periods to display
$maxForecastLegendWords = 4; // more words in forecast legend than this number will use our forecast words
$numIconsInFoldedRow = 8; // if words cause overflow of $maxWidth pixels, then put this num of icons in rows
$autoSetTemplate = true; // =true set icons based on wide/narrow template design
$cacheFileDir = './'; // default cache file directory
$cacheName = "PW-forecast-json.txt"; // locally cached page from PW
$refetchSeconds = 3600; // cache lifetime (3600sec = 60 minutes)
//
// Units:
// si: SI units (C,m/s,hPa,mm,km)
// ca: same as si, except that windSpeed and windGust are in kilometers per hour
// uk2: same as si, except that nearestStormDistance and visibility are in miles, and windSpeed and windGust in miles per hour
// us: Imperial units (F,mph,inHg,in,miles)
//
$showUnitsAs = 'ca'; // ='us' for imperial, , ='si' for metric, ='ca' for canada, ='uk2' for UK
//
$charsetOutput = 'ISO-8859-1'; // default character encoding of output
//$charsetOutput = 'UTF-8'; // for standalone use if desired
$lang = 'en'; // default language
$foldIconRow = false; // =true to display icons in rows of 5 if long texts are found
$timeFormat = 'Y-m-d H:i T'; // default time display format
$showConditions = true; // set to true to show current conditions box
// ---- end of settings ---------------------------------------------------
// overrides from Settings.php if available
global $SITE;
if (isset($SITE['PWforecasts'])) {$PWforecasts = $SITE['PWforecasts']; }
if (isset($SITE['PWAPIkey'])) {$PWAPIkey = $SITE['PWAPIkey']; } // new V3.00
if (isset($SITE['PWshowUnitsAs'])) { $showUnitsAs = $SITE['PWshowUnitsAs']; }
if (isset($SITE['fcsticonsdir'])) {$iconDir = $SITE['fcsticonsdir'];}
if (isset($SITE['fcsticonstype'])) {$iconType = $SITE['fcsticonstype'];}
if (isset($SITE['xlateCOP'])) {$xlateCOP = $SITE['xlateCOP'];}
if (isset($LANGLOOKUP['Chance of precipitation'])) {
$xlateCOP = $LANGLOOKUP['Chance of precipitation'];
}
if (isset($SITE['charset'])) {$charsetOutput = strtoupper($SITE['charset']); }
if (isset($SITE['lang'])) {$lang = $SITE['lang'];}
if (isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; }
if (isset($SITE['foldIconRow'])) {$foldIconRow = $SITE['foldIconRow']; }
if (isset($SITE['RTL-LANG'])) {$RTLlang = $SITE['RTL-LANG']; }
if (isset($SITE['timeFormat'])) {$timeFormat = $SITE['timeFormat']; }
if (isset($SITE['PWshowConditions'])) {$showConditions = $SITE['PWshowConditions'];} // new V1.05
// end of overrides from Settings.php
//
// -------------------begin code ------------------------------------------
$RTLlang = ',he,jp,cn,'; // languages that use right-to-left order
if (isset($_REQUEST['sce']) && strtolower($_REQUEST['sce']) == 'view' ) {
//--self downloader --
$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");
header("Accept-Ranges: bytes");
header("Content-Length: $download_size");
header('Connection: close');
readfile($filenameReal);
exit;
}
$Status = "<!-- $Version on PHP ".phpversion()." -->\n";
$PWcurrentConditions = ''; // HTML for table of current conditions
//------------------------------------------------
if(preg_match('|specify|i',$PWAPIkey)) {
print "<p>Note: the PW-forecast.php script requires an API key from Pirateweather.net to operate.<br/>";
print "Visit <a href=\"https://pirateweather.net/\">pirateweather.net</a> to ";
print "register for an API key.</p>\n";
if( isset($SITE['fcsturlPW']) ) {
print "<p>Insert in Settings.php an entry for:<br/><br/>\n";
print "\$SITE['PWAPIkey'] = '<i>your-key-here</i>';<br/><br/>\n";
print "replacing <i>your-key-here</i> with your PW API key.</p>\n";
}
return;
}
$NWSiconlist = array(
// darksky.net ICON definitions
'clear-day' => 'skc.jpg',
'clear-night' => 'nskc.jpg',
'rain' => 'ra.jpg',
'snow' => 'sn.jpg',
'sleet' => 'fzra.jpg',
'wind' => 'wind.jpg',
'fog' => 'fg.jpg',
'cloudy' => 'ovc.jpg',
'partly-cloudy-day' => 'sct.jpg',
'partly-cloudy-night' => 'nsct.jpg',
'hail' => 'ip.jpg',
'thunderstorm' => 'tsra.jpg',
'tornado' => 'tor.jpg'
);
//
$windUnits = array(
'us' => 'mph',
'ca' => 'km/h',
'si' => 'm/s',
'uk2' => 'mph'
);
$UnitsTab = array(
'si' => array('T'=>'°C','W'=>'m/s','P'=>'hPa','R'=>'mm','D'=>'km'),
'ca' => array('T'=>'°C','W'=>'km/s','P'=>'hPa','R'=>'mm','D'=>'km'),
'uk2' => array('T'=>'°C','W'=>'mph','P'=>'mb','R'=>'mm','D'=>'mi'),
'us' => array('T'=>'°F','W'=>'mph','P'=>'inHg','R'=>'in','D'=>'mi'),
);
if(isset($UnitsTab[$showUnitsAs])) {
$Units = $UnitsTab[$showUnitsAs];
} else {
$Units = $UnitsTab['si'];
}
if(!function_exists('langtransstr')) {
// shim function if not running in template set
function langtransstr($input) { return($input); }
}
if(!function_exists('json_last_error')) {
// shim function if not running PHP 5.3+
function json_last_error() { return('- N/A'); }
$Status .= "<!-- php V".phpversion()." json_last_error() stub defined -->\n";
if(!defined('JSON_ERROR_NONE')) { define('JSON_ERROR_NONE',0); }
if(!defined('JSON_ERROR_DEPTH')) { define('JSON_ERROR_DEPTH',1); }
if(!defined('JSON_ERROR_STATE_MISMATCH')) { define('JSON_ERROR_STATE_MISMATCH',2); }
if(!defined('JSON_ERROR_CTRL_CHAR')) { define('JSON_ERROR_CTRL_CHAR',3); }
if(!defined('JSON_ERROR_SYNTAX')) { define('JSON_ERROR_SYNTAX',4); }
if(!defined('JSON_ERROR_UTF8')) { define('JSON_ERROR_UTF8',5); }
}
PW_loadLangDefaults (); // set up the language defaults
$PWLANG = 'en'; // Default to English for API
$lang = strtolower($lang);
if( isset($PWlanguages[$lang]) ) { // if $lang is specified, use it
$SITE['lang'] = $lang;
$PWLANG = $PWlanguages[$lang];
$charsetOutput = (isset($PWlangCharsets[$lang]))?$PWlangCharsets[$lang]:$charsetOutput;
}
if(isset($_GET['lang']) and isset($PWlanguages[strtolower($_GET['lang'])]) ) { // template override
$lang = strtolower($_GET['lang']);
$SITE['lang'] = $lang;
$PWLANG = $PWlanguages[$lang];
$charsetOutput = (isset($PWlangCharsets[$lang]))?$PWlangCharsets[$lang]:$charsetOutput;
}
$doRTL = (strpos($RTLlang,$lang) !== false)?true:false; // format RTL language in Right-to-left in output
if(isset($SITE['copyr']) and $doRTL) {
// running in a Saratoga template. Turn off $doRTL
$Status .= "<!-- running in Saratoga Template. doRTL set to false as template handles formatting -->\n";
$doRTL = false;
}
if(isset($doShowConditions)) {$showConditions = $doShowConditions;}
if($doRTL) {$RTLopt = ' style="direction: rtl;"'; } else {$RTLopt = '';};
// get the selected forecast location code
$haveIndex = '0';
if (!empty($_GET['z']) && preg_match("/^[0-9]+$/i", htmlspecialchars($_GET['z']))) {
$haveIndex = htmlspecialchars(strip_tags($_GET['z'])); // valid zone syntax from input
}
if(!isset($PWforecasts[0])) {
// print "<!-- making NWSforecasts array default -->\n";
$PWforecasts = array("Saratoga|37.27465,-122.02295"); // create default entry
}
if(isset($useUTF8) and $useUTF8) {
$charsetOutput = 'UTF-8';
$Status .= "<!-- useUTF8 enabled -->\n";
}
if($charsetOutput == 'UTF-8') {
foreach ($PWlangCharsets as $l => $cs) {
$PWlangCharsets[$l] = 'UTF-8';
}
$Status .= "<!-- charsetOutput UTF-8 selected for all languages. -->\n";
$Status .= "<!-- PWlangCharsets\n".var_export($PWlangCharsets,true)." \n-->\n";
}
if(stripos($timeFormat,'g') !== false or $showUnitsAs == 'us') {
$showAMPMtime = true;
$Status .= "<!-- timeFormat='$timeFormat'. timeline hours displayed as am/pm -->\n";
} else {
$showAMPMtime = false;
$Status .= "<!-- timeFormat='$timeFormat'. timeline hours displayed as 24hr time -->\n";
}
if(!headers_sent()) {
header('Content-type: text/html,charset='.$charsetOutput);
}
// print "<!-- NWSforecasts\n".print_r($PWforecasts,true). " -->\n";
// Set the default zone. The first entry in the $SITE['NWSforecasts'] array.
list($Nl,$Nn) = explode('|',$PWforecasts[0].'|||');
$FCSTlocation = $Nl;
$PW_LATLONG = $Nn;
if(!isset($PWforecasts[$haveIndex])) {
$haveIndex = 0;
}
// locations added to the drop down menu and set selected zone values
$dDownMenu = '';
for ($m=0;$m<count($PWforecasts);$m++) { // for each locations
list($Nlocation,$Nname) = explode('|',$PWforecasts[$m].'|||');
$seltext = '';
if($haveIndex == $m) {
$FCSTlocation = $Nlocation;
$PW_LATLONG = $Nname;
$seltext = ' selected="selected" ';
}
$dDownMenu .= " <option value=\"$m\"$seltext>".langtransstr($Nlocation)."</option>\n";
}
// build the drop down menu
$ddMenu = '';
// create menu if at least two locations are listed in the array
if (isset($PWforecasts[0]) and isset($PWforecasts[1])) {
$ddMenu .= '<tr align="center">
<td style="font-size: 14px; font-family: Arial, Helvetica, sans-serif">
<script type="text/javascript">
<!--
function menu_goto( menuform ){
selecteditem = menuform.logfile.selectedIndex ;
logfile = menuform.logfile.options[ selecteditem ].value ;
if (logfile.length != 0) {
location.href = logfile ;
}
}
//-->
</script>
<form action="" method="get">
<p><select name="z" onchange="this.form.submit()"'.$RTLopt.'>
<option value=""> - '.langtransstr('Select Forecast').' - </option>
' . $dDownMenu .
$ddMenu . ' </select></p>
<div><noscript><pre><input name="submit" type="submit" value="'.langtransstr('Get Forecast').'" /></pre></noscript></div>
</form>
</td>
</tr>
';
}
$Force = false;
if (isset($_REQUEST['force']) and $_REQUEST['force']=="1" ) {
$Force = true;
}
$doDebug = false;
if (isset($_REQUEST['debug']) and strtolower($_REQUEST['debug'])=='y' ) {
$doDebug = true;
}
$showTempsAs = ($showUnitsAs == 'us')? 'F':'C';
$Status .= "<!-- temps in $showTempsAs -->\n";
$fileName = "https://api.pirateweather.net/forecast/$PWAPIkey/$PW_LATLONG" .
"?exclude=minutely&extend=hourly&units=$showUnitsAs";
if ($doDebug) {
$Status .= "<!-- PW URL: $fileName -->\n";
}
if ($autoSetTemplate and isset($_SESSION['CSSwidescreen'])) {
if($_SESSION['CSSwidescreen'] == true) {
$maxWidth = '900px';
$maxIcons = 8;
$maxForecasts = 8;
$numIconsInFoldedRow = 7;
$Status .= "<!-- autoSetTemplate using ".$SITE['CSSwideOrNarrowDefault']." aspect. -->\n";
}
if($_SESSION['CSSwidescreen'] == false) {
$maxWidth = '640px';
$maxIcons = 8;
$maxForecasts = 8;
$numIconsInFoldedRow = 7;
$Status .= "<!-- autoSetTemplate using ".$SITE['CSSwideOrNarrowDefault']." aspect. -->\n";
}
}
$cacheName = $cacheFileDir . $cacheName;
$cacheName = preg_replace('|\.txt|is',"-$haveIndex-$showUnitsAs.txt",$cacheName); // unique cache per units used.. all are in English
$APIfileName = $fileName;
if($showConditions) {
$refetchSeconds = 15*60; // shorter refresh time so conditions will be 'current'
}
if (! $Force and file_exists($cacheName) and filemtime($cacheName) + $refetchSeconds > time()) {
$html = implode('', file($cacheName));
$Status .= "<!-- loading from $cacheName (" . strlen($html) . " bytes) -->\n";
} else {
$Status .= "<!-- loading from $APIfileName. -->\n";
$html = PW_fetchUrlWithoutHanging($APIfileName,false);
$RC = '';
if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$html,$matches)) {
$RC = trim($matches[1]);
}
$Status .= "<!-- RC=$RC, bytes=" . strlen($html) . " -->\n";
if (preg_match('|30\d |',$RC)) { // handle possible blocked redirect
preg_match('|Location: (\S+)|is',$html,$matches);
if(isset($matches[1])) {
$sURL = $matches[1];
if(preg_match('|opendns.com|i',$sURL)) {
$Status .= "<!-- NOT following to $sURL --->\n";
} else {
$Status .= "<!-- following to $sURL --->\n";
$html = PW_fetchUrlWithoutHanging($sURL,false);
$RC = '';
if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$html,$matches)) {
$RC = trim($matches[1]);
}
$Status .= "<!-- RC=$RC, bytes=" . strlen($html) . " -->\n";
}
}
}
if(preg_match('!temperature!is',$html)) {
$fp = fopen($cacheName, "w");
if (!$fp) {
$Status .= "<!-- unable to open $cacheName for writing. -->\n";
} else {
$write = fputs($fp, $html);
fclose($fp);
$Status .= "<!-- saved cache to $cacheName (". strlen($html) . " bytes) -->\n";
}
} else {
$Status .= "<!-- bad return from $APIfileName\n".var_export($html,true)."\n -->\n";
if(file_exists($cacheName) and filesize($cacheName) > 3000) {
$html = implode('', file($cacheName));
$Status .= "<!-- reloaded stale cache $cacheName temporarily -->\n";
} else {
$Status .= "<!-- cache $cacheName missing or contains invalid contents -->\n";
print $Status;
print "<p>Sorry.. the Pirateweather forecast is not available.</p>\n";
return;
}
}
}
$charsetInput = 'UTF-8';
$doIconv = ($charsetInput == $charsetOutput)?false:true; // only do iconv() if sets are different
if($charsetOutput == 'UTF-8') {
$doIconv = false;
}
$Status .= "<!-- using charsetInput='$charsetInput' charsetOutput='$charsetOutput' doIconv='$doIconv' doRTL='$doRTL' -->\n";
$tranTab = PW_loadTranslate($lang,$charsetOutput);
$i = strpos($html,"\r\n\r\n");
$headers = substr($html,0,$i-1);
$content = substr($html,$i+4);
// process the file .. select out the 7-day forecast part of the page
$UnSupported = false;
// --------------------------------------------------------------------------------------------------
$Status .= "<!-- processing JSON entries for forecast -->\n";
$i = strpos($html,"\r\n\r\n");
$headers = substr($html,0,$i-1);
$content = substr($html,$i+4);
$rawJSON = $content;
$Status .= "<!-- rawJSON size is ".strlen($rawJSON). " bytes -->\n";
$rawJSON = PW_prepareJSON($rawJSON);
$JSON = json_decode($rawJSON,true); // get as associative array
$Status .= PW_decode_JSON_error();
#if(isset($_GET['debug'])) {$Status .= "<!-- JSON\n".var_export($JSON,true)." -->\n";}
if(isset($JSON['daily']['data'][0]['time'])) { // got good JSON .. process it
$UnSupported = false;
$PWforecastcity = $FCSTlocation;
if($doIconv) {$PWforecastcity = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$PWforecastcity);}
if($doDebug) {
$Status .= "<!-- PWforecastcity='$PWforecastcity' -->\n";
}
//$PWtitle = langtransstr("Forecast");
$PWtitle = $tranTab['Pirateweather Forecast for:'];
if($doIconv) {$PWtitle = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$PWtitle);}
if($doDebug) {
$Status .= "<!-- PWtitle='$PWtitle' -->\n";
}
/*
[daily] => Array
(
[summary] => No precipitation throughout the week, with high temperatures bottoming out at 19°C on Thursday.
[icon] => clear-day
[data] => Array
(
[0] => Array
(
[time] => 1526886000
[summary] => Partly cloudy until afternoon.
[icon] => partly-cloudy-day
[sunriseTime] => 1526907369
[sunsetTime] => 1526958974
[moonPhase] => 0.23
[precipIntensity] => 0.0025
[precipIntensityMax] => 0.0432
[precipIntensityMaxTime] => 1526968800
[precipProbability] => 0.2
[precipType] => rain
[temperatureHigh] => 18.87
[temperatureHighTime] => 1526936400
[temperatureLow] => 10.02
[temperatureLowTime] => 1526997600
[apparentTemperatureHigh] => 18.87
[apparentTemperatureHighTime] => 1526936400
[apparentTemperatureLow] => 10.02
[apparentTemperatureLowTime] => 1526997600
[dewPoint] => 9.38
[humidity] => 0.73
[pressure] => 1011.77
[windSpeed] => 3.04
[windGust] => 22.6
[windGustTime] => 1526943600
[windBearing] => 250
[cloudCover] => 0.41
[uvIndex] => 8
[uvIndexTime] => 1526932800
[visibility] => 15.21
[ozone] => 374.58
[temperatureMin] => 11.11
[temperatureMinTime] => 1526907600
[temperatureMax] => 18.87
[temperatureMaxTime] => 1526936400
[apparentTemperatureMin] => 11.11
[apparentTemperatureMinTime] => 1526907600
[apparentTemperatureMax] => 18.87
[apparentTemperatureMaxTime] => 1526936400
)
*/
if(isset($JSON['timezone'])) {
date_default_timezone_set($JSON['timezone']);
$Status .= "<!-- using '".$JSON['timezone']."' for timezone -->\n";
}
if(isset($JSON['daily']['data'][0]['time'])) {
$PWupdated = $tranTab['Updated:'];
if($doIconv) {
$PWupdated = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$PWupdated). ' ';
}
if(isset($JSON['hourly']['data'][0]['time'])) {
$PWupdated .= date($timeFormat,$JSON['hourly']['data'][0]['time']);
} else {
$PWupdated .= date($timeFormat,$JSON['daily']['data'][0]['time']);
}
} else {
$PWupdated = '';
}
if($doDebug) {
$Status .= "\n<!-- JSON daily:data count=" . count( $JSON['daily']['data']) . "-->\n";
}
if(isset($windUnits[$showUnitsAs])) {
$windUnit = $windUnits[$showUnitsAs];
$Status .= "<!-- wind unit for '$showUnitsAs' set to '$windUnit' -->\n";
if(isset($tranTab[$windUnit])) {
$windUnit = $tranTab[$windUnit];
$Status .= "<!-- wind unit translation for '$showUnitsAs' set to '$windUnit' -->\n";
}
} else {
$windUnit = '';
}
$n = 0;
foreach ($JSON['daily']['data'] as $i => $FCpart) {
# process each daily entry
list($tDay,$tTime) = explode(" ",date('l H:i:s',$FCpart['time']));
if ($doDebug) {
$Status .= "<!-- period $n ='$tDay $tTime' -->\n";
}
$PWforecastdayname[$n] = $tDay;
if(isset($tranTab[$tDay])) {
$PWforecastday[$n] = $tranTab[$tDay];
} else {
$PWforecastday[$n] = $tDay;
}
if($doIconv) {
$PWforecastday[$n] = iconv("UTF-8",$charsetOutput.'//IGNORE',$PWforecastday[$n]);
}
$PWforecasttitles[$n] = $PWforecastday[$n];
if ($doDebug) {
$Status .= "<!-- PWforecastday[$n]='" . $PWforecastday[$n] . "' -->\n";
}
$PWforecastcloudcover[$n] = $FCpart['cloudCover'];
# extract the temperatures
$PWforecasttemp[$n] = "<span style=\"color: #ff0000;\">".PW_round($FCpart['temperatureHigh'],0)."°$showTempsAs</span>";
$PWforecasttemp[$n] .= "<br/><span style=\"color: #0000ff;\">".PW_round($FCpart['temperatureLow'],0)."°$showTempsAs</span>";
# extract the icon to use
$PWforecasticon[$n] = $FCpart['icon'];
if ($doDebug) {
$Status .= "<!-- PWforecasticon[$n]='" . $PWforecasticon[$n] . "' -->\n";
}
if(isset($FCpart['precipProbability'])) {
$PWforecastpop[$n] = round($FCpart['precipProbability'],1)*100;
} else {
$PWforecastpop[$n] = 0;
}
if ($doDebug) {
$Status .= "<!-- PWforecastpop[$n]='" . $PWforecastpop[$n] . "' -->\n";
}
if(isset($FCpart['precipType'])) {
$PWforecastpreciptype[$n] = $FCpart['precipType'];
} else {
$PWforecastpreciptype[$n] = '';
}
$PWforecasttext[$n] = // replace problematic characters in forecast text
str_replace(
array('<', '>', 'â','cm.','in.','.)'),
array('<','>','-', 'cm', 'in',')'),
trim($FCpart['summary']));
$tstr = $PWforecasttext[$n];
$PWforecasttext[$n] = isset($tranTab[$tstr])?$tranTab[$tstr].'.':$tstr.'.';
# Add info to the forecast text
if($PWforecastpop[$n] > 0) {
$tstr = '';
if(!empty($PWforecastpreciptype[$n])) {
$t = explode(',',$PWforecastpreciptype[$n].',');
foreach ($t as $k => $ptype) {
if(!empty($ptype)) {$tstr .= $tranTab[$ptype].',';}
}
if(strlen($tstr)>0) {
$tstr = '('.substr($tstr,0,strlen($tstr)-1) .') ';
}
}
$PWforecasttext[$n] .= " ".
$tranTab['Chance of precipitation']." $tstr".$PWforecastpop[$n]."%. ";
}
$PWforecasttext[$n] .= " ".$tranTab['High:']." ".PW_round($FCpart['temperatureHigh'],0)."°$showTempsAs. ";
$PWforecasttext[$n] .= " ".$tranTab['Low:']." ".PW_round($FCpart['temperatureLow'],0)."°$showTempsAs. ";
$tWdir = PW_WindDir(round($FCpart['windBearing'],0));
$PWforecasttext[$n] .= " ".$tranTab['Wind']." ".PW_WindDirTrans($tWdir);
$PWforecasttext[$n] .= " ".
round($FCpart['windSpeed'],0)."->".round($FCpart['windGust'],0) .
" $windUnit.";
if(isset($FCpart['uvIndex']) and $FCpart['uvIndex'] > 1) {
$PWforecasttext[$n] .= " ".$tranTab['UV index']." ".round($FCpart['uvIndex'],0).".";
}
if($doIconv) {
$PWforecasttext[$n] = iconv("UTF-8",$charsetOutput.'//IGNORE',$PWforecasttext[$n]);
}
if ($doDebug) {
$Status .= "<!-- PWforecasttext[$n]='" . $PWforecasttext[$n] . "' -->\n";
}
//$temp = explode('.',$PWforecasttext[$n]); // split as sentences (sort of).
$PWforecastcond[$n] = isset($tranTab[trim($FCpart['summary'])])?
$tranTab[trim($FCpart['summary'])]:trim($FCpart['summary']); // take first one as summary.
if($doIconv) {
$PWforecastcond[$n] = iconv("UTF-8",$charsetOutput.'//IGNORE',$PWforecastcond[$n]);
}
if ($doDebug) {
$Status .= "<!-- forecastcond[$n]='" . $PWforecastcond[$n] . "' -->\n";
}
$PWforecasticons[$n] = $PWforecastday[$n] . "<br/>" .
PW_img_replace(
$PWforecasticon[$n],$PWforecastcond[$n],$PWforecastpop[$n],$PWforecastcloudcover[$n]) .
"<br/>" .
$PWforecastcond[$n];
$n++;
} // end of process text forecasts
if(isset($JSON['flags']['sources'])) {
$dsSources = PW_sources($JSON['flags']['sources']);
// $Status .= "<!-- sources\n".$dsSources." -->\n";
}
// process alerts if any are available
$PWforecastwarnings = '';
if (isset($JSON['alerts']) and is_array($JSON['alerts']) and count($JSON['alerts']) > 0) {
$Status.= "<!-- preparing " . count($JSON['alerts']) . " warning links -->\n";
foreach($JSON['alerts'] as $i => $ALERT) {
$expireUTC = $ALERT['expires'];
$expires = date($timeFormat,$ALERT['expires']);
$Status.= "<!-- alert expires $expires (" . $ALERT['expires'] . ") -->\n";
$regions = '';
$description = str_replace(' * ',"\n* ",$ALERT['description']);
if(is_array($ALERT['regions'])) {
foreach ($ALERT['regions'] as $i => $reg) {
$regions .= $reg . ', ';
}
$regions = substr($regions,0,strlen($regions)-2);
}
if (time() < $expireUTC) {
$PWforecastwarnings .= '<a href="' . $ALERT['uri'] . '"' . ' title="' . $ALERT['title'] . " expires $expires\n$regions\n---\n" . $description . '" target="_blank">' . '<strong><span style="color: red">' . $ALERT['title'] . "</span></strong></a><br/>\n";
}
else {
$Status.= "<!-- alert " . $ALERT['title'] . " " . " expired - " . $ALERT['expires'] . " -->\n";
}
}
}
else {
$Status.= "<!-- no current hazard alerts found-->\n";
}
// make the Current conditions table from $currently array
$currently = $JSON['currently'];
/*
"currently": {
"time": 1543970527,
"summary": "Overcast",
"icon": "cloudy",
"nearestStormDistance": 0,
"precipIntensity": 0.127,
"precipIntensityError": 0.1016,
"precipProbability": 0.21,
"precipType": "rain",
"temperature": 12.35,
"apparentTemperature": 12.35,
"dewPoint": 5.48,
"humidity": 0.63,
"pressure": 1013.59,
"windSpeed": 5.89,
"windGust": 15.61,
"windBearing": 102,
"cloudCover": 1,
"uvIndex": 0,
"visibility": 14.89,
"ozone": 311.96
},
"daily": {
"summary": "Light rain today through Monday, with high temperatures rising to 16°C on Thursday.",
"icon": "rain",
*/
$nCols = 3; // number of columns in the conditions table
if (isset($currently['time']) ) { // only generate if we have the data
if (isset($currently['icon']) and ! $currently['icon'] ) { $nCols = 2; };
$PWcurrentConditions = '<table class="PWforecast" cellpadding="3" cellspacing="3" style="border: 1px solid #909090;">' . "\n";
$PWcurrentConditions .= '
<tr><td colspan="' . $nCols . '" align="center" '.$RTLopt.'><small>' .
$tranTab['Currently'].': '. date($timeFormat,$currently['time']) . "<br/>\n";
# removed V2.02 - nearest-station is always zero
# $t = $tranTab['Weather conditions at 999 from forecast point.'];
# $t = str_replace('999',round($JSON['flags']['nearest-station'],1).' '.$Units['D'],$t);
$PWcurrentConditions .=
'</small></td></tr>' . "\n<tr$RTLopt>\n";
if (isset($currently['icon'])) {
$tCond = isset($tranTab[$currently['summary']])?$tranTab[$currently['summary']]:$currently['summary'];
$PWcurrentConditions .= '
<td align="center" valign="middle">' .
PW_img_replace(
$currently['icon'],
$tCond,
round($currently['precipProbability'],1)*100,
$currently['cloudCover']) . "<br/>\n" .
$tCond;
$PWcurrentConditions .= ' </td>
';
} // end of icon
$PWcurrentConditions .= "
<td valign=\"middle\">\n";
if (isset($currently['temperature'])) {
$PWcurrentConditions .= $tranTab['Temperature'].": <b>".
PW_round($currently['temperature'],0) . $Units['T'] . "</b><br/>\n";
}
if (isset($currently['windchill'])) {
$PWcurrentConditions .= $tranTab['Wind chill'].": <b>".
PW_round($currently['windchill'],0) . $Units['T']. "</b><br/>\n";
}
if (isset($currently['heatindex'])) {
$PWcurrentConditions .= $tranTab['Heat index'].": <b>" .
PW_round($currently['heatindex']) . $Units['T']. "</b><br/>\n";
}
if (isset($currently['windSpeed'])) {
$tWdir = PW_WindDir(round($currently['windBearing'],0));
$PWcurrentConditions .= $tranTab['Wind'].": <b>".PW_WindDirTrans($tWdir);
$PWcurrentConditions .= " ".round($currently['windSpeed'],0).
"->".round($currently['windGust'],0) . " $windUnit." .
"</b><br/>\n";
}
if (isset($currently['humidity'])) {
$PWcurrentConditions .= $tranTab['Humidity'].": <b>".
round($currently['humidity'],1)*100 . "%</b><br/>\n";
}
if (isset($currently['dewPoint'])) {
$PWcurrentConditions .= $tranTab['Dew Point'].": <b>".
PW_round($currently['dewPoint'],0) . $Units['T'] . "</b><br/>\n";
}
$PWcurrentConditions .= $tranTab['Barometer'].": <b>".
PW_conv_baro($currently['pressure']) . " " . $Units['P'] . "</b><br/>\n";
if (isset($currently['visibility'])) {
$PWcurrentConditions .= $tranTab['Visibility'].": <b>".
round($currently['visibility'],1) . " " . $Units['D']. "</b>\n" ;
}
if (isset($currently['uvIndex'])) {
$PWcurrentConditions .= '<br/>'.$tranTab['UV index'].": <b>".
round($currently['uvIndex'],0) . "</b>\n" ;
}
$PWcurrentConditions .= ' </td>
';
$PWcurrentConditions .= ' <td valign="middle">
';
$tFMT = ($showUnitsAs == 'us')?'g:ia':'H:i';
if(isset($JSON['daily']['data'][0]['sunriseTime']) and
isset($JSON['daily']['data'][0]['sunsetTime']) ) {
$PWcurrentConditions .=
$tranTab['Sunrise'].': <b>'.
date($tFMT,$JSON['daily']['data'][0]['sunriseTime']) .
"</b><br/>\n" .
$tranTab['Sunset'].': <b>'.
date($tFMT,$JSON['daily']['data'][0]['sunsetTime']) .
"</b><br/>\n" ;
}
$PWcurrentConditions .= '
</td>
</tr>
';
if(isset($JSON['daily']['summary'])) {
$tCond = isset($tranTab[$JSON['daily']['summary']])?$tranTab[$JSON['daily']['summary']]:$JSON['daily']['summary'];
if($doRTL) {
$PWcurrentConditions .= '
<tr><td colspan="' . $nCols . '" align="center" style="width: 350px;direction: rtl;"><small>' .
$tCond .
'</small></td>
</tr>
'; } else {
$PWcurrentConditions .= '
<tr><td colspan="' . $nCols . '" align="center" style="width: 350px;"><small>' .
$tCond .
'</small></td>
</tr>
';
}
}
$PWcurrentConditions .= '
</table>
';
if($doIconv) {
$PWcurrentConditions =
iconv('UTF-8',$charsetOutput.'//TRANSLIT',$PWcurrentConditions);
}
} // end of if isset($currently['cityobserved'])
// end of current conditions mods
$timelineColors = array(
// timeline Colors to use for each condition
"Clear" => "#eeeef5",
"Partly Cloudy" => "#d5dae2",
"Cloudy"=> "#b6bfcb",
"Rain" => "#4a80c7",
"Light Rain" => "#80a5d6",
"Drizzle" => "#a4b8d4",
"Snow" => "#8c82ce",
"Light Snow" => "#aba4db",
"Flurries"=> "#b7b2db",
"Sleet"=> "#6264a7",
"Fog" => "#d5dae2",
"Wind" => "#ffdead",
"Windy" => "#ffdead",
);
if(isset($JSON['hourly']['data'][0]['time'])) { // process Hourly forecast data
/*
"hourly": {
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-night",
"data": [{
"time": 1548018000,
"summary": "Mostly Cloudy",
"icon": "partly-cloudy-day",
"precipIntensity": 0.1422,
"precipProbability": 0.29,
"precipType": "rain",
"temperature": 14.91,
"apparentTemperature": 14.91,
"dewPoint": 11.49,
"humidity": 0.8,
"pressure": 1017.89,
"windSpeed": 10.8,
"windGust": 24.54,
"windBearing": 226,
"cloudCover": 0.88,
"uvIndex": 2,
"visibility": 14.11,
"ozone": 289.95
}, {
*/
$newJSON = array(); // storage for the merry-timeline JSON
/*
{
"color": "#b7b2db",
"text": "Flurries",
"annotation": "0°",
"time": 1672257600
},
*/
$tempUOM = str_replace('°'," ",$UnitsTab[$showUnitsAs]['T']);
foreach($JSON['hourly']['data'] as $i => $H) {
$dayname = date('l',$H['time']);
if(isset($tranTab[$dayname])) {$dayname = $tranTab[$dayname];
if($doIconv) {iconv($charsetInput,$charsetOutput.'//TRANSLIT',$dayname); }
$dayname .= ', '.date('d',$H['time']);
$tColor = isset($timelineColors[$H['summary']])?$timelineColors[$H['summary']]:'#fefefe';
$text = isset($tranTab[$H['summary']])?$tranTab[$H['summary']]:$H['summary'];
if($doIconv) {iconv($charsetInput,$charsetOutput.'//TRANSLIT',$text);}
$newJSON[$dayname][] = array(
'color' => $tColor,
'text' => $text,
'annotation' => round($H['temperature'],0).$tempUOM,
'time' => $H['time']
);
} // end each hourly forecast parsing
} // end process hourly forecast data
$utfdata = json_encode($newJSON,JSON_UNESCAPED_UNICODE);
$merrytimelineJSON = ($doIconv)?iconv('UTF-8',$charsetOutput.'//TRANSLIT//IGNORE',$utfdata):$utfdata;
$hourlyData = "<script type=\"text/javascript\">\n";
$hourlyData .= "var showAMPMtime = ";
$hourlyData .= ($showAMPMtime)?'true;':'false;';
$hourlyData .= " // =true use AMPM, =false use 24h time on timeline\n";
$hourlyData .= "// hourly data \n// <![CDATA[\n";
$hourlyData .= "var weatherData = ".$merrytimelineJSON.";\n// ]]>\n";
$hourlyData .= "</script>\n";
if(isset($_GET['debug'])) {
$hourlyData .= "<!-- newJSON array\n".var_export($newJSON,true)." -->\n";
}
if(isset($_GET['snapshot'])) {
file_put_contents('./raw-weatherData-json.txt',$merrytimelineJSON);
file_put_contents('./raw-newJSON-array.txt',var_export($newJSON,true));
$Status .= "<!-- snapshots taken -->\n";
}
/* old version
if(isset($JSON['hourly']['data'][0]['time'])) { // process Hourly forecast data
/*
"hourly": {
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-night",
"data": [{
"time": 1548018000,
"summary": "Mostly Cloudy",
"icon": "partly-cloudy-day",
"precipIntensity": 0.1422,
"precipProbability": 0.29,
"precipType": "rain",
"temperature": 14.91,
"apparentTemperature": 14.91,
"dewPoint": 11.49,
"humidity": 0.8,
"pressure": 1017.89,
"windSpeed": 10.8,
"windGust": 24.54,