summaryrefslogtreecommitdiffstats
path: root/modules-available/rebootcontrol/inc/exectemplate.inc.php
blob: 483dc31fb4786d326b7c4a31202922935f1c7a22 (plain) (blame)
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
declare(strict_types=1);

class ExecTemplate
{

	/** @var string */
	public $id;
	/** @var string */
	public $title;
	/** @var string */
	public $command;
	/** @var ExecTemplateField[] */
	public $args;

	public function __construct(string $id, string $title, string $command, array $args)
	{
		$this->id = $id;
		$this->title = $title;
		$this->command = $command;
		$this->args = $args;
	}

	public function buildFromPost(): string
	{
		$args = [];
		foreach ($this->args as $arg) {
			$args[$arg->id] = Request::post('param-' . $arg->id, '', 'string');
		}
		return preg_replace_callback('/%([0-9]+)([a-z]*)%/', function($out) use ($args) {
			if (!isset($args[$out[1]])) {
				ErrorHandler::traceError('Invalid Argument Index: ' . $out[1]);
			}
			$str = preg_replace('/\r\n?/', "\n", $args[$out[1]]);
			if (strpos($out[2], 'r') === false) {
				$str = $this->bashString($str);
			}
			return $str;
		}, $this->command);
	}

	private function bashString(string $string): string
	{
		if (strpos($string, "'") === false) {
			return "'$string'";
		}
		return "'" . str_replace("'", "'\\''", $string) . "'";
	}

	// ## STATIC ##

	public static function get(string $id): ?ExecTemplate
	{
		// TODO: some day, maybe put these in a json file? Or DB and allow user defined ones...
		// XXX: Add to list() too if you add something here
		if ($id === '1') {
			return new ExecTemplate('1', Dictionary::translateFileModule('rebootcontrol', 'module', 'exec_debug_report'),
				'debug_report --message %1%',
				[new ExecTemplateField('1', Dictionary::translateFileModule('rebootcontrol', 'module', 'exec_debug_report_message'), 'string')],
			);
		}
		if ($id === '2') {
			return new ExecTemplate('2', Dictionary::translateFileModule('rebootcontrol', 'module', 'exec_systemd_plot'),
				'systemd-analyze plot',
				[],
			);
		}
		return null;
	}

	/**
	 * @return ExecTemplate[]
	 */
	public static function list(): array
	{
		return [self::get('1'), self::get('2')];
	}

}

class ExecTemplateField
{

	/** @var string */
	private $type;
	/** @var string */
	public $title;
	/** @var string */
	public $id;

	public function __construct(string $id, string $title, string $type)
	{
		$this->id = $id;
		$this->title = $title;
		$this->type = $type;
	}

	public function render(): string
	{
		if ($this->type === 'string') {
			return '<input type="text" class="form-control" name="param-' . $this->id . '">';
		}
		return '<div>???</div>';
	}

}