GSyncTop   F
last analyzed

Complexity

Total Complexity 159

Size/Duplication

Total Lines 740
Duplicated Lines 0 %

Importance

Changes 14
Bugs 1 Features 0
Metric Value
eloc 405
c 14
b 1
f 0
dl 0
loc 740
rs 2
wmc 159

19 Methods

Rating   Name   Duplication   Size   Complexity  
A IsAvailable() 0 6 3
A __construct() 0 19 3
D processData() 0 93 32
A scrPrintAt() 0 2 1
A scrAsBold() 0 2 1
F scrOverview() 0 189 35
A sec2min() 0 6 2
A scrClear() 0 2 1
A scrHelp() 0 22 1
A getVersion() 0 2 1
A ptStr() 0 11 3
D readLineProcess() 0 133 52
B getLine() 0 9 11
A scrGetSize() 0 8 3
A UsageInstructions() 0 12 1
A initialize() 0 9 1
A scrDefaultColors() 0 2 1
A run() 0 38 5
A SignalHandler() 0 6 2

How to fix   Complexity   

Complex Class

Complex classes like GSyncTop often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GSyncTop, and based on these observations, apply Extract Interface, too.

1
#!/usr/bin/env php
2
<?php
3
/*
4
 * SPDX-License-Identifier: AGPL-3.0-only
5
 * SPDX-FileCopyrightText: Copyright 2007-2016 Zarafa Deutschland GmbH
6
 * SPDX-FileCopyrightText: Copyright 2020-2023 grommunio GmbH
7
 *
8
 * Shows realtime information about connected devices and active connections
9
 * in a top-style format.
10
 */
11
12
require_once 'vendor/autoload.php';
13
if (!defined('GSYNC_CONFIG')) {
14
	define('GSYNC_CONFIG', 'config.php');
15
}
16
17
include_once GSYNC_CONFIG;
18
setlocale(LC_ALL, "");
19
20
/*
21
 * MAIN
22
 */
23
declare(ticks=1);
24
define('BASE_PATH_CLI', dirname(__FILE__) . "/");
25
set_include_path(get_include_path() . PATH_SEPARATOR . BASE_PATH_CLI);
26
27
if (!defined('GSYNC_CONFIG')) {
28
	define('GSYNC_CONFIG', BASE_PATH_CLI . 'config.php');
29
}
30
31
include_once GSYNC_CONFIG;
32
33
try {
34
	GSync::CheckConfig();
35
	if (!function_exists("pcntl_signal")) {
36
		throw new FatalException("Function pcntl_signal() is not available. Please install package 'php8-pcntl' (or similar) on your system.");
37
	}
38
39
	if (php_sapi_name() != "cli") {
40
		throw new FatalException("This script can only be called from the CLI.");
41
	}
42
43
	$zpt = new GSyncTop();
44
45
	// check if help was requested from CLI
46
	if (in_array('-h', $argv) || in_array('--help', $argv)) {
47
		echo $zpt->UsageInstructions();
48
49
		exit(0);
50
	}
51
52
	if ($zpt->IsAvailable()) {
53
		pcntl_signal(SIGINT, [$zpt, "SignalHandler"]);
54
		$zpt->run();
55
		$zpt->scrClear();
56
		system("stty sane");
57
	}
58
	else {
59
		echo "grommunio-sync interprocess communication (IPC) is not available or TopCollector is disabled.\n";
60
	}
61
}
62
catch (GSyncException $zpe) {
63
	fwrite(STDERR, get_class($zpe) . ": " . $zpe->getMessage() . "\n");
64
65
	exit(1);
66
}
67
68
echo "terminated\n";
69
70
/*
71
 * grommunio-sync-top
72
 */
