summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Cli/Screen.php
blob: 4ffad723e1a2f47382fb523028de5a19ecae59f3 (plain)
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
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Cli;

use Icinga\Cli\AnsiScreen;

class Screen
{
    protected static $instances = [];

    protected $isUtf8;

    public function getColumns()
    {
        $cols = (int) getenv('COLUMNS');
        if (! $cols) {
            // stty -a ?
            $cols = (int) exec('tput cols');
        }
        if (! $cols) {
            $cols = 80;
        }
        return $cols;
    }

    public function getRows()
    {
        $rows = (int) getenv('ROWS');
        if (! $rows) {
            // stty -a ?
            $rows = (int) exec('tput lines');
        }
        if (! $rows) {
            $rows = 25;
        }
        return $rows;
    }

    public function strlen($string)
    {
        return strlen($string);
    }

    public function newlines($count = 1)
    {
        return str_repeat("\n", $count);
    }

    public function center($txt)
    {
        $len = $this->strlen($txt);
        $width = floor(($this->getColumns() + $len) / 2) - $len;
        return str_repeat(' ', $width) . $txt;
    }

    public function hasUtf8()
    {
        if ($this->isUtf8 === null) {
            // null should equal 0 here, however seems to equal '' on some systems:
            $current = setlocale(LC_ALL, 0);

            $parts = preg_split('/;/', $current);
            $lc_parts = array();
            foreach ($parts as $part) {
                if (strpos($part, '=') === false) {
                    continue;
                }
                list($key, $val) = preg_split('/=/', $part, 2);
                $lc_parts[$key] = $val;
            }

            $this->isUtf8 = array_key_exists('LC_CTYPE', $lc_parts)
                && preg_match('~\.UTF-8$~i', $lc_parts['LC_CTYPE']);
        }
        return $this->isUtf8;
    }

    public function clear()
    {
        return "\n";
    }

    public function underline($text)
    {
        return $text;
    }

    public function colorize($text, $fgColor = null, $bgColor = null)
    {
        return $text;
    }

    public static function instance($output = STDOUT)
    {
        if (! isset(self::$instances[(int) $output])) {
            if (function_exists('posix_isatty') && posix_isatty($output)) {
                self::$instances[(int) $output] = new AnsiScreen();
            } else {
                self::$instances[(int) $output] = new Screen();
            }
        }

        return self::$instances[(int) $output];
    }
}