-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathec-forecast.php
More file actions
2022 lines (1840 loc) · 73.6 KB
/
Copy pathec-forecast.php
File metadata and controls
2022 lines (1840 loc) · 73.6 KB
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
// PHP script by Ken True, [email protected]
// ec-forecast.php version 1.00 - 10-Aug-2006
// Version 1.01 - 14-Dec-2006 - fixed script to handle changes in EC website
// Version 1.02 - 14-Dec-2006 - fixed problems with include mode/no printing.
// Version 1.03 - 14-Mar-2007 - fixed to handle changes to EC website
// Version 1.04 - 16-May-2007 - fixed to handle changes to EC website
// Version 1.05 - 15-Jun-2007 - handle printable/regular EC URL + table, debugging improvements
// Version 1.06 - 27-Jun-2007 - added parsing/printing for alerts/watches/warnings $alertstring
// Version 1.07 - 06-Aug-2007 - corrected php delim at top of file (missing php)
// Version 1.08 - 14-Dec-2007 - added optional current conditions report table $currentConditions
// Version 2.00 - 24-Jan-2008 - major rewrite to handle many changes to EC forecast website + new icons
// Version 2.01 - 26-Jan-2008 - added 'Air Quality Health Index' to optional conditions display
// Version 2.02 - 26-Feb-2008 - added support for Carterlake/WD/PHP template settings.
// Version 2.03 - 01-Mar-2008 - fixed to handle changes to EC website for conditions
// Version 2.04 - 19-Mar-2008 - fixed to handle changes to EC website for forecast
// Version 2.05 - 19-Mar-2008 - corrected extraction of Update date from EC website
// Version 2.06 - 05-Jun-2008 - fixed to handle changes to EC website for historical conditions
// Version 2.07 - 21-Dec-2008 - added printing/formatting for historical conditions
// Version 2.08 - 10-Mar-2009 - fixed to handle change to EC website for abnormal temperature trend indicator
// Version 2.09 - 09-Nov-2009 - fixed missing-space in warning titles problem
// Version 2.10 - 10-Nov-2009 - fixed to handle changes to EC website for normals conditions display
// Version 2.11 - 26-May-2010 - fixed to handle changes to EC website for humidex/wind-chill
// Version 2.12 - 19-Feb-2011 - added formatting to EC watch/warning/ended message alerts
// Version 2.13 - 30-May-2011 - fixed handling of $SITE['fcsticonsdirEC'] when used with template
// Version 2.14 - 16-Apr-2013 - fixes for changes in EC website structure
// Version 2.15 - 17-Apr-2013 - fixes for $title display with new EC website structure
// Version 2.16 - 12-May-2013 - added settings to display days of week w/o day month for icons and detail area; icon type selection for .gif/.png; added debugging code for EC website fetch; added multi-forecast capability
// Version 2.17 - 15-May-2013 - fixes for changes in EC website structure
// Version 3.00 - 17-Oct-2014 - redesign for major changes in EC website structure
// Version 3.01 - 29-Oct-2014 - fix for 'Normals' extract and text forecast
// Version 3.02 - 29-Apr-2015 - fixes for changes in EC website structure+new temps processing
// Version 3.03 - 01-Dec-2015 - fixes for current conditions based on EC website changes
// Version 3.04 - 14-Dec-2015 - fixes for changes in EC website structure (chunked+gzipped response)
// Version 3.05 - 16-Dec-2015 - fixes for changes in temperature forecast wording+extraction
// Version 4.00 - 22-Oct-2016 - major redesign for EC website changes+curl fetch
// Version 4.01 - 27-Oct-2016 - fix for conditions icon extract, yesterday data, use curl fetch for URL
// Version 4.02 - 22-Feb-2017 - force HTTPS to EC website, improved error handling
// Version 4.03 - 31-Aug-2017 - fixes for changes in EC website structure
// Version 5.00 - 27-Sep-2017 - major redesign to use EC XML forecast data instead of website scraping
// Version 5.01 - 07-Nov-2017 - added windchill display to conditions box
// Version 5.02 - 20-Nov-2017 - added wind-gust display to conditions box and hourly display, fix no conds icon issue
// Version 5.03 - 16-Oct-2019 - change XML access URL to https on EC site
// Version 5.04 - 27-Dec-2022 - fixes for PHP 8.2
// Version 5.05 - 09-Feb-2023 - fixes for .png icons and PHP 8.2
// Version 5.06 - 18-May-2023 - added 'advisory' alert display same as 'statement' type
// Version 5.07 - 02-Jul-2024 - fixes for changes in EC XML returns w/o almanac section
// Version 6.00 - 26-Oct-2024 - rewrite to use new EC JSON return instead of XML citypage
// Version 6.01 - 26-Oct-2024 - fix for hourly display icons when using .png icons
// Version 6.02 - 28-Oct-2024 - fixed alert display when there are highway alerts
// Version 7.00 - 18-Dec-2025 - major update to support color-coded alerts from EC
// Version 7.01 - 21-May-2026 - fixes for PHP 8.5
//
$Version = "V7.01 - 21-May-2026";
// error_reporting(E_ALL); // uncomment for checking errata in code
//---------------------------------------------------------------------------------------------
// NOTE: as of V5.00, the separate file 'ec-forecast-lookup.txt' is REQUIRED to be in the
// same directory as this script. It provides the lookup for EC page-id to XML file id.
//---------------------------------------------------------------------------------------------
// NOTE: Version 6.00+ allows use of old and new format URLS for ECURL entries in the script
//
// OLD: $ECURL = 'https://weather.gc.ca/city/pages/on-77_metric_e.html'; # Old format
// NEW $ECURL = 'https://weather.gc.ca/en/location/index.html?coords=43.258,-79.869'; # New Format
//
//---------------------------------------------------------------------------------------------
//*
// Settings:
// --------- start of settings ----------
// you need to set the $ECURL to the printable forecast for your area
//
// Go to https://weather.gc.ca/ and select your language English or French
//
// Search for your location by name.
//
// Copy the URL from the browser address bar, and paste it into $ECURL below.
// The URL may be from either the weather.gc.ca or meteo.gc.ca sites.
// Examples:
// English: https://weather.gc.ca/en/location/index.html?coords=43.258,-79.869 or
// French: https://meteo.gc.ca/fr/location/index.html?coords=43.258,-79.869
//
//$ECURL = 'https://weather.gc.ca/city/pages/on-77_metric_e.html'; # Old format
$ECURL = 'https://weather.gc.ca/en/location/index.html?coords=43.258,-79.869'; # New Format
//
$defaultLang = 'en'; // set to 'fr' for french default language
// // set to 'en' for english default language
//
$printIt = true; // set to false if you want to manually print on your page
//
$showConditions = true; // set to true to show current conditions box
$showAlmanac = true; // set to true to show almanac box
$show24hour = true; // set to true to show the 24 hour forecast box
//
$imagedirEC = "ec-icons/";
//directory with your image icons WITH the trailing slash
//
$cacheName = 'ec-forecast.json'; // note: will be changed to include lat-long/language
$cacheFileDir = './'; // directory to store cache files (with trailing / )
//
$refetchSeconds = 600; // get new forecast from EC
// every 10 minutes (600 seconds)
//
//$LINKtarget = 'target="_blank"'; // to launch new link in new page
$LINKtarget = ''; // to launch new link in same page
//
$charsetOutput = 'ISO-8859-1'; // default character encoding of output
// new settings with V2.16 ------ all have Settings.php overrides available for template use
/* deprecated in V5.00+ .. data not in XML feeds
$doIconDayDate = false; // =false; Icon names = day of week. =true; icon names as Day dd Mon
$doDetailDayDate = false; // =false; for day name only, =true; detail day as name, nn mon.
*/
$iconTypeEC = '.gif'; // ='.gif' or ='.png' for ec-icons file type
// The optional multi-city forecast .. make sure the first entry is for the $ECURL location
// The contents will be replaced by $SITE['ECforecasts'] if specified in your Settings.php
//*
$ECforecasts = array(
// Location|forecast-URL (separated by | characters)
'St. Catharines, ON|https://weather.gc.ca/en/location/index.html?coords=43.160,-79.245', // St. Catharines, ON
'Hamilton, ON|https://weather.gc.ca/city/pages/on-77_metric_e.html',
'Hamilton, ON new|https://weather.gc.ca/en/location/index.html?coords=43.258,-79.869',
'Montréal, QC|https://meteo.gc.ca/city/pages/qc-147_metric_f.html',
'Montréal, QC new|https://meteo.gc.ca/fr/location/index.html?coords=45.529,-73.562',
'St. John\'s, NL new|https://meteo.gc.ca/fr/location/index.html?coords=47.558,-52.717',
'Victoria, BC new|https://weather.gc.ca/en/location/index.html?coords=48.433,-123.362',
'Vancouver, BC new|https://weather.gc.ca/en/location/index.html?coords=49.245,-123.115',
'Regina, SK|https://weather.gc.ca/en/location/index.html?coords=50.450,-104.617',
'Lethbridge, AB|https://weather.gc.ca/en/location/index.html?coords=49.693,-112.835',
'Merritt, BC|https://weather.gc.ca/en/location/index.html?coords=50.111,-120.790',
'Val-d\'Or, QC|https://weather.gc.ca/en/location/index.html?coords=48.105,-77.796',
'Boissevain, MB|https://weather.gc.ca/en/location/index.html?coords=49.231,-100.055',
);
//*/
// end of new settings with V2.16 ------
// ---------- end of settings -----------
//---------------------------------------------------------------------------------------------
// overrides from Settings.php if available
global $SITE;
if (isset($SITE['fcsturlEC'])) {$ECURL = $SITE['fcsturlEC'];}
if (isset($SITE['defaultlang'])) {$defaultLang = $SITE['defaultlang'];}
if (isset($SITE['LINKtarget'])) {$LINKtarget = $SITE['LINKtarget'];}
if (isset($SITE['fcsticonsdirEC'])) {$imagedirEC = $SITE['fcsticonsdirEC'];}
if (isset($SITE['charset'])) {$charsetOutput = strtoupper($SITE['charset']); }
// following overrides are new with V2.16
if (isset($SITE['ECiconType'])) {$iconTypeEC = $SITE['ECiconType']; } // new with V2.16
/* deprecated in V5.00+ .. data not in XML feeds
if (isset($SITE['ECiconDayDate'])) {$doIconDayDate = $SITE['ECiconDayDate']; } // new with V2.16
if (isset($SITE['ECdetailDayDate'])){$doDetailDayDate = $SITE['ECdetailDayDate']; } // new with V2.16
*/
if (isset($SITE['ECforecasts'])) {$ECforecasts = $SITE['ECforecasts']; } // new with V2.16
if (isset($SITE['cacheFileDir'])) {$cacheFileDir = $SITE['cacheFileDir']; } // new with V2.16
if (isset($SITE['ECshowConditions'])) {$showConditions = $SITE['ECshowConditions'];} // new 5.00
if (isset($SITE['ECshowAlmanac'])) {$showAlmanac = $SITE['ECshowAlmanac'];} // new 5.00
if (isset($SITE['ECshow24hour'])) {$show24hour = $SITE['ECshow24hour'];} // new 5.00
// end of overrides from Settings.php if available
//---------------------------------------------------------------------------------------------
//
// The program will return with bits of the forecast items in various
// PHP variables:
// With V4.00 and an EC site redesign, the EC now returns 12hour forecast periods
// $i = 0 to 11 with 0=now, 1=next period, 2=period+2, 3=period+3, 4=period+4 (etc.)
//
// $forecasttitles[$i] = Day/night day of week for forecast
// $forecasticon[$i] = <img> statement for forecast icon
// $forecasttemp[$i] = Red Hi, Blue Lo temperature(s)
// $forecasttext[$i] = Summary of forecast for icon
//
// $forecastdays[$n] = Day/night day of week for detail forecast
// $forecastdetail[$n] = detailed forecast text
//
// Also returned are these useful variables filled in:
// $title = updated/issued text in language selected
// $textfcsthead = 'Current Forecast' or 'Textes des prévisions'
//
// $weather = fully formed html table with two rows of Icons and text
// $textforecast = fully formed <div> with text forecast as <dl>
//
// $alertstring = styled HTML with current advisories/warnings with dropdown/expand
// $currentConditions = table with current conditions at EC forecast site
// $almanac = styled box with Average/Extreme data for the EC forecast site (V5.00)
// $forecast24h = styled table with rolling 24hr forecast details (V5.00)
//
// you can set $printIT = false; and just echo/print the variables above
// in your page to precisely position them. Or use $forecast[$i] to
// print just one of the items where you need it.
//
// I'd recommend you NOT change any of the main code. You can do styling
// for the results by using CSS. See the companion test page
// ec-forecast-testpage.php to demonstrate CSS styling of results.
//
//---------------------------------------------------------------------------------------------
// ---------- main code -----------------
if (isset($_REQUEST['sce']) and 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,charset=ISO-8859-1");
header("Accept-Ranges: bytes");
header("Content-Length: $download_size");
header('Connection: close');
readfile($filenameReal);
exit;
}
// initialize arrays and expected variables
$conditions = array();
$forecasticon = array();
$forecasttemp = array();
$forecasttemptype = array();
$forecasttempabn = array();
$forecasttempHigh = array();
$forecasttempLow = array();
$forecastpop = array();
$forecasttitles = array();
$forecast = array();
$forecasttemptxt = array();
$forecastrealday = array();
$forecasthours = array();
$updated = 'unknown';
$currentConditions = ''; // HTML for table of current conditions
$alertstring = ''; // HTML+Javascript for alert displays
$forecast24h = ''; // HTML for 24hour forecast table
$almanac = ''; // HTML for almanac table
$charsetInput = 'UTF-8'; // they claim ISO-8859-1, but it's really UTF-8 in French XML. Sigh.
if (! isset($PHP_SELF) ) { $PHP_SELF = $_SERVER['PHP_SELF']; }
if(!function_exists('langtransstr')) {
// shim function if not running in template set
function langtransstr($input) { return($input); }
}
$t = pathinfo($PHP_SELF); // get our program name for the HTML comments
$Program = $t['basename'];
$Status = "<!-- ec-forecast.php - $Version -->\n";
if (! isset($doInclude)) { $doInclude = false ; }
if( (isset($_REQUEST['inc']) and strtolower($_REQUEST['inc']) == 'y') or
$doInclude )
{$printIt = false;}
if(!isset($_REQUEST['lang'])) { $_REQUEST['lang'] = '';}
// overrides from calling page
if(isset($doPrint)) {$printIt = $doPrint; }
if(isset($doShowConditions)) {$showConditions = $doShowConditions;}
if(isset($doShowAlmanac)) {$showAlmanac = $doShowAlmanac; }
if(isset($doShow24hour)) {$show24hour = $doShow24hour; }
if(isset($_REQUEST['lang'])) {
$Lang = strtolower($_REQUEST['lang']);
} else {
$Lang = '';
}
if (isset($doLang)) {$Lang = $doLang;};
if (! $Lang) {$Lang = $defaultLang;};
$doDebug = (isset($_REQUEST['debug']) and strtolower($_REQUEST['debug']) == 'y')?true:false;
if ($Lang == 'fr') {
$LMode = 'f';
$ECNAME = "Environnement Canada";
$ECHEAD = 'Prévisions';
$abnormalString = '<p class="ECforecast"><strong>*</strong> - Indique une tendance inverse de la température.</p>' . "\n";
} else {
$Lang = 'en';
$LMode = 'e';
$ECNAME = "Environment Canada";
$ECHEAD = 'Forecast';
$abnormalString = '<p class="ECforecast"><strong>*</strong> - Denotes an abnormal temperature trend.</p>' . "\n";
}
// 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($ECforecasts[0])) {
// print "<!-- making NWSforecasts array default -->\n";
$ECforecasts = array("|$ECURL"); // create default entry
}
// print "<!-- ECforecasts\n".print_r($ECforecasts,true). " -->\n";
// Set the default zone. The first entry in the $SITE['ECforecasts'] array.
list($Nl,$Nn) = explode('|',$ECforecasts[0].'|||');
$FCSTlocation = $Nl;
$ECURL = $Nn;
if(!isset($ECforecasts[$haveIndex])) {
$haveIndex = 0;
}
// locations added to the drop down menu and set selected zone values
$dDownMenu = '';
for ($m=0;$m<count($ECforecasts);$m++) { // for each locations
list($Nlocation,$Nname) = explode('|',$ECforecasts[$m].'|||');
$seltext = '';
if($haveIndex == $m) {
$FCSTlocation = $Nlocation;
$ECURL = $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($ECforecasts[0]) and isset($ECforecasts[1])) {
$ddMenu .= '<table style="border:none;width:99%"><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()">
<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>
</table>
';
}
if(file_exists('ec-forecast-lookup.txt')) {
include_once('ec-forecast-lookup.txt'); // load lookup table
} else {
print $Status;
print "<p>ec-forecast.php ERROR: this script requires 'ec-forecast-lookup.txt' in the same directory, and it is not available.</p>\n";
return(false);
}
/*
// we need to use an array like this, but sometimes this script will not be
// saved as ASCII/ISO-8859-1, and the array of characters gets garbled.
$trantab = array(
'ISO' =>
array('À','à','Â','â','Æ','æ',
'Ç','ç',
'É','é','È','è','Ê','ê','Ë','ë',
'Î','î','Ï','ï',
'Ô','ô','','',
'Ù','ù','Û','û','Ü','ü',
'','ÿ'),
// UTF-8 characters represented as ISO-8859-1
'UTF' =>
array('Ã','à ','Ã','â','Ã','æ',
'Ã','ç',
'Ã','é','Ã','è','Ã','ê','Ã','ë',
'Ã','î','Ã','ï',
'Ã','ô','Å','Å',
'Ã','ù','Ã','û','Ã','ü',
'Ÿ','ÿ'),
);
// so we used the following to encode it:
$serialized = serialize($trantab);
$base64 = base64_encode($serialized);
// and used the output of the base64_encode in the define() statement below.
// then we reconstitute the array with perfect fidelity using
// $trantab = unserialize(base64_decode(ISO_UTF_ARRAY));
// below.
*/
if(!defined('ISO_UTF_ARRAY')) {
define('ISO_UTF_ARRAY',
'YToyOntzOjM6IklTTyI7YTozMjp7aTowO3M6MToiwCI7aToxO3M6MToi4CI7aToyO3M6MToi
wiI7aTozO3M6MToi4iI7aTo0O3M6MToixiI7aTo1O3M6MToi5iI7aTo2O3M6MToixyI7aTo3
O3M6MToi5yI7aTo4O3M6MToiySI7aTo5O3M6MToi6SI7aToxMDtzOjE6IsgiO2k6MTE7czox
OiLoIjtpOjEyO3M6MToiyiI7aToxMztzOjE6IuoiO2k6MTQ7czoxOiLLIjtpOjE1O3M6MToi
6yI7aToxNjtzOjE6Is4iO2k6MTc7czoxOiLuIjtpOjE4O3M6MToizyI7aToxOTtzOjE6Iu8i
O2k6MjA7czoxOiLUIjtpOjIxO3M6MToi9CI7aToyMjtzOjE6IowiO2k6MjM7czoxOiKcIjtp
OjI0O3M6MToi2SI7aToyNTtzOjE6IvkiO2k6MjY7czoxOiLbIjtpOjI3O3M6MToi+yI7aToy
ODtzOjE6ItwiO2k6Mjk7czoxOiL8IjtpOjMwO3M6MToinyI7aTozMTtzOjE6Iv8iO31zOjM6
IlVURiI7YTozMjp7aTowO3M6Mjoiw4AiO2k6MTtzOjI6IsOgIjtpOjI7czoyOiLDgiI7aToz
O3M6Mjoiw6IiO2k6NDtzOjI6IsOGIjtpOjU7czoyOiLDpiI7aTo2O3M6Mjoiw4ciO2k6Nztz
OjI6IsOnIjtpOjg7czoyOiLDiSI7aTo5O3M6Mjoiw6kiO2k6MTA7czoyOiLDiCI7aToxMTtz
OjI6IsOoIjtpOjEyO3M6Mjoiw4oiO2k6MTM7czoyOiLDqiI7aToxNDtzOjI6IsOLIjtpOjE1
O3M6Mjoiw6siO2k6MTY7czoyOiLDjiI7aToxNztzOjI6IsOuIjtpOjE4O3M6Mjoiw48iO2k6
MTk7czoyOiLDryI7aToyMDtzOjI6IsOUIjtpOjIxO3M6Mjoiw7QiO2k6MjI7czoyOiLFkiI7
aToyMztzOjI6IsWTIjtpOjI0O3M6Mjoiw5kiO2k6MjU7czoyOiLDuSI7aToyNjtzOjI6IsOb
IjtpOjI3O3M6Mjoiw7siO2k6Mjg7czoyOiLDnCI7aToyOTtzOjI6IsO8IjtpOjMwO3M6Mjoi
xbgiO2k6MzE7czoyOiLDvyI7fX0=');
}
//reconstitute our trantab from the base64 encoded serialized value
//so we won't have issues if someone inadvertantly saves this script as
// UTF-8 instead of ASCII/ISO-8859-1
//
global $trantab;
$trantab = unserialize(base64_decode(ISO_UTF_ARRAY));
// support both french and english caches
$ECURL = preg_replace('|weatheroffice|i','weather',$ECURL); // autochange Old EC URL if present
$ECURL = preg_replace('|_.\.html|',"_$LMode.html",$ECURL);
$ECURL = preg_replace('|http://|i','https://',$ECURL); // force HTTPS access
# compute new URL based on old URL format if necessary
list($ECURL,$PAGEURL,$cacheName) = gen_ecurl($ECURL);
// force refresh of cache
if (isset($_REQUEST['cache'])) { $refetchSeconds = 1; }
function gen_ecurl($URL) {
# convert old to new format URLS and process new format URLs
# to generate data and link URLs
global $Lang,$EClookup,$Status,$cacheFileDir;
# input URLs:
#
# Old Format
# $ECURL = 'https://weather.gc.ca/city/pages/on-107_metric_e.html'; # Old format
# https://meteo.gc.ca/city/pages/on-107_metric_f.html
#New format
# https://weather.gc.ca/en/location/index.html?coords=49.245,-123.115
# https://meteo.gc.ca/fr/location/index.html?coords=49.245,-123.115
# return:
# $ECURL = 'https://weather.gc.ca/api/app/en/Location/49.245,-123.115?type=city';
# https://meteo.gc.ca/api/app/fr/Location/49.245,-123.115?type=city
$Status .= "<!-- gen_ecurl: URL='$URL' -->\n";
if(strpos($URL,'/pages/')!==false) { # handle OLD forma
# OLD format URL
$U= parse_url($URL);
$host = $U['host'];
$path = $U['path'];
$P = pathinfo($path);
$pp = explode('_',$P['filename'].'_');
$id = $pp[0]; # gets the PP-nnn code from old url.
if(isset($EClookup[$id])){
# 'ab-1' => 'AB|s0000493|Cochrane|Cochrane|51.21|-114.47',
list($pv,$scode,$ENname,$FRname,$lat,$lon) = explode('|',$EClookup[$id]);
$latlon = "$lat,$lon";
} else {
$Status .= "<!-- Warning: unable to find $id in EClookup table -->\n";
}
$cache = $cacheFileDir.'ecforecast-'.str_replace('.','_',$latlon)."-$Lang.json";
if($Lang == 'fr') {
$ECURL = "https://meteo.gc.ca/api/app/v3/fr/Location/$latlon?type=city";
$PGURL = "https://meteo.gc.ca/fr/location/index.html?coords=$latlon";
$Status .= "<!-- using $ECURL for French forecast -->\n";
$Status .= "<!-- using $PGURL for page -->\n";
}
if($Lang == 'en') {
$ECURL = "https://weather.gc.ca/api/app/v3/en/Location/$latlon?type=city";
$PGURL = "https://weather.gc.ca/en/location/index.html?coords=$latlon";
$Status .= "<!-- using $ECURL for English forecast -->\n";
$Status .= "<!-- using $PGURL for page -->\n";
}
$Status .= "<!-- cache '$cache' -->\n";
return(array($ECURL,$PGURL,$cache));
}
if(strpos($URL,'/location/')!==false) { # Handle new format URLs
# NEW format URL
$U= parse_url($URL);
$host = $U['host'];
$path = $U['path'];
$query = $U['query'];
$latlon = str_replace('coords=','',$query);
$cache = $cacheFileDir.'ecforecast-'.str_replace('.','_',$latlon)."-$Lang.json";
if($Lang == 'fr') {
$ECURL = "https://meteo.gc.ca/api/app/v3/fr/Location/$latlon?type=city";
$PGURL = "https://meteo.gc.ca/fr/location/index.html?coords=$latlon";
$Status .= "<!-- using $ECURL for French forecast -->\n";
$Status .= "<!-- using $PGURL for page -->\n";
}
if($Lang == 'en') {
$ECURL = "https://weather.gc.ca/api/app/v3/en/Location/$latlon?type=city";
$PGURL = "https://weather.gc.ca/en/location/index.html?coords=$latlon";
$Status .= "<!-- using $ECURL for English forecast -->\n";
$Status .= "<!-- using $PGURL for page -->\n";
}
$Status .= "<!-- cache '$cache' -->\n";
return(array($ECURL,$PGURL,$cache));
}
}
if($ECURL === false) {
print $Status;
print "<p>ec-forecast.php ERROR: '$FCSTlocation' has an invalid EC page URL '$ECURL'.<br/> The corresponding JSON weather data file is not found for page ID='$ECpgcode'.</p>\n";
return(false);
}
$cacheAge = (file_exists($cacheName))?time()-filemtime($cacheName):9999999;
//---------------------------------------------------------------------------------------------
// load the XML from the EC or cache
$total_time = 0.0;
if (file_exists($cacheName) and $cacheAge < $refetchSeconds) {
$Status .= "<!-- using Cached version from $cacheName age=$cacheAge seconds old -->\n";
$content = file_get_contents($cacheName);
} else {
$Status .= "<!-- refreshing $cacheName age=$cacheAge seconds old -->\n";
$Status .= "<!-- ECURL='$ECURL'\n EC PAGEURL='$PAGEURL' -->\n";
$time_start = ECF_fetch_microtime();
$rawhtml = ECF_fetch_URL($ECURL,false);
$time_stop = ECF_fetch_microtime();
$total_time += ($time_stop - $time_start);
$time_fetch = sprintf("%01.3f",round($time_stop - $time_start,3));
$RC = '';
if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$rawhtml,$matches)) {
$RC = trim($matches[1]);
}
$Status .= "<!-- time to fetch: $time_fetch sec (RC=$RC) -->\n";
if(preg_match('|30\d |i',$RC)) { //oops.. a redirect.. retry the new location
sleep(2); // wait two seconds and retry
preg_match('|Location: (.*)\r\n|',$rawhtml,$matches);
if(isset($matches[1])) {$ECURL = $matches[1];} // update the URL
$time_start = ECF_fetch_microtime();
$rawhtml = ECF_fetch_URL($ECURL,false);
$time_stop = ECF_fetch_microtime();
$total_time += ($time_stop - $time_start);
$time_fetch = sprintf("%01.3f",round($time_stop - $time_start,3));
$RC = '';
if (preg_match("|^HTTP\/\S+ (.*)\r\n|",$rawhtml,$matches)) {
$RC = trim($matches[1]);
}
$Status .= "<!-- second time to fetch: $time_fetch sec ($RC) -->\n";
}
$stuff = explode("\r\n\r\n",$rawhtml); // maybe we have more than one header due to redirects.
$content = (string)array_pop($stuff); // last one is the content
$headers = (string)array_pop($stuff); // next-to-last-one is the headers
if(preg_match('|200|',$RC)) { // good return so save off the cache
$fp = fopen($cacheName, "w");
if ($fp) {
// $site = utf8_decode($site); // convert to ISO-8859-1 for use (like old EC site)
$write = fputs($fp, $content);
fclose($fp);
$Status .= "<!-- cache saved to $cacheName, ".strlen($content)." bytes. -->\n";
} else {
$Status .= "<!-- unable to open $cacheName for writing .. cache not saved -->\n";
}
} else {
$Status .= "<!-- headers returned:\n$headers\n -->\n";
$Status .= "<!-- using Cached version from $cacheName due to unsucessful fetch(s); age=$cacheAge seconds old -->\n";
} // end of cache save
}
// load the XML into an array
if(! file_exists($cacheName)) {
print $Status;
print "<!-- cache file $cacheName not found. Exiting. -->\n";
return (false);
}
$doIconv = ($charsetInput == $charsetOutput)?false:true; // only do iconv() if sets are different
$Status .= "<!-- using charsetInput='$charsetInput' charsetOutput='$charsetOutput' doIconv='$doIconv' -->\n";
// Set up the built-in legends to use in both English and French
$LegendsLang = array(
// English
'en' => array(
'citycondition' => 'Condition',
'obsdate' => 'Date',
'cityobserved' => 'Observed at',
'temperature' => 'Temperature',
'pressure' => 'Pressure',
'tendency' => 'Tendency',
'humidity' => 'Humidity',
'windchill' => 'Wind<br/>Chill',
'windchillabbr' => 'Wind Chill',
'humidex' => 'Humidex',
'visibility' => 'Visibility',
'dewpoint' => 'Dew point',
'wind' => 'Wind',
'gust' => 'gust',
'calm' => 'calm',
'aqhi' => 'Air Quality Health Index',
'maxtemp' => 'Max',
'mintemp' => 'Min',
'maxmin' => 'Normals',
'precip' => 'Total Precipitation',
'precip' => 'Rainfall',
'snow' => 'Snowfall',
'sunrise' => 'Sunrise',
'sunset' => 'Sunset',
'moonrise' => 'Moonrise',
'moonset' => 'Moonset',
'obs' => 'Currently',
'yday' => 'Yesterday',
'norms' => 'Normals',
'issued' => 'Issued',
'extremeMax' => 'Highest temperature',
'extremeMin' => 'Lowest temperature',
'normalMax' => 'Average high',
'normalMin' => 'Average low',
'normalMean' => 'Average',
'extremeRainfall' => 'Greatest rainfall',
'extremeSnowfall' => 'Greatest snowfall',
'extremePrecipitation' => 'Greatest precipitation',
'extremeSnowOnGround' => 'Most snow on the ground',
'almanacpop' => 'Monthly frequency of precipitation',
'avgexhead' => 'Averages and extremes',
'na' => 'n/a',
'forecast24' => '24 Hour Forecast',
'datetime' => 'Date/Time',
'temperature' => 'Temp.',
'weatherconds' => 'Weather Conditions',
'lop' => 'LOP †',
'lopnote' => '† Likelihood of Precipitation (LOP) as described in the public forecast '.
'as a chance of measurable precipitation for a period of time.<br/>' .
' Nil: 0%<br/>' .
' Low: 40% or below<br/>' .
' Medium: 60% or 70%<br/>' .
' High: Above 70%<br/>',
'nonsig' => '‡ Value not significant ',
'impact' => 'Impact Level: ',
'confidence' => 'Forecast Confidence: ',
'effectivefor' => 'In effect for:'
),
'fr'=> array(
// French
'citycondition' => 'Condition',
'obsdate' => 'Date',
'cityobserved' => 'Enregistrées à',
'temperature' => 'Température',
'pressure' => 'Pression',
'tendency' => 'Tendance',
'humidity' => 'Humidité',
'windchill' => 'Refr.<br/>éolien',
'windchillabbr' => 'refroidissement éolien',
'humidex' => 'Humidex',
'visibility' => 'Visibilité',
'dewpoint' => 'Point de rosée',
'wind' => 'Vent',
'calm' => 'calme',
'gust' => 'rafale',
'aqhi' => 'Cote air santé',
'maxmin' => 'Normales',
'maxtemp' => 'Max',
'mintemp' => 'Min',
'precip' => 'Précipitation totale',
'precip' => 'Pluie',
'snow' => 'Neige',
'sunrise' => 'Lever',
'sunset' => 'Coucher',
'moonrise' => 'Lever de la lune',
'moonset' => 'Coucher de la lune',
'obs' => 'Conditions actuelles',
'yday' => 'Données d\'hier',
'norms' => 'Normales',
'issued' => 'Émises à',
'extremeMax' => 'Température la plus élevée',
'extremeMin' => 'Température la plus basse',
'normalMax' => 'Température maximale moyenne',
'normalMin' => 'Température minimale moyenne',
'normalMean' => 'Température moyenne',
'extremeRainfall' => 'Pluie maximale',
'extremeSnowfall' => 'Neige maximale',
'extremePrecipitation' => 'Précipitation maximale',
'extremeSnowOnGround' => 'Maximum de neige au sol',
'almanacpop' => 'Fréquence mensuelle de précipitation',
'avgexhead' => 'Moyennes et extrêmes',
'na' => 'n.d.',
'forecast24' => 'Prévisions 24 heures',
'datetime' => 'Date/Heure',
'temperature' => 'Temp',
'weatherconds' => 'Condition météo',
'lop' => 'EdP †',
'wind' => 'Vents',
'lopnote' => '† Éventualité de précipitation (EdP) mesurable, indiqué dans la prévision '.
'publique comme probabilité de précipitation pour une période de temps.<br/>' .
' Nulle: 0%<br/>' .
' Basse: 40% et moins<br/>' .
' Moyenne: 60% ou 70%<br/>' .
' Élevée : 80% et plus<br/>',
'nonsig' => '‡ Valeur non significative',
'impact' => 'Niveau d\'impact: ',
'confidence' => 'Confiance dans les prévisions: ',
'effectivefor' => 'En vigueur pour:',
)
);
$Legends = $LegendsLang[$Lang]; // use the legends based on language choice
if($doIconv) { // put legends in UTF-8 for later conversion
$TLegends = array();
foreach ($Legends as $key => $val) {
$nval = iconv('ISO-8859-1','UTF-8//TRANSLIT',$val);
$TLegends[$key] = $nval;
}
$Legends = $TLegends;
$Status .= "<!-- converted lookup legends to UTF-8 -->\n";
}
$MonthNamesLang = array( // easier to use this than switching locales...
'en' => array(
'01' => 'January',
'02' => 'February',
'03' => 'March',
'04' => 'April',
'05' => 'May',
'06' => 'June',
'07' => 'July',
'08' => 'August',
'09' => 'September',
'10' => 'October',
'11' => 'November',
'12' => 'December'
),
'fr' => array(
'01' => 'janvier',
'02' => 'février',
'03' => 'mars',
'04' => 'avril',
'05' => 'mai',
'06' => 'juin',
'07' => 'juillet',
'08' => 'août',
'09' => 'septembre',
'10' => 'octobre',
'11' => 'novembre',
'12' => 'décembre'
)
);
$MonthNames = $MonthNamesLang[$Lang]; // month names (for 24hr forecast) based on language
if($doIconv) { // put months in UTF-8
$TMonths = array();
foreach ($MonthNames as $key => $val) {
$nval = iconv('ISO-8859-1','UTF-8//TRANSLIT',$val);
$TMonths[$key] = $nval;
}
$MonthNames = $TMonths;
$Status .= "<!-- converted lookup months to UTF-8 -->\n";
}
$RAWJSON = json_decode($content,true);
$JSON = isset($RAWJSON[0]['lastUpdated'])?$RAWJSON[0]:array();
//----------- handle the city conditions -----------------------------------------
$X = $JSON['observation'];
/*
"observation": {
"observedAt": "Hamilton Munro Int'l Airport",
"provinceCode": "ON",
"climateId": "6153193",
"tcid": "yhm",
"timeStamp": "2024-10-23T18:00:00.000Z",
"timeStampText": "2:00 PM EDT Wednesday 23 October 2024",
"iconCode": "03",
"condition": "Mostly Cloudy",
"temperature": {
"imperial": "68",
"imperialUnrounded": "68.4",
"metric": "20",
"metricUnrounded": "20.2",
"qaValue": 100
},
"dewpoint": {
"imperial": "51",
"imperialUnrounded": "50.7",
"metric": "10",
"metricUnrounded": "10.4",
"qaValue": 100
},
"feelsLike": {
"imperial": "72",
"metric": "22",
"qaValue": 100
},
"pressure": {
"imperial": "29.9",
"metric": "101.1",
"changeImperial": "0.01",
"changeMetric": "0.04",
"qaValue": 100
},
"tendency": "rising",
"visibility": {
"imperial": "15",
"metric": "24",
"qaValue": 100
},
"visUnround": 24.10000000000000142108547152020037174224853515625,
"humidity": "53",
"humidityQaValue": 100,
"windSpeed": {
"imperial": "17",
"metric": "27",
"qaValue": 100
},
"windGust": {
"imperial": "24",
"metric": "38",
"qaValue": 100
},
"windDirection": "WSW",
"windDirectionQAValue": 100,
"windBearing": "243.0"
},
*/
// NOTE: we'll store the current conditions in the $conditions array for later assembly
if(isset($X['observedAt'])) { // got an observation.. format it
$conditions['cityobserved'] = $Legends['cityobserved'] . ': <strong>'.
(string)$X['observedAt'] . '</strong>';
$obsdate = (string)$X['timeStampText'];
if($doIconv) {
$obsdate = iconv($charsetInput,$charsetOutput.'//TRANSLIT',ECF_UTF_CLEANUP($obsdate));
}
$conditions['obsdate'] = $Legends['obsdate'] .': <strong>'.
$obsdate . '</strong>';
if(isset($X['condition']) and strlen((string)$X['condition']) > 0) {
$conditions['citycondition'] = '<strong>'.
(string)$X['condition'] . '</strong>';
$conditions['icon'] = (string)$X['iconCode'] . $iconTypeEC;
}
$conditions['pressure'] = $Legends['pressure'] . ': <strong>'.
(string)$X['pressure']['metric'] . ' kPa</strong>';
$conditions['tendency'] = $Legends['tendency'] . ': <strong>'.
(string)$X['pressure']['changeMetric'] . ' kPa</strong>';
$conditions['temperature'] = $Legends['temperature'] . ': <strong>'.
(string)$X['temperature']['metric'] . ' °C</strong>';
if(strlen((string)$X['dewpoint']['metric']) > 0) {
$conditions['dewpoint'] = $Legends['dewpoint'] . ': <strong>'.
(string)$X['dewpoint']['metric'] . ' °C</strong>';
}
if(isset($X['humidity'])) {
$conditions['humidity'] = $Legends['humidity'] . ': <strong>'.
(string)$X['humidity'] . ' %</strong>';
}
$conditions['wind'] = $Legends['wind'] . ': <strong>';
if($X['windSpeed']['metric'] > 0) {
$conditions['wind'] .= (string)$X['windDirection'] . ' ' . $X['windSpeed']['metric'];
if(isset($X['windGust']['metric']) and strlen((string)$X['windGust']['metric'])>0) {
$conditions['wind'] .= ' ' . $Legends['gust'] . ' ' . (string)$X['windGust']['metric'];
}
$conditions['wind'] .= ' km/h';
} else {
$conditions['wind'] .= $Legends['calm'];
}
$conditions['wind'] .= '</strong>';
if(isset($X['humidex'])) {
$conditions['humidex'] = $Legends['humidex'] . ': <strong>'.
(string)$X['humidex'] . '</strong>';
}
if($X['temperature']['metric'] <= 0 and isset($X['feelsLike']['metric'])) {
$tl = str_replace('<br/>',' ',$Legends['windchill']);
$conditions['windchill'] = $tl . ': <strong>'.
$X['feelsLike']['metric'] . ' °C</strong>';
}
if(isset($X['visibility']['metric'])) {
$conditions['visibility'] = $Legends['visibility'] . ': <strong>'.
$X['visibility']['metric'] . ' km</strong>';
}
}
// extract 'normals'
/*
"dailyFcst": {
"dailyIssuedTimeShrt": "5:00 AM PDT",
"regionalNormals": {
"metric": {
"highTemp": 13,
"lowTemp": 6,
"text": "Low 6. High 13."
},
"imperial": {
"highTemp": 55,
"lowTemp": 43,
"text": "Low 6. High 13."
}
},
*/
if(isset($JSON['dailyFcst']['dailyIssuedTimeShrt'])) {
$X = $JSON['dailyFcst'];
if(isset($X['regionalNormals']['metric']['text'])) {
$conditions['maxmin'] = $Legends['maxmin'] .
': Max <strong>' . $X['regionalNormals']['metric']['highTemp'] .
'°C</strong> Min <strong>' . $X['regionalNormals']['metric']['lowTemp'] .
'°C</strong>';
}
/* yesterday info not available
// extract the yesterday values
$X = $xml->yesterdayConditions;
if(isset($X->temperature[1])) {
$conditions['ydayheading'] = $Legends['yday'];
$conditions['ydaymaxtemp'] = $Legends['maxtemp'] . ': <strong>' .
(string)$X->temperature[0] . ' °C</strong>';
$conditions['ydaymintemp'] = $Legends['mintemp'] . ': <strong>' .
(string)$X->temperature[1] . ' °C</strong>';
$conditions['ydayprecip'] = $Legends['precip'] . ': <strong>' .
(string)$X->precip . ' mm</strong>';
}
*/
/*
"riseSet": {
"set": {
"time12h": "6:13 pm",
"epochTimeRounded": "1729386000",
"time": "18:13"
},
"timeZone": "PDT",
"rise": {
"time12h": "7:41 am",
"epochTimeRounded": "1729346400",
"time": "7:41"
}
},
*/
// extract the sunrise/sunset data
$X = $JSON['riseSet'];
if(isset($X['rise']['time'])) {
$conditions['sunrise'] = $Legends['sunrise'] . ': <strong>' .
$X['rise']['time'] . '</strong>';
$conditions['sunset'] = $Legends['sunset'] . ': <strong>' .
$X['set']['time'] . '</strong>';
}
}
// Almanac info is not available in new JSON data
// change conditions back to ISO-8859-1 if needed
if($doIconv) {
foreach ($conditions as $key => $val) {
if($key == 'obsdate') {continue;} // it's already in iso-8859-1 strangely
$conditions[$key] = iconv($charsetInput,$charsetOutput.'//TRANSLIT',$val);
}
}
$Status .= "<!-- conditions\n" . print_r($conditions,true) . " -->\n";
//---------------------------------------------------------------------------------------------
// Process the Hourly Forecast (if availablel)
/*
"hourlyFcst": {
"hourlyIssuedTimeShrt": "5:00 AM PDT",
"hourly": [
{
"date": "19 October 2024",
"periodID": 0,
"windGust": {
"metric": "",
"imperial": ""
},
"windDir": "SE",
"feelsLike": {
"metric": "",
"imperial": ""
},
"condition": "Rain at times heavy",
"precip": "100",
"temperature": {
"metric": "14",
"imperial": "57"
},
"iconCode": "13",
"time": "7 AM",
"windSpeed": {
"metric": "30",
"imperial": "19"
},
"epochTime": 1729346400,
"dateShrt": "19 Oct"
},
*/
if(isset($JSON['hourlyFcst']['hourly'][0])) {
$UOMTempUsed = "°C";