1<?php declare(strict_types = 1);
2/*
3** Zabbix
4** Copyright (C) 2001-2021 Zabbix SIA
5**
6** This program is free software; you can redistribute it and/or modify
7** it under the terms of the GNU General Public License as published by
8** the Free Software Foundation; either version 2 of the License, or
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
16** You should have received a copy of the GNU General Public License
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19**/
20
21
22class CInputSecret extends CInput {
23
24	/**
25	 * Default CSS class name for HTML root element.
26	 */
27	public const ZBX_STYLE_CLASS = 'input-secret';
28
29	/**
30	 * Style for change value button.
31	 */
32	public const ZBX_STYLE_BTN_CHANGE = 'btn-change';
33
34	/**
35	 * Add initialization javascript code.
36	 *
37	 * @var bool
38	 */
39	protected $add_post_js;
40
41	/**
42	 * CInputSecret constructor.
43	 *
44	 * @param string $name         Input element name attribute.
45	 * @param string $value        Input element value attribute.
46	 * @param bool   $add_post_js  Add initialization javascript, default true.
47	 */
48	public function __construct(string $name, string $value = null, $add_post_js = true) {
49		$this->add_post_js = $add_post_js;
50		$this->setAttribute('name', $name);
51		$this->setId(uniqid('input-secret-'));
52
53		if ($value !== null) {
54			$this->setAttribute('value', $value);
55		}
56	}
57
58	/**
59	 * Get content of all Javascript code.
60	 *
61	 * @return string  Javascript code.
62	 */
63	public function getPostJS(): string {
64		return 'jQuery("#'.$this->getId().'").inputSecret();';
65	}
66
67	public function toString($destroy = true) {
68		$node = (new CDiv())
69			->setId($this->getId())
70			->addClass(self::ZBX_STYLE_CLASS);
71		$name = $this->getAttribute('name');
72
73		if ($this->getAttribute('value') !== null) {
74			$node->addItem(new CPassBox($name, $this->getAttribute('value')));
75		}
76		else {
77			$node->addItem([
78				(new CPassBox($name, ZBX_SECRET_MASK))->setAttribute('disabled', 'disabled'),
79				(new CButton(null, _('Set new value')))
80					->setId(zbx_formatDomId($name.'[btn]'))
81					->setAttribute('disabled', $this->getAttribute('disabled'))
82					->addClass(self::ZBX_STYLE_BTN_CHANGE)
83			]);
84		}
85
86		if ($this->add_post_js) {
87			zbx_add_post_js($this->getPostJS());
88		}
89
90		return $node->toString(true);
91	}
92}
93