1<?php
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 CUpdateDiscoveredValidator extends CValidator implements CPartialValidatorInterface {
23
24	/**
25	 * Fields that can be updated for discovered objects. If no fields are set, updating discovered objects
26	 * will be forbidden.
27	 *
28	 * @var array
29	 */
30	public $allowed = [];
31
32	/**
33	 * Error message in case updating discovered objects is totally forbidden.
34	 *
35	 * @var string
36	 */
37	public $messageAllowed;
38
39	/**
40	 * Error message in case we can update only certain fields for discovered objects.
41	 *
42	 * @var string
43	 */
44	public $messageAllowedField;
45
46	/**
47	 * Checks that only the allowed fields for discovered objects are updated.
48	 *
49	 * The object must have the "flags" property defined.
50	 *
51	 * @param array $object
52	 *
53	 * @return bool
54	 */
55	public function validate($object) {
56		$allowedFields = array_flip($this->allowed);
57
58		if ($object['flags'] == ZBX_FLAG_DISCOVERY_CREATED) {
59			// ignore the "flags" field
60			unset($object['flags']);
61
62			foreach ($object as $field => $value) {
63				if (!isset($allowedFields[$field])) {
64					// if we allow to update some fields, throw an error referencing a specific field
65					// we check if there is more than 1 field, because the PK must always be present
66					if (count($allowedFields) > 1) {
67						$this->error($this->messageAllowedField, $field);
68					}
69					else {
70						$this->error($this->messageAllowed);
71					}
72
73					return false;
74				}
75			}
76		}
77
78		return true;
79	}
80
81	public function validatePartial(array $array, array $fullArray) {
82		$array['flags'] = $fullArray['flags'];
83
84		return $this->validate($array);
85	}
86
87}
88