Projet

Général

Profil

Télécharger (17,8 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / usr / local / www / widgets / widgets / ntp_status.widget.php @ fab1cd2f

1
<?php
2
/*
3
        $Id$
4
        Copyright 2007 Scott Dale
5
        Part of pfSense widgets (https://www.pfsense.org)
6
        originally based on m0n0wall (http://m0n0.ch/wall)
7

    
8
        Copyright (C) 2004-2005 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
9
        and Jonathan Watt <jwatt@jwatt.org>.
10
        All rights reserved.
11

    
12
        Redistribution and use in source and binary forms, with or without
13
        modification, are permitted provided that the following conditions are met:
14

    
15
        1. Redistributions of source code must retain the above copyright notice,
16
           this list of conditions and the following disclaimer.
17

    
18
        2. Redistributions in binary form must reproduce the above copyright
19
           notice, this list of conditions and the following disclaimer in the
20
           documentation and/or other materials provided with the distribution.
21

    
22
        THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
24
        AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25
        AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
26
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29
        CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30
        ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31
        POSSIBILITY OF SUCH DAMAGE.
32
*/
33

    
34
$nocsrf = true;
35

    
36
require_once("guiconfig.inc");
37
require_once("pfsense-utils.inc");
38
require_once("functions.inc");
39

    
40
require_once("/usr/local/www/widgets/include/ntp_status.inc");
41

    
42
if($_REQUEST['updateme']) {
43
//this block displays only on ajax refresh
44
	exec("/usr/local/sbin/ntpq -pn | /usr/bin/tail +3", $ntpq_output);
45
	$ntpq_counter = 0;
46
	foreach ($ntpq_output as $line) {
47
		if (substr($line, 0, 1) == "*") {
48
			//Active NTP Peer
49
			$line = substr($line, 1);
50
			$peerinfo = preg_split("/[\s\t]+/", $line);
51
			if ($peerinfo[2] == "1") {
52
				$syncsource = $peerinfo[0] . " (stratum " . $peerinfo[2] . ", " . $peerinfo[1] . ")";
53
			} else {
54
				$syncsource = $peerinfo[0] . " (stratum " . $peerinfo[2] . ")";
55
			}
56
			$ntpq_counter++;
57
		} elseif (substr($line, 0, 1) == "o") {
58
			//Local PPS Peer
59
			$line = substr($line, 1);
60
			$peerinfo = preg_split("/[\s\t]+/", $line);
61
			$syncsource = $peerinfo[1] . " (stratum " . $peerinfo[2] . ", PPS)";
62
			$ntpq_counter++;
63
		}
64
	}
65

    
66
	exec("/usr/local/sbin/ntpq -c clockvar", $ntpq_clockvar_output);
67
	foreach ($ntpq_clockvar_output as $line) {
68
		if (substr($line, 0, 9) == "timecode=") {
69
			$tmp = explode('"', $line);
70
			$tmp = $tmp[1];
71
			if (substr($tmp, 0, 6) == '$GPRMC') {
72
				$gps_vars = explode(",", $tmp);
73
				$gps_ok  = ($gps_vars[2] == "A");
74
				$gps_lat_deg = substr($gps_vars[3], 0, 2);
75
				$gps_lat_min = substr($gps_vars[3], 2) / 60.0;
76
				$gps_lon_deg = substr($gps_vars[5], 0, 3);
77
				$gps_lon_min = substr($gps_vars[5], 3) / 60.0;
78
				$gps_lat = $gps_lat_deg + $gps_lat_min;
79
				$gps_lat = $gps_lat * (($gps_vars[4] == "N") ? 1 : -1);
80
				$gps_lon = $gps_lon_deg + $gps_lon_min;
81
				$gps_lon = $gps_lon * (($gps_vars[6] == "E") ? 1 : -1);
82
				$gps_la = $gps_vars[4];
83
				$gps_lo = $gps_vars[6];
84
			}elseif (substr($tmp, 0, 6) == '$GPGGA') {
85
				$gps_vars = explode(",", $tmp);
86
				$gps_ok  = $gps_vars[6];
87
				$gps_lat_deg = substr($gps_vars[2], 0, 2);
88
				$gps_lat_min = substr($gps_vars[2], 2) / 60.0;
89
				$gps_lon_deg = substr($gps_vars[4], 0, 3);
90
				$gps_lon_min = substr($gps_vars[4], 3) / 60.0;
91
				$gps_lat = $gps_lat_deg + $gps_lat_min;
92
				$gps_lat = $gps_lat * (($gps_vars[3] == "N") ? 1 : -1);
93
				$gps_lon = $gps_lon_deg + $gps_lon_min;
94
				$gps_lon = $gps_lon * (($gps_vars[5] == "E") ? 1 : -1);
95
				$gps_alt = $gps_vars[9];
96
				$gps_alt_unit = $gps_vars[10];
97
				$gps_sat = $gps_vars[7];
98
				$gps_la = $gps_vars[3];
99
				$gps_lo = $gps_vars[5];
100
			}elseif (substr($tmp, 0, 6) == '$GPGLL') {
101
				$gps_vars = explode(",", $tmp);
102
				$gps_ok  = ($gps_vars[6] == "A");
103
				$gps_lat_deg = substr($gps_vars[1], 0, 2);
104
				$gps_lat_min = substr($gps_vars[1], 2) / 60.0;
105
				$gps_lon_deg = substr($gps_vars[3], 0, 3);
106
				$gps_lon_min = substr($gps_vars[3], 3) / 60.0;
107
				$gps_lat = $gps_lat_deg + $gps_lat_min;
108
				$gps_lat = $gps_lat * (($gps_vars[2] == "N") ? 1 : -1);
109
				$gps_lon = $gps_lon_deg + $gps_lon_min;
110
				$gps_lon = $gps_lon * (($gps_vars[4] == "E") ? 1 : -1);
111
				$gps_la = $gps_vars[2];
112
				$gps_lo = $gps_vars[4];
113
			}
114
		}
115
	}
116

    
117
	if (isset($config['ntpd']['gps']['type']) && ($config['ntpd']['gps']['type'] == 'SureGPS') && (isset($gps_ok))) {
118
		//GSV message is only enabled by init commands in services_ntpd_gps.php for SureGPS board
119
		$gpsport = fopen("/dev/gps0", "r+");
120
		while($gpsport){
121
			$buffer = fgets($gpsport);
122
			if(substr($buffer, 0, 6)=='$GPGSV'){
123
				//echo $buffer."\n";
124
				$gpgsv = explode(',',$buffer);
125
				$gps_satview = $gpgsv[3];
126
				break;
127
			}
128
		}
129
	}
130
?>
131

    
132
<table width="100%" border="0" cellspacing="0" cellpadding="0" summary="clock">
133
	<tbody>
134
		<tr>
135
			<td width="40%" class="vncellt">Sync Source</td>
136
			<td width="60%" class="listr">
137
			<?php if ($ntpq_counter == 0): ?>
138
				No active peers available
139
			<?php else: ?>
140
				<?php echo $syncsource; ?>
141
			<?php endif; ?>
142
			</td>
143
		</tr>
144
		<?php if (($gps_ok) && ($gps_lat) && ($gps_lon)): ?>
145
			<tr>
146
				<td width="40%" class="vncellt">Clock location</td>
147
				<td width="60%" class="listr">
148
					<a target="_gmaps" href="http://maps.google.com/?q=<?php echo $gps_lat; ?>,<?php echo $gps_lon; ?>">
149
					<?php 
150
					echo sprintf("%.5f", $gps_lat) . " " . $gps_la . ", " . sprintf("%.5f", $gps_lon) . " " . $gps_lo; ?>
151
					</a>
152
					<?php if (isset($gps_alt)) {echo " (" . $gps_alt . " " . $gps_alt_unit . " alt.)";} ?>
153
				</td>
154
			</tr>
155
			<?php if (isset($gps_sat) || isset($gps_satview)): ?>
156
				<tr>
157
					<td width="40%" class="vncellt">Satellites</td>
158
					<td width="60%" class="listr">
159
					<?php 
160
					if (isset($gps_satview)) {echo 'in view ' . intval($gps_satview);}
161
					if (isset($gps_sat) && isset($gps_satview)) {echo ', ';}
162
					if (isset($gps_sat)) {echo 'in use ' . $gps_sat;} 
163
					?>
164
					</td>
165
				</tr>
166
			<?php endif; ?>
167
		<?php endif; ?>
168
	</tbody>
169
</table>
170
<?php	
171
	exit;
172
}
173

    
174
/*** Clock -- beginning of server-side support code
175
by Andrew Shearer, http://www.shearersoftware.com/
176
v2.1.2-PHP, 2003-08-07. For updates and explanations, see
177
<http://www.shearersoftware.com/software/web-tools/clock/>. ***/
178

    
179
/* Prevent this page from being cached (though some browsers still
180
   cache the page anyway, which is why we use cookies). This is
181
   only important if the cookie is deleted while the page is still
182
   cached (and for ancient browsers that don't know about Cache-Control).
183
   If that's not an issue, you may be able to get away with
184
   "Cache-Control: private" instead. */
185

    
186
/* Grab the current server time. */
187
$gDate = time();
188
/* Are the seconds shown by default? When changing this, also change the
189
   JavaScript client code's definition of clockShowsSeconds below to match. */
190
$gClockShowsSeconds = true;
191

    
192
function getServerDateItems($inDate) {
193
	return date('Y,n,j,G,',$inDate).intval(date('i',$inDate)).','.intval(date('s',$inDate));
194
	// year (4-digit),month,day,hours (0-23),minutes,seconds
195
	// use intval to strip leading zero from minutes and seconds
196
	//   so JavaScript won't try to interpret them in octal
197
	//   (use intval instead of ltrim, which translates '00' to '')
198
}
199

    
200
function clockDateString($inDate) {
201
    return date('Y. F j l',$inDate);    // eg "Monday, January 1, 2002"
202
}
203

    
204
function clockTimeString($inDate, $showSeconds) {
205
    return date($showSeconds ? 'G:i:s' : 'g:i',$inDate).' ';
206
}
207
/*** Clock -- end of server-side support code ***/
208
?>
209

    
210
<script type="text/javascript">
211
<!--
212
/* set up variables used to init clock in BODY's onLoad handler;
213
   should be done as early as possible */
214
var clockLocalStartTime = new Date();
215
var clockServerStartTime = new Date(<?php echo(getServerDateItems($gDate))?>);
216

    
217
/* stub functions for older browsers;
218
   will be overridden by next JavaScript1.2 block */
219
function clockInit() {
220
}
221
//-->
222
</script>
223

    
224

    
225
<script type="text/javascript">
226
<!--
227
/*** simpleFindObj, by Andrew Shearer
228

    
229
Efficiently finds an object by name/id, using whichever of the IE,
230
classic Netscape, or Netscape 6/W3C DOM methods is available.
231
The optional inLayer argument helps Netscape 4 find objects in
232
the named layer or floating DIV. */
233
function simpleFindObj(name, inLayer) {
234
	return document[name] || (document.all && document.all[name])
235
		|| (document.getElementById && document.getElementById(name))
236
		|| (document.layers && inLayer && document.layers[inLayer].document[name]);
237
}
238

    
239
/*** Beginning of Clock 2.1.2, by Andrew Shearer
240
See: http://www.shearersoftware.com/software/web-tools/clock/
241
Redistribution is permitted with the above notice intact.
242

    
243
Client-side clock, based on computed time differential between browser &
244
server. The server time is inserted by server-side JavaScript, and local
245
time is subtracted from it by client-side JavaScript while the page is
246
loading.
247

    
248
Cookies: The local and remote times are saved in cookies named
249
localClock and remoteClock, so that when the page is loaded from local
250
cache (e.g. by the Back button) the clock will know that the embedded
251
server time is stale compared to the local time, since it already
252
matches its cookie. It can then base the calculations on both cookies,
253
without reloading the page from the server. (IE 4 & 5 for Windows didn't
254
respect Response.Expires = 0, so if cookies weren't used, the clock
255
would be wrong after going to another page then clicking Back. Netscape
256
& Mac IE were OK.)
257

    
258
Every so often (by default, one hour) the clock will reload the page, to
259
make sure the clock is in sync (as well as to update the rest of the
260
page content).
261

    
262
Compatibility: IE 4.x and 5.0, Netscape 4.x and 6.0, Mozilla 1.0. Mac & Windows.
263

    
264
History:  1.0   2000-05-09 GIF-image digits
265
          2.0   2000-06-29 Uses text DIV layers (so 4.0 browsers req'd), &
266
                         cookies to work around Win IE stale-time bug
267
		  2.1   2002-10-12 Noted Mozilla 1.0 compatibility; released PHP version.
268
		  2.1.1 2002-10-20 Fixed octal bug in the PHP translation; the number of
269
		  				minutes & seconds were misinterpretes when less than 10
270
		  2.1.2 2003-08-07 The previous fix had introduced a bug when the
271
		                minutes or seconds were exactly 0. Thanks to Man Bui
272
		                for reporting the bug.
273
*/
274
var clockIncrementMillis = 1000;
275
var localTime;
276
var clockOffset;
277
var clockExpirationLocal;
278
var clockShowsSeconds = true;
279
var clockTimerID = null;
280

    
281
function clockInit(localDateObject, serverDateObject)
282
{
283
    var origRemoteClock = parseInt(clockGetCookieData("remoteClock"));
284
    var origLocalClock = parseInt(clockGetCookieData("localClock"));
285
    var newRemoteClock = serverDateObject.getTime();
286
    // May be stale (WinIE); will check against cookie later
287
    // Can't use the millisec. ctor here because of client inconsistencies.
288
    var newLocalClock = localDateObject.getTime();
289
    var maxClockAge = 60 * 60 * 1000;   // get new time from server every 1hr
290

    
291
    if (newRemoteClock != origRemoteClock) {
292
        // new clocks are up-to-date (newer than any cookies)
293
        document.cookie = "remoteClock=" + newRemoteClock;
294
        document.cookie = "localClock=" + newLocalClock;
295
        clockOffset = newRemoteClock - newLocalClock;
296
        clockExpirationLocal = newLocalClock + maxClockAge;
297
        localTime = newLocalClock;  // to keep clockUpdate() happy
298
    }
299
    else if (origLocalClock != origLocalClock) {
300
        // error; localClock cookie is invalid (parsed as NaN)
301
        clockOffset = null;
302
        clockExpirationLocal = null;
303
    }
304
    else {
305
        // fall back to clocks in cookies
306
        clockOffset = origRemoteClock - origLocalClock;
307
        clockExpirationLocal = origLocalClock + maxClockAge;
308
        localTime = origLocalClock;
309
        // so clockUpdate() will reload if newLocalClock
310
        // is earlier (clock was reset)
311
    }
312
    /* Reload page at server midnight to display the new date,
313
       by expiring the clock then */
314
    var nextDayLocal = (new Date(serverDateObject.getFullYear(),
315
            serverDateObject.getMonth(),
316
            serverDateObject.getDate() + 1)).getTime() - clockOffset;
317
    if (nextDayLocal < clockExpirationLocal) {
318
        clockExpirationLocal = nextDayLocal;
319
    }
320
}
321

    
322
function clockOnLoad()
323
{
324
    clockUpdate();
325
}
326

    
327
function clockOnUnload() {
328
    clockClearTimeout();
329
}
330

    
331
function clockClearTimeout() {
332
    if (clockTimerID) {
333
        clearTimeout(clockTimerID);
334
        clockTimerID = null;
335
    }
336
}
337

    
338
function clockToggleSeconds()
339
{
340
    clockClearTimeout();
341
    if (clockShowsSeconds) {
342
        clockShowsSeconds = false;
343
        clockIncrementMillis = 60000;
344
    }
345
    else {
346
        clockShowsSeconds = true;
347
        clockIncrementMillis = 1000;
348
    }
349
    clockUpdate();
350
}
351

    
352
function clockTimeString(inHours, inMinutes, inSeconds) {
353
	return inHours
354
	+ (inMinutes < 10 ? ":0" : ":") + inMinutes
355
	+ (inSeconds < 10 ? ":0" : ":") + inSeconds;
356
}
357

    
358
function clockDisplayTime(inHours, inMinutes, inSeconds) {
359
    
360
    clockWriteToDiv("ClockTime", clockTimeString(inHours, inMinutes, inSeconds));
361
}
362

    
363
function clockWriteToDiv(divName, newValue) // APS 6/29/00
364
{
365
    var divObject = simpleFindObj(divName);
366
    newValue = '<b>' + newValue + '<' + '/b>';
367
    if (divObject && divObject.innerHTML) {
368
        divObject.innerHTML = newValue;
369
    }
370
    else if (divObject && divObject.document) {
371
        divObject.document.writeln(newValue);
372
        divObject.document.close();
373
    }
374
    // else divObject wasn't found; it's only a clock, so don't bother complaining
375
}
376

    
377
function clockGetCookieData(label) {
378
    /* find the value of the specified cookie in the document's
379
    semicolon-delimited collection. For IE Win98 compatibility, search
380
    from the end of the string (to find most specific host/path) and
381
    don't require "=" between cookie name & empty cookie values. Returns
382
    null if cookie not found. One remaining problem: Under IE 5 [Win98],
383
    setting a cookie with no equals sign creates a cookie with no name,
384
    just data, which is indistinguishable from a cookie with that name
385
    but no data but can't be overwritten by any cookie with an equals
386
    sign. */
387
    var c = document.cookie;
388
    if (c) {
389
        var labelLen = label.length, cEnd = c.length;
390
        while (cEnd > 0) {
391
            var cStart = c.lastIndexOf(';',cEnd-1) + 1;
392
            /* bug fix to Danny Goodman's code: calculate cEnd, to
393
            prevent walking the string char-by-char & finding cookie
394
            labels that contained the desired label as suffixes */
395
            // skip leading spaces
396
            while (cStart < cEnd && c.charAt(cStart)==" ") cStart++;
397
            if (cStart + labelLen <= cEnd && c.substr(cStart,labelLen) == label) {
398
                if (cStart + labelLen == cEnd) {
399
                    return ""; // empty cookie value, no "="
400
                }
401
                else if (c.charAt(cStart+labelLen) == "=") {
402
                    // has "=" after label
403
                    return unescape(c.substring(cStart + labelLen + 1,cEnd));
404
                }
405
            }
406
            cEnd = cStart - 1;  // skip semicolon
407
        }
408
    }
409
    return null;
410
}
411

    
412
/* Called regularly to update the clock display as well as onLoad (user
413
   may have clicked the Back button to arrive here, so the clock would need
414
   an immediate update) */
415
function clockUpdate()
416
{
417
    var lastLocalTime = localTime;
418
    localTime = (new Date()).getTime();
419
    
420
    /* Sanity-check the diff. in local time between successive calls;
421
       reload if user has reset system clock */
422
    if (clockOffset == null) {
423
        clockDisplayTime(null, null, null);
424
    }
425
    else if (localTime < lastLocalTime || clockExpirationLocal < localTime) {
426
        /* Clock expired, or time appeared to go backward (user reset
427
           the clock). Reset cookies to prevent infinite reload loop if
428
           server doesn't give a new time. */
429
        document.cookie = 'remoteClock=-';
430
        document.cookie = 'localClock=-';
431
        location.reload();      // will refresh time values in cookies
432
    }
433
    else {
434
        // Compute what time would be on server 
435
        var serverTime = new Date(localTime + clockOffset);
436
        clockDisplayTime(serverTime.getHours(), serverTime.getMinutes(),
437
            serverTime.getSeconds());
438
        
439
        // Reschedule this func to run on next even clockIncrementMillis boundary
440
        clockTimerID = setTimeout("clockUpdate()",
441
            clockIncrementMillis - (serverTime.getTime() % clockIncrementMillis));
442
    }
443
}
444

    
445
/*** End of Clock ***/
446
//-->
447
  window.onload=clockInit(clockLocalStartTime, clockServerStartTime);clockOnLoad();
448
  window.onunload=clockOnUnload()
449
  clockUpdate();
450
</script>
451

    
452

    
453
<table width="100%" border="0" cellspacing="0" cellpadding="0" summary="clock">
454
	<tbody>
455
		<tr>
456
			<td width="40%" class="vncellt">Server Time</td>
457
			<td width="60%" class="listr">
458
				<div id="ClockTime">
459
					<b><?php echo(clockTimeString($gDate,$gClockShowsSeconds));?></b>
460
				</div>
461
			</td>
462
		</tr>
463
	</tbody>
464
</table>
465

    
466
<div id='ntpstatus'>
467
<table width="100%" border="0" cellspacing="0" cellpadding="0" summary="clock">
468
	<tbody>
469
		<tr>
470
			<td width="100%" class="listr">
471
				Updating...
472
			</td>
473
		</tr>
474
	</tbody>
475
</table>
476
</div>
477

    
478
<script type="text/javascript">
479
	function ntp_getstatus() {
480
		scroll(0,0);
481
		var url = "/widgets/widgets/ntp_status.widget.php";
482
		var pars = 'updateme=yes';
483
		jQuery.ajax(
484
			url,
485
			{
486
				type: 'get',
487
				data: pars,
488
				complete: ntpstatuscallback
489
			});
490
		// Refresh the status every 1 minute
491
		setTimeout('ntp_getstatus()', 1*60*1000);
492
	}
493
	function ntpstatuscallback(transport) {
494
		// The server returns formatted html code
495
		var responseStringNtp = transport.responseText
496
		jQuery('#ntpstatus').prop('innerHTML',responseStringNtp);
497
	}
498
	// Do the first status check 1 second after the dashboard opens
499
	setTimeout('ntp_getstatus()', 1000);
500
</script>
(12-12/21)