73
class GSyncTop {
74
	// show options
75
	public const SHOW_DEFAULT = 0;
76
	public const SHOW_ACTIVE_ONLY = 1;
77
	public const SHOW_UNKNOWN_ONLY = 2;
78
	public const SHOW_TERM_DEFAULT_TIME = 5; // 5 secs
79
80
	private $topCollector;
81
	private $starttime;
82
	private $currenttime;
83
	private $action;
84
	private $filter;
85
	private $status;
86
	private $statusexpire;
87
	private $helpexpire;
88
	private $doingTail;
89
	private $wide;
90
	private $wasEnabled;
91
	private $terminate;
92
	private $scrSize;
93
	private $pingInterval;
94
	private $showPush;
95
	private $showOption;
96
	private $showTermSec;
97
98
	private $linesActive = [];
99
	private $linesOpen = [];
100
	private $linesUnknown = [];
101
	private $linesTerm = [];
102
	private $pushConn = 0;
103
	private $activeConn = [];
104
	private $activeHosts = [];
105
	private $activeUsers = [];
106
	private $activeDevices = [];
107
108
	/**
109
	 * Constructor.
110
	 */
111
	public function __construct() {
112
		$this->starttime = time();
113
		$this->currenttime = time();
114
		$this->action = "";
115
		$this->filter = false;
116
		$this->status = false;
117
		$this->statusexpire = 0;
118
		$this->helpexpire = 0;
119
		$this->doingTail = false;
120
		$this->wide = false;
121
		$this->terminate = false;
122
		$this->showPush = true;
123
		$this->showOption = self::SHOW_DEFAULT;
124
		$this->showTermSec = self::SHOW_TERM_DEFAULT_TIME;
125
		$this->scrSize = ['width' => 80, 'height' => 24];
126
		$this->pingInterval = (defined('PING_INTERVAL') && PING_INTERVAL > 0) ? PING_INTERVAL : 12;
127
128
		// get a TopCollector
129
		$this->topCollector = new TopCollector();
130
	}
131
132
	/**
133
	 * Requests data from the running grommunio-sync processes.
134
	 */
135
	private function initialize() {
136
		// request feedback from active processes
137
		$this->wasEnabled = $this->topCollector->CollectData();
138
139
		// remove obsolete data
140
		$this->topCollector->ClearLatest(true);
141
142
		// start with default colours
143
		$this->scrDefaultColors();
144
	}
145
146
	/**
147
	 * Main loop of grommunio-sync-top
148
	 * Runs until termination is requested.
149
	 */
150
	public function run() {
151
		$this->initialize();
152
153
		do {
154
			$this->currenttime = time();
155
156
			// see if shared memory is active
157
			if (!$this->IsAvailable()) {
158
				$this->terminate = true;
159
			}
160
161
			// active processes should continue sending data
162
			$this->topCollector->CollectData();
163
164
			// get and process data from processes
165
			$this->topCollector->ClearLatest();
166
			$topdata = $this->topCollector->ReadLatest();
167
			$this->processData($topdata);
168
169
			// check if screen size changed
170
			$s = $this->scrGetSize();
171
			if ($this->scrSize['width'] != $s['width']) {
172
				if ($s['width'] > 180) {
173
					$this->wide = true;
174
				}
175
				else {
176
					$this->wide = false;
177
				}
178
			}
179
			$this->scrSize = $s;
180
181
			// print overview
182
			$this->scrOverview();
183
184
			// wait for user input
185
			$this->readLineProcess();
186
		}
187
		while ($this->terminate !== true);
188
	}
189
190
	/**
191
	 * Indicates if TopCollector is available collecting data.
192
	 *
193
	 * @return bool
194
	 */
195
	public function IsAvailable() {
196
		if (defined('TOPCOLLECTOR_DISABLED') && constant('TOPCOLLECTOR_DISABLED') === true) {
197
			return false;
198
		}
199
200
		return $this->topCollector->IsActive();
201
	}
202
203
	/**
204
	 * Processes data written by the running processes.
205
	 *
206
	 * @param array $data
207
	 */
208
	private function processData($data) {
209
		$this->linesActive = [];
210
		$this->linesOpen = [];
211
		$this->linesUnknown = [];
212
		$this->linesTerm = [];
213
		$this->pushConn = 0;
214
		$this->activeConn = [];
215
		$this->activeHosts = [];
216
		$this->activeUsers = [];
217
		$this->activeDevices = [];
218
219
		if (!is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
220
			return;
221
		}
222
223
		foreach ($data as $devid => $users) {
224
			foreach ($users as $user => $pids) {
225
				foreach ($pids as $pid => $line) {
226
					if (!is_array($line)) {
227
						continue;
228
					}
229
230
					$line['command'] = Utils::GetCommandFromCode($line['command']);
231
232
					if ($line["ended"] == 0) {
233
						$this->activeDevices[$devid] = 1;
234
						$this->activeUsers[$user] = 1;
235
						$this->activeConn[$pid] = 1;
236
						$this->activeHosts[$line['ip']] = 1;
237
238
						$line["time"] = $this->currenttime - $line['start'];
239
						if ($line['push'] === true) {
240
							++$this->pushConn;
241
						}
242
243
						// ignore push connections
244
						if ($line['push'] === true && !$this->showPush) {
245
							continue;
246
						}
247
248
						if ($this->filter !== false) {
249
							$f = $this->filter;
250
							if (!($line["pid"] == $f || $line["ip"] == $f || strtolower($line['command']) == strtolower($f) || preg_match("/.*?{$f}.*?/i", $line['user']) ||
0 ignored issues
show
Bug introduced by
$f of type true is incompatible with the type string expected by parameter $string of strtolower(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

250
							if (!($line["pid"] == $f || $line["ip"] == $f || strtolower($line['command']) == strtolower(/** @scrutinizer ignore-type */ $f) || preg_match("/.*?{$f}.*?/i", $line['user']) ||
Loading history...
251
								preg_match("/.*?{$f}.*?/i", $line['devagent']) || preg_match("/.*?{$f}.*?/i", $line['devid']) || preg_match("/.*?{$f}.*?/i", $line['addinfo']))) {
252
								continue;
253
							}
254
						}
255
256
						$lastUpdate = $this->currenttime - $line["update"];
257
						if ($this->currenttime - $line["update"] < 2) {
258
							$this->linesActive[$line["update"] . $line["pid"]] = $line;
259
						}
260
						elseif (($line['push'] === true && $lastUpdate > ($this->pingInterval + 2)) || ($line['push'] !== true && $lastUpdate > 4)) {
261
							$this->linesUnknown[$line["update"] . $line["pid"]] = $line;
262
						}
263
						else {
264
							$this->linesOpen[$line["update"] . $line["pid"]] = $line;
265
						}
266
					}
267
					else {
268
						// do not show terminated + expired connections
269
						if ($this->currenttime > $line['ended'] + $this->showTermSec) {
270
							continue;
271
						}
272
273
						if ($this->filter !== false) {
274
							$f = $this->filter;
275
							if (
276
								!(
277
									$line['pid'] == $f ||
278
									$line['ip'] == $f ||
279
									strtolower($line['command']) == strtolower($f) ||
280
									preg_match("/.*?{$f}.*?/i", $line['user']) ||
281
									preg_match("/.*?{$f}.*?/i", $line['devagent']) ||
282
									preg_match("/.*?{$f}.*?/i", $line['devid']) ||
283
									preg_match("/.*?{$f}.*?/i", $line['addinfo'])
284
								)) {
285
								continue;
286
							}
287
						}
288
289
						$line['time'] = $line['ended'] - $line['start'];
290
						$this->linesTerm[$line['update'] . $line['pid']] = $line;
291
					}
292
				}
293
			}
294
		}
295
296
		// sort by execution time
297
		krsort($this->linesActive);
298
		krsort($this->linesOpen);
299
		krsort($this->linesUnknown);
300
		krsort($this->linesTerm);
301
	}
302
303
	/**
304
	 * Prints data to the terminal.
305
	 */
306
	private function scrOverview() {
307
		$linesAvail = $this->scrSize['height'] - 7;
308
		$lc = 1;
309
		echo "\e[?25l\e[1;1H";
310
		$this->scrPrintAt($lc, 0, sprintf(
311
			"grommunio-sync-top live stats (%s, Gromox %s) %s\n",
312
			$this->getVersion(),
313
			phpversion("mapi"),
314
			date("Y-m-d H:i:s")
315
		));
316
		++$lc;
317
318
		$this->scrPrintAt($lc, 0, sprintf(
319
			"Conn: \e[1m%4d\e[0m open, \e[1m%4d\e[0m push; " .
320
			"\e[1m%4d\e[0m users, \e[1m%4d\e[0m devices, \e[1m%4d\e[0m hosts\n",
321
			count($this->activeConn),
322
			$this->pushConn,
323
			count($this->activeUsers),
324
			count($this->activeDevices),
325
			count($this->activeHosts)
326
		));
327
		++$lc;
328
329
		// remove old status
330
		if ($this->statusexpire < $this->currenttime) {
331
			$this->status = false;
332
		}
333
334
		// show request information and help command
335
		if ($this->starttime + 6 > $this->currenttime) {
336
			$this->status = sprintf("Requesting information (takes up to %dsecs)", $this->pingInterval) . str_repeat(".", $this->currenttime - $this->starttime) . "  type \033[01;31mh\033[00;31m or \033[01;31mhelp\033[00;31m for usage instructions";
337
			$this->statusexpire = $this->currenttime + 1;
338
		}
339
340
		$str = "";
341
		if (!$this->showPush) {
342
			$str .= "\033[00;32mPush: \033[01;32mNo\033[0m   ";
343
		}
344
345
		if ($this->showOption == self::SHOW_ACTIVE_ONLY) {
346
			$str .= "\033[01;32mActive only\033[0m   ";
347
		}
348
349
		if ($this->showOption == self::SHOW_UNKNOWN_ONLY) {
350
			$str .= "\033[01;32mUnknown only\033[0m   ";
351
		}
352
353
		if ($this->showTermSec != self::SHOW_TERM_DEFAULT_TIME) {
354
			$str .= "\033[01;32mTerminated: " . $this->showTermSec . "s\033[0m   ";
355
		}
356
357
		if ($this->filter !== false || ($this->status !== false && $this->statusexpire > $this->currenttime)) {
358
			// print filter in green
359
			if ($this->filter !== false) {
360
				$str .= "\033[00;32mFilter: \033[01;32m{$this->filter}\033[0m   ";
361
			}
362
			// print status in red
363
			if ($this->status !== false) {
364
				$str .= "\033[00;31m{$this->status}\033[0m";
365
			}
366
		}
367
		$this->scrPrintAt($lc, 0, "Action: \033[01m" . $this->action . "\033[0m\n");
368
		++$lc;
369
		$this->scrPrintAt($lc, 0, $str . "\n");
370
		++$lc;
371
		$header = $this->getLine(['pid' => 'PID', 'ip' => 'ADDRESS', 'user' => 'USER', 'command' => 'COMMAND', 'time' => 'TIME', 'devagent' => 'AGENT', 'devid' => 'DEVID', 'addinfo' => 'Additional Information', 'asversion' => 'EAS']);
372
		$this->scrPrintAt($lc, 0, "\033[7m" . $header . str_repeat(" ", $this->scrSize['width'] - ($this->scrSize['width'] > strlen($header) ? strlen($header) : 0)) . "\033[0m\n");
373
		++$lc;
374
375
		if ($linesAvail < 1) {
376
			echo "Terminal too small, no room to display any useful information.";
377
			++$lc;
378
379
			return;
380
		}
381
382
		// print help text if requested
383
		$help = false;
384
		if ($this->helpexpire > $this->currenttime) {
385
			$help = $this->scrHelp();
386
			$linesAvail -= (count($help) + 1);
387
		}
388
389
		$toPrintActive = $linesAvail;
390
		$toPrintOpen = $linesAvail;
391
		$toPrintUnknown = $linesAvail;
392
		$toPrintTerm = $linesAvail;
393
394
		// default view: show all unknown, no terminated and half active+open
395
		if (count($this->linesActive) + count($this->linesOpen) + count($this->linesUnknown) > $linesAvail) {
396
			$toPrintUnknown = count($this->linesUnknown);
397
			$toPrintActive = count($this->linesActive);
398
			$toPrintOpen = $linesAvail - $toPrintUnknown - $toPrintActive;
399
			$toPrintTerm = 0;
400
		}
401
402
		if ($this->showOption == self::SHOW_ACTIVE_ONLY) {
403
			$toPrintActive = $linesAvail;
404
			$toPrintOpen = 0;
405
			$toPrintUnknown = 0;
406
			$toPrintTerm = 0;
407
		}
408
409
		if ($this->showOption == self::SHOW_UNKNOWN_ONLY) {
410
			$toPrintActive = 0;
411
			$toPrintOpen = 0;
412
			$toPrintUnknown = $linesAvail;
413
			$toPrintTerm = 0;
414
		}
415
416
		$linesprinted = 0;
417
		foreach ($this->linesActive as $time => $l) {
418
			if ($linesprinted >= $toPrintActive) {
419
				break;
420
			}
421
422
			$this->scrPrintAt($lc, 0, "\033[01m" . $this->getLine($l) . "\033[0m\n");
423
			++$lc;
424
			++$linesprinted;
425
		}
426
427
		$linesprinted = 0;
428
		foreach ($this->linesOpen as $time => $l) {
429
			if ($linesprinted >= $toPrintOpen) {
430
				break;
431
			}
432
433
			$this->scrPrintAt($lc, 0, $this->getLine($l) . "\n");
434
			++$lc;
435
			++$linesprinted;
436
		}
437
438
		$linesprinted = 0;
439
		foreach ($this->linesUnknown as $time => $l) {
440
			if ($linesprinted >= $toPrintUnknown) {
441
				break;
442
			}
443
			$time = intval($time);
444
			$color = "0;31m";
445
			if (!isset($l['start'])) {
446
				$l['start'] = $time;
447
			}
448
			if ((!isset($l['push']) || $l['push'] == false) && $time - $l["start"] > 30) {
449
				$color = "1;31m";
450
			}
451
			$this->scrPrintAt($lc, 0, "\033[0" . $color . $this->getLine($l) . "\033[0m\n");
452
			++$lc;
453
			++$linesprinted;
454
		}
455
456
		if ($toPrintTerm > 0) {
457
			$toPrintTerm = $linesAvail - $lc + 5;
458
		}
459
460
		$linesprinted = 0;
461
		foreach ($this->linesTerm as $time => $l) {
462
			if ($linesprinted >= $toPrintTerm) {
463
				break;
464
			}
465
466
			$this->scrPrintAt($lc, 0, "\033[01;30m" . $this->getLine($l) . "\033[0m\n");
467
			++$lc;
468
			++$linesprinted;
469
		}
470
471
		// add the lines used when displaying the help text
472
		if ($help !== false) {
473
			while ($lc < $linesAvail + 7) {
474
				$this->scrPrintAt($lc, 0, "\033[K\n");
475
				++$lc;
476
			}
477
			if ($linesAvail < 1) {
478
				$this->scrPrintAt($lc, 0, "Can't display help text, terminal has not enough lines. Use -h or --help to see help information. \n");
479
				++$lc;
480
			}
481
			else {
482
				foreach ($help as $h) {
483
					$this->scrPrintAt($lc, 0, $h . "\n");
484
					++$lc;
485
				}
486
			}
487
		}
488
		$this->scrPrintAt($lc, 0, "\033[K\n");
489
		++$lc;
490
		$this->scrPrintAt($lc, 0, "Colorscheme: \033[01mActive  \033[0mOpen  \033[01;31mUnknown  \033[01;30mTerminated\033[0m");
491
		/* Clear rest of area */
492
		echo "\e[J";
493
		/* Reposition cursor to Action: line */
494
		printf("\e[3;%dH\e[?25h", 9 + strlen($this->action));
495
	}
496
497
	/**
498
	 * Waits for a keystroke and processes the requested command.
499
	 */
500
	private function readLineProcess() {
501
		$ans = explode("^^", `bash -c "read -n 1 -t 1 ANS ; echo \\\$?^^\\\$ANS;"`);
502
503
		if ($ans[0] < 128) {
504
			if (isset($ans[1]) && bin2hex(trim($ans[1])) == "7f") {
505
				$this->action = substr($this->action, 0, -1);
506
			}
507
508
			if (isset($ans[1]) && $ans[1] != "") {
509
				$this->action .= trim(preg_replace("/[^A-Za-z0-9:]/", "", $ans[1]));
510
			}
511
512
			if (bin2hex($ans[0]) == "30" && bin2hex($ans[1]) == "0a") {
513
				$cmds = explode(':', $this->action);
514
				if ($cmds[0] == "quit" || $cmds[0] == "q" || (isset($cmds[1]) && $cmds[0] == "" && $cmds[1] == "q")) {
515
					$this->topCollector->CollectData(true);
516
					$this->topCollector->ClearLatest(true);
517
518
					$this->terminate = true;
519
				}
520
				elseif ($cmds[0] == "clear") {
521
					$this->topCollector->ClearLatest(true);
522
					$this->topCollector->CollectData(true);
523
					$this->topCollector->ReInitIPC();
524
				}
525
				elseif ($cmds[0] == "filter" || $cmds[0] == "f") {
526
					if (!isset($cmds[1]) || $cmds[1] == "") {
527
						$this->filter = false;
528
						$this->status = "No filter";
529
						$this->statusexpire = $this->currenttime + 5;
530
					}
531
					else {
532
						$this->filter = $cmds[1];
533
						$this->status = false;
534
					}
535
				}
536
				elseif ($cmds[0] == "option" || $cmds[0] == "o") {
537
					if (!isset($cmds[1]) || $cmds[1] == "") {
538
						$this->status = "Option value needs to be specified. See 'help' or 'h' for instructions";
539
						$this->statusexpire = $this->currenttime + 5;
540
					}
541
					elseif ($cmds[1] == "p" || $cmds[1] == "push" || $cmds[1] == "ping") {
542
						$this->showPush = !$this->showPush;
543
					}
544
					elseif ($cmds[1] == "a" || $cmds[1] == "active") {
545
						$this->showOption = self::SHOW_ACTIVE_ONLY;
546
					}
547
					elseif ($cmds[1] == "u" || $cmds[1] == "unknown") {
548
						$this->showOption = self::SHOW_UNKNOWN_ONLY;
549
					}
550
					elseif ($cmds[1] == "d" || $cmds[1] == "default") {
551
						$this->showOption = self::SHOW_DEFAULT;
552
						$this->showTermSec = self::SHOW_TERM_DEFAULT_TIME;
553
						$this->showPush = true;
554
					}
555
					elseif (is_numeric($cmds[1])) {
556
						$this->showTermSec = $cmds[1];
557
					}
558
					else {
559
						$this->status = sprintf("Option '%s' unknown", $cmds[1]);
560
						$this->statusexpire = $this->currenttime + 5;
561
					}
562
				}
563
				elseif ($cmds[0] == "reset" || $cmds[0] == "r") {
564
					$this->filter = false;
565
					$this->wide = false;
566
					$this->helpexpire = 0;
567
					$this->status = "reset";
568
					$this->statusexpire = $this->currenttime + 2;
569
				}
570
				// enable/disable wide view
571
				elseif ($cmds[0] == "wide" || $cmds[0] == "w") {
572
					$this->wide = !$this->wide;
573
					$this->status = ($this->wide) ? "w i d e  view" : "normal view";
574
					$this->statusexpire = $this->currenttime + 2;
575
				}
576
				elseif ($cmds[0] == "help" || $cmds[0] == "h") {
577
					$this->helpexpire = $this->currenttime + 20;
578
				}
579
				// grep the log file
580
				elseif (($cmds[0] == "log" || $cmds[0] == "l") && isset($cmds[1])) {
581
					if (!file_exists(LOGFILE)) {
582
						$this->status = "Logfile can not be found: " . LOGFILE;
583
					}
584
					else {
585
						system('bash -c "fgrep -a ' . escapeshellarg($cmds[1]) . ' ' . LOGFILE . ' | less +G" > `tty`');
586
						$this->status = "Returning from log, updating data";
587
					}
588
					$this->statusexpire = time() + 5; // it might be much "later" now
589
				}
590
				// tail the log file
591
				elseif ($cmds[0] == "tail" || $cmds[0] == "t") {
592
					if (!file_exists(LOGFILE)) {
593
						$this->status = "Logfile can not be found: " . LOGFILE;
594
					}
595
					else {
596
						$this->doingTail = true;
597
						$this->scrClear();
598
						$this->scrPrintAt(1, 0, $this->scrAsBold("Press CTRL+C to return to grommunio-sync-top\n\n"));
599
						$secondary = "";
600
						if (isset($cmds[1])) {
601
							$secondary = " -n 200 | grep " . escapeshellarg($cmds[1]);
602
						}
603
						system('bash -c "tail -f ' . LOGFILE . $secondary . '" > `tty`');
604
						$this->doingTail = false;
605
						$this->status = "Returning from tail, updating data";
606
					}
607
					$this->statusexpire = time() + 5; // it might be much "later" now
608
				}
609
				// tail the error log file
610
				elseif ($cmds[0] == "error" || $cmds[0] == "e") {
611
					if (!file_exists(LOGERRORFILE)) {
612
						$this->status = "Error logfile can not be found: " . LOGERRORFILE;
613
					}
614
					else {
615
						$this->doingTail = true;
616
						$this->scrClear();
617
						$this->scrPrintAt(1, 0, $this->scrAsBold("Press CTRL+C to return to grommunio-sync-top\n\n"));
618
						$secondary = "";
619
						if (isset($cmds[1])) {
620
							$secondary = " -n 200 | grep " . escapeshellarg($cmds[1]);
621
						}
622
						system('bash -c "tail -f ' . LOGERRORFILE . $secondary . '" > `tty`');
623
						$this->doingTail = false;
624
						$this->status = "Returning from tail, updating data";
625
					}
626
					$this->statusexpire = time() + 5; // it might be much "later" now
627
				}
628
				elseif ($cmds[0] != "") {
629
					$this->status = sprintf("Command '%s' unknown", $cmds[0]);
630
					$this->statusexpire = $this->currenttime + 8;
631
				}
632
				$this->action = "";
633
			}
634
		}
635
	}
636
637
	/**
638
	 * Signal handler function.
639
	 *
640
	 * @param int $signo signal number
641
	 */
642
	public function SignalHandler($signo) {
0 ignored issues
show
Unused Code introduced by
The parameter $signo is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

642
	public function SignalHandler(/** @scrutinizer ignore-unused */ $signo) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
643
		// don't terminate if the signal was sent by terminating tail
644
		if (!$this->doingTail) {
645
			$this->topCollector->CollectData(true);
646
			$this->topCollector->ClearLatest(true);
647
			$this->terminate = true;
648
		}
649
	}
650
651
	/**
652
	 * Returns usage instructions.
653
	 *
654
	 * @return string
655
	 */
656
	public function UsageInstructions() {
657
		$help = "Usage:\n\tgrommunio-sync-top\n\n" .
658
				"  grommunio-sync-top is a live top-like overview of what grommunio-sync is doing. It does not have specific command line options.\n\n" .
659
				"  When grommunio-sync-top is running you can specify certain actions and options which can be executed (listed below).\n" .
660
				"  This help information can also be shown inside grommunio-sync-top by hitting 'help' or 'h'.\n\n";
661
		$scrhelp = $this->scrHelp();
662
		unset($scrhelp[0]);
663
664
		$help .= implode("\n", $scrhelp);
665
		$help .= "\n\n";
666
667
		return $help;
668
	}
669
670
	/**
671
	 * Prints a 'help' text at the end of the page.
672
	 *
673
	 * @return array with help lines
674
	 */
675
	private function scrHelp() {
676
		$h = [];
677
		$secs = $this->helpexpire - $this->currenttime;
678
		$h[] = "Actions supported by grommunio-sync-top (help page still displayed for " . $secs . "secs)";
679
		$h[] = "  " . $this->scrAsBold("Action") . "                " . $this->scrAsBold("Comment");
680
		$h[] = "  " . $this->scrAsBold("h") . " or " . $this->scrAsBold("help") . "             Displays this information.";
681
		$h[] = "  " . $this->scrAsBold("q") . ", " . $this->scrAsBold("quit") . " or " . $this->scrAsBold(":q") . "         Exits grommunio-sync-top.";
682
		$h[] = "  " . $this->scrAsBold("w") . " or " . $this->scrAsBold("wide") . "             Tries not to truncate data. Automatically done if more than 180 columns available.";
683
		$h[] = "  " . $this->scrAsBold("f:VAL") . " or " . $this->scrAsBold("filter:VAL") . "   Only display connections which contain VAL. This value is case-insensitive.";
684
		$h[] = "  " . $this->scrAsBold("f:") . " or " . $this->scrAsBold("filter:") . "         Without a search word: resets the filter.";
685
		$h[] = "  " . $this->scrAsBold("l:STR") . " or " . $this->scrAsBold("log:STR") . "      Issues 'less +G' on the logfile, after grepping on the optional STR.";
686
		$h[] = "  " . $this->scrAsBold("t:STR") . " or " . $this->scrAsBold("tail:STR") . "     Issues 'tail -f' on the logfile, grepping for optional STR.";
687
		$h[] = "  " . $this->scrAsBold("e:STR") . " or " . $this->scrAsBold("error:STR") . "    Issues 'tail -f' on the error logfile, grepping for optional STR.";
688
		$h[] = "  " . $this->scrAsBold("r") . " or " . $this->scrAsBold("reset") . "            Resets 'wide' or 'filter'.";
689
		$h[] = "  " . $this->scrAsBold("o:") . " or " . $this->scrAsBold("option:") . "         Sets display options. Valid options specified below";
690
		$h[] = "  " . $this->scrAsBold("  p") . " or " . $this->scrAsBold("push") . "           Lists/not lists active and open push connections.";
691
		$h[] = "  " . $this->scrAsBold("  a") . " or " . $this->scrAsBold("action") . "         Lists only active connections.";
692
		$h[] = "  " . $this->scrAsBold("  u") . " or " . $this->scrAsBold("unknown") . "        Lists only unknown connections.";
693
		$h[] = "  " . $this->scrAsBold("  10") . " or " . $this->scrAsBold("20") . "            Lists terminated connections for 10 or 20 seconds. Any other number can be used.";
694
		$h[] = "  " . $this->scrAsBold("  d") . " or " . $this->scrAsBold("default") . "        Uses default options";
695
696
		return $h;
697
	}
698
699
	/**
700
	 * Encapsulates string with different color escape characters.
701
	 *
702
	 * @param string $text
703
	 *
704
	 * @return string same text as bold
705
	 */
706
	private function scrAsBold($text) {
707
		return "\033[01m" . $text . "\033[0m";
708
	}
709
710
	/**
711
	 * Prints one line of precessed data.
712
	 *
713
	 * @param array $l line information
714
	 *
715
	 * @return string
716
	 */
717
	private function getLine($l) {
718
		if (!isset($l['pid']) || !isset($l['ip']) || !isset($l['user']) || !isset($l['command']) || !isset($l['time']) || !isset($l['devagent']) || !isset($l['devid']) || !isset($l['addinfo']) || !isset($l['asversion'])) {
719
			return "";
720
		}
721
		if ($this->wide === true) {
722
			return sprintf("%s%s%s%s%s%s%s%s%s", $this->ptStr($l['pid'], 7), $this->ptStr($l['ip'], 40), $this->ptStr($l['user'], 24), $this->ptStr($l['command'], 16), $this->ptStr($this->sec2min($l['time']), 8), $this->ptStr($l['devagent'], 28), $this->ptStr($l['asversion'], 5), $this->ptStr($l['devid'], 33, true), $l['addinfo']);
723
		}
724
725
		return sprintf("%s%s%s%s%s%s%s%s%s", $this->ptStr($l['pid'], 7), $this->ptStr($l['ip'], 16), $this->ptStr($l['user'], 8), $this->ptStr($l['command'], 8), $this->ptStr($this->sec2min($l['time']), 6), $this->ptStr($l['devagent'], 20), $this->ptStr($l['asversion'], 5), $this->ptStr($l['devid'], 12, true), $l['addinfo']);
726
	}
727
728
	/**
729
	 * Pads and trims string.
730
	 *
731
	 * @param string $str       to be trimmed/padded
732
	 * @param int    $size      characters to be considered
733
	 * @param bool   $cutmiddle (optional) indicates where to long information should
734
	 *                          be trimmed of, false means at the end
735
	 *
736
	 * @return string
737
	 */
738
	private function ptStr($str, $size, $cutmiddle = false) {
739
		if (strlen($str) < $size) {
740
			return str_pad($str, $size);
741
		}
742
		if ($cutmiddle === true) {
743
			$cut = ($size - 2) / 2;
744
745
			return $this->ptStr(substr($str, 0, $cut) . ".." . substr($str, (-1) * ($cut - 1)), $size);
746
		}
747
748
		return substr($str, 0, $size - 3) . ".. ";
749
	}
750
751
	/**
752
	 * Tries to discover the size of the current terminal.
753
	 *
754
	 * @return array 'width' and 'height' as keys
755
	 */
756
	private function scrGetSize() {
757
		$tty = strtolower(exec('stty -a | fgrep columns'));
758
		if (preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", $tty, $output) ||
759
			preg_match_all("/([0-9]+).rows;.([0-9]+).columns;/", $tty, $output)) {
760
			return ['width' => $output[2][0], 'height' => $output[1][0]];
761
		}
762
763
		return ['width' => 80, 'height' => 24];
764
	}
765
766
	/**
767
	 * Returns the version of the current grommunio-sync installation.
768
	 *
769
	 * @return string
770
	 */
771
	private function getVersion() {
772
		return GROMMUNIOSYNC_VERSION;
773
	}
774
775
	/**
776
	 * Converts seconds in MM:SS.
777
	 *
778
	 * @param int $s seconds
779
	 *
780
	 * @return string
781
	 */
782
	private function sec2min($s) {
783
		if (!is_int($s)) {
0 ignored issues
show
introduced by
The condition is_int($s) is always true.
Loading history...
784
			return $s;
785
		}
786
787
		return sprintf("%02.2d:%02.2d", floor($s / 60), $s % 60);
788
	}
789
790
	/**
791
	 * Resets the default colors of the terminal.
792
	 */
793
	private function scrDefaultColors() {
794
		echo "\033[0m";
795
	}
796
797
	/**
798
	 * Clears screen of the terminal.
799
	 */
800
	public function scrClear() {
801
		echo "\033[2J";
802
	}
803
804
	/**
805
	 * Prints a text at a specific screen/terminal coordinates.
806
	 *
807
	 * @param int    $row  row number
808
	 * @param int    $col  column number
809
	 * @param string $text to be printed
810
	 */
811
	private function scrPrintAt($row, $col, $text = "") {
812
		echo "\033[" . $row . ";" . $col . "H" . preg_replace("/\n/", "\e[K\n", $text);
813
	}
814
}
815