1#!/usr/bin/env php
2<?php
3
4require 'Bencode.php';
5require 'Cjdns.php';
6require 'publicKey2ipv6.php';
7
8define('PASSWORD', 'NONE');
9
10$cjdns = new Cjdns(PASSWORD, "127.0.0.1", 11234);
11
12$peers = []; $page = 0;
13do
14{
15        $res = $cjdns->call("InterfaceController_peerStats", ['page' => $page++]);
16        $peers = array_merge($peers, $res['peers']);
17} while(!empty($res['more']));
18
19$table = new table();
20
21$table->add(['Public Key', 'Ipv6', 'User', 'State', 'Last', 'Bytes In', 'Bytes Out', 'Lost', 'Ver', 'In']);
22
23foreach ($peers as $a)
24{
25	$pK   = preg_match('/.{23}([a-z0-6]{4}).+(.{6})$/', $a['addr'], $m) ? $m[1].'...'.$m[2] : '?';
26	$ip   = preg_replace('#.+:#', ':', publicKey2ipv6(explode('.', $a['addr'])[5]));
27	$ver  = preg_match('/^v(\d+)/', $a['addr'], $m) ? $m[1] : '?';
28	$date = str_replace(date(' d.m.y'), '', date('H:i:s d.m.y', $a['last']/1000));
29	$table->add([$pK, $ip, $a['user'], $a['state'], $date,
30		_h($a['bytesIn']), _h($a['bytesOut']), $a['lostPackets'],
31		$ver, $a['isIncoming']]);
32}
33
34$table->printSimple();
35
36// human readable bytes
37function _h($x)
38{
39	if ($x < 1024) return sprintf("%5.2f",    $x); $x /= 1024;
40	if ($x < 1024) return sprintf("%5.2f Kb", $x); $x /= 1024;
41	if ($x < 1024) return sprintf("%5.2f Mb", $x); $x /= 1024;
42	if ($x < 1024) return sprintf("%5.2f Gb", $x); $x /= 1024;
43	return $x;
44}
45
46
47// class for draw table data
48class table
49{
50	private $data  = [];
51	private $width = [];
52	private $cur_row   = 0;
53	public function add($a)
54	{
55		array_push($this->data, $a);
56		foreach ($a as $i => $x)
57		if (@$this->width[$i] < strlen($x))
58			$this->width[$i] = strlen($x);
59	}
60	public function printSimple()
61	{
62		$this->printLine();
63		$this->printRows(1); // header
64		$this->printLine();
65		$this->printRows();
66		$this->printLine();
67	}
68	public function printLine()
69	{
70		foreach ($this->width as $w)
71		{
72			printf("+");
73			printf($this->strdup($w+2));
74		}
75		printf("+\n");
76	}
77	public function printRows($n = NULL)
78	{
79		if (is_null($n)) $n = count($this->data);
80		for ($this->cur_row; $n && $this->cur_row<count($this->data); $this->cur_row++, $n--)
81		{
82			foreach ($this->width as $i => $w)
83			{
84				$this->printCell($this->data[$this->cur_row][$i], $w);
85			}
86			printf("|\n");
87		}
88	}
89	private function strdup($n,$x='-') { $st=''; for ($i=0;$i<$n;$i++)$st.=$x; return $st; }
90	private function printCell($data, $width)
91	{
92		if (empty($data)) $data = ''; // clear zero-value
93		if (!is_numeric($data)) // align string to center
94		{
95			$d = ($width - strlen($data)) >> 1;
96			$data .= $this->strdup($d, ' ');
97		}
98		printf("| %{$width}s ", $data);
99	}
100}
101