Debian Codegraph @

lib/modules/puppetClient.inc

raw
1 <?php
2
3 use LAM\PDF\PDFTable;
4 use LAM\PDF\PDFTableCell;
5 use LAM\PDF\PDFTableRow;
6 use LAM\TYPES\ConfiguredType;
7
8 /*
9
10 This code is not yet part of LDAP Account Manager (http://www.ldap-account-manager.org/)
11 Copyright (C) 2012 - 2026 Roland Gruber
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26
27 */
28
29
30 /**
31 * Manages Puppet configuration options.
32 *
33 * @package modules
34 * @author Roland Gruber
35 */
36
37 /**
38 * Manages Puppet configuration options.
39 *
40 * @package modules
41 */
42 class puppetClient extends baseModule {
43
44 /** @var string[]|null $classCache cache for classes */
45 private ?array $classCache = null;
46 /** @var string[]|null $variablesCache cache for variables */
47 private ?array $variablesCache = null;
48
49 /**
50 * Creates a new authorizedServiceObject object.
51 *
52 * @param string $scope account type (user, group, host)
53 */
54 public function __construct($scope) {
55 // call parent constructor
56 parent::__construct($scope);
57 $this->autoAddObjectClasses = false;
58 }
59
60
61 /**
62 * {@inheritDoc}
63 */
64 public function can_manage(): bool {
65 return $this->get_scope() === 'host';
66 }
67
68 /**
69 * {@inheritDoc}
70 */
71 public function get_metaData(): array {
72 $return = [];
73 // icon
74 $return['icon'] = 'computer.svg';
75 // alias name
76 $return["alias"] = _("Puppet");
77 // module dependencies
78 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
79 // managed object classes
80 $return['objectClasses'] = ['puppetClient'];
81 // managed attributes
82 $return['attributes'] = ['environment', 'parentnode', 'puppetclass', 'puppetvar'];
83 // help Entries
84 $return['help'] = [
85 'environment' => [
86 "Headline" => _('Environment'), 'attr' => 'environment',
87 "Text" => _('Please enter the environment name for this node (e.g. production).')
88 ],
89 'environmentList' => [
90 "Headline" => _('Environment'), 'attr' => 'environment',
91 "Text" => _('Please enter the environment name for this node (e.g. production).') . ' ' . _('Multiple values are separated by semicolon.')
92 ],
93 'parentnode' => [
94 "Headline" => _('Parent node'), 'attr' => 'parentnode',
95 "Text" => _('This is this node\'s parent. All classes and variables are inherited from this node.')
96 ],
97 'puppetclass' => [
98 "Headline" => _('Classes'), 'attr' => 'puppetclass',
99 "Text" => _('The list of configured Puppet classes for this node (e.g. ntp).')
100 ],
101 'puppetclassList' => [
102 "Headline" => _('Classes'), 'attr' => 'puppetclass',
103 "Text" => _('The list of configured Puppet classes for this node (e.g. ntp).') . ' ' . _('Multiple values are separated by semicolon.')
104 ],
105 'puppetvar' => [
106 "Headline" => _('Variables'), 'attr' => 'puppetvar',
107 "Text" => _('Please enter your Puppet variables for this node (e.g. config_exim=true).')
108 ],
109 'puppetvarList' => [
110 "Headline" => _('Variables'), 'attr' => 'puppetvar',
111 "Text" => _('Please enter your Puppet variables for this node (e.g. config_exim=true).') . ' ' . _('Multiple values are separated by semicolon.')
112 ],
113 'autoAdd' => [
114 "Headline" => _('Automatically add this extension'),
115 "Text" => _('This will enable the extension automatically if this profile is loaded.')
116 ],
117 'predefinedClasses' => [
118 "Headline" => _('Predefined classes'),
119 "Text" => _('These classes will be available as autocompletion hints when adding new classes.')
120 ],
121 'predefinedEnvironments' => [
122 "Headline" => _('Predefined environments'),
123 "Text" => _('These environments will be available as autocompletion hints when setting the environment.')
124 ],
125 'enforceClasses' => [
126 "Headline" => _('Enforce classes'),
127 "Text" => _('If set then only these classes are allowed. One class per line.')
128 ],
129 ];
130 // upload fields
131 $allowedClasses = '';
132 if (!empty($this->moduleSettings['puppetClient_enforceClasses'][0])) {
133 $allowedClasses = implode(', ', $this->moduleSettings['puppetClient_enforceClasses']);
134 }
135 $return['upload_columns'] = [
136 [
137 'name' => 'puppetClient_environment',
138 'description' => _('Environment'),
139 'help' => 'environmentList',
140 'example' => 'production'
141 ],
142 [
143 'name' => 'puppetClient_parentnode',
144 'description' => _('Parent node'),
145 'help' => 'parentnode',
146 'example' => 'basenode'
147 ],
148 [
149 'name' => 'puppetClient_puppetclass',
150 'description' => _('Classes'),
151 'help' => 'puppetclassList',
152 'example' => 'ntp;exim',
153 'values' => $allowedClasses
154 ],
155 [
156 'name' => 'puppetClient_puppetvar',
157 'description' => _('Variables'),
158 'help' => 'puppetvarList',
159 'example' => 'config_exim=true;config_exim_trusted_users=root'
160 ],
161 ];
162 // available PDF fields
163 $return['PDF_fields'] = [
164 'environment' => _('Environment'),
165 'parentnode' => _('Parent node'),
166 'puppetclass' => _('Classes'),
167 'puppetvar' => _('Variables'),
168 ];
169 // profile options
170 $profileContainer = new htmlResponsiveRow();
171 $profileContainer->add(new htmlResponsiveInputCheckbox('puppetClient_addExt', false, _('Automatically add this extension'), 'autoAdd'));
172 $profileEnvironment = new htmlResponsiveInputField(_('Environment'), 'puppetClient_environment', null, 'environment');
173 $autocompleteEnvironment = [];
174 if (isset($this->moduleSettings['puppetClient_environments'])) {
175 $autocompleteEnvironment = $this->moduleSettings['puppetClient_environments'];
176 }
177 $profileEnvironment->enableAutocompletion($autocompleteEnvironment);
178 $profileContainer->add($profileEnvironment);
179 $profileContainer->add(new htmlResponsiveInputTextarea('puppetClient_puppetclass', '', 60, 5, _('Classes'), 'puppetclass'));
180 $profileContainer->add(new htmlResponsiveInputTextarea('puppetClient_puppetvar', '', 60, 5, _('Variables'), 'puppetvar'));
181 $return['profile_options'] = $profileContainer;
182 // profile checks
183 $return['profile_checks']['puppetClient_environment'] = ['type' => 'ext_preg', 'regex' => 'ascii', 'error_message' => $this->messages['environment'][0]];
184 // profile mappings
185 $return['profile_mappings'] = [
186 'puppetClient_environment' => 'environment',
187 ];
188 return $return;
189 }
190
191 /**
192 * {@inheritDoc}
193 */
194 protected function load_Messages(): void {
195 $this->messages['environment'][0] = ['ERROR', _('The environment name may only contain ASCII characters.')];
196 $this->messages['environment'][1] = ['ERROR', _('Account %s:') . ' puppetClient_environment', _('The environment name may only contain ASCII characters.')];
197 $this->messages['puppetclass'][0] = ['ERROR', _('The class names may only contain ASCII characters.')];
198 $this->messages['puppetclass'][1] = ['ERROR', _('Account %s:') . ' puppetClient_puppetclass', _('The class names may only contain ASCII characters.')];
199 $this->messages['puppetclass'][2] = ['ERROR', _('Account %s:') . ' puppetClient_puppetclass', _('The class names contain invalid values.')];
200 $this->messages['puppetvar'][0] = ['ERROR', _('The variables may only contain ASCII characters.')];
201 $this->messages['puppetvar'][1] = ['ERROR', _('Account %s:') . ' puppetClient_puppetvar', _('The variables may only contain ASCII characters.')];
202 $this->messages['parentnode'][0] = ['ERROR', _('Account %s:') . ' puppetClient_parentnode', _('Parent node not found.')];
203 }
204
205 /**
206 * {@inheritDoc}
207 */
208 public function save_attributes(): array {
209 if (!in_array('puppetClient', $this->attributes['objectClass']) && !in_array('puppetClient', $this->orig['objectClass'])) {
210 // skip saving if the extension was not added/modified
211 return [];
212 }
213 return parent::save_attributes();
214 }
215
216 /**
217 * {@inheritDoc}
218 */
219 public function display_html_attributes(): htmlElement|array {
220 if (isset($_POST['form_subpage_puppetClient_attributes_addObjectClass'])) {
221 $this->attributes['objectClass'][] = 'puppetClient';
222 }
223 $return = new htmlResponsiveRow();
224 if (!in_array('puppetClient', $this->attributes['objectClass'])) {
225 $return->add(new htmlAccountPageButton('puppetClient', 'attributes', 'addObjectClass', _('Add Puppet extension')));
226 return $return;
227 }
228 $this->initCache();
229 // environment
230 $autocompleteEnvironment = [];
231 if (isset($this->moduleSettings['puppetClient_environments'])) {
232 $autocompleteEnvironment = $this->moduleSettings['puppetClient_environments'];
233 }
234 $environments = [];
235 if (isset($this->attributes['environment'][0])) {
236 $environments = $this->attributes['environment'];
237 }
238 if (count($environments) === 0) {
239 $environments[] = '';
240 }
241 $environmentLabel = new htmlOutputText(_('Environment'));
242 $return->addLabel($environmentLabel);
243 $environmentContainer = new htmlGroup();
244 for ($i = 0; $i < count($environments); $i++) {
245 $environmentField = new htmlInputField('environment' . $i, $environments[$i]);
246 $environmentField->enableAutocompletion($autocompleteEnvironment);
247 $environmentContainer->addElement($environmentField);
248 if ($i < (count($environments) - 1)) {
249 $environmentContainer->addElement(new htmlLineBreak());
250 }
251 else {
252 $environmentContainer->addElement(new htmlButton('addEnvironment', 'add.svg', true));
253 $environmentContainer->addElement(new htmlHelpLink('environment'));
254 }
255 }
256 $return->addField($environmentContainer);
257 // parent node
258 $possibleParentNodes = $this->getPossibleParentNodes();
259 array_unshift($possibleParentNodes, '-');
260 $parentnode = '-';
261 if (isset($this->attributes['parentnode'][0])) {
262 $parentnode = $this->attributes['parentnode'][0];
263 }
264 $return->add(new htmlResponsiveSelect('parentnode', $possibleParentNodes, [$parentnode], _('Parent node'), 'parentnode'));
265 // classes
266 if (empty($this->moduleSettings['puppetClient_enforceClasses'][0])) {
267 $this->addMultiValueInputTextField($return, 'puppetclass', _('Classes'), false, null, false, $this->classCache);
268 }
269 else {
270 $this->addMultiValueSelectField($return, 'puppetclass', _('Classes'), $this->moduleSettings['puppetClient_enforceClasses']);
271 }
272 // variables
273 $this->addMultiValueInputTextField($return, 'puppetvar', _('Variables'), false, null, false, $this->variablesCache);
274
275 $return->addVerticalSpacer('2rem');
276 $remButton = new htmlAccountPageButton('puppetClient', 'attributes', 'remObjectClass', _('Remove Puppet extension'));
277 $remButton->setCSSClasses(['lam-danger']);
278 $return->add($remButton, 12, 12, 12, 'text-center');
279 return $return;
280 }
281
282 /**
283 * {@inheritDoc}
284 */
285 public function process_attributes(): array {
286 if (isset($_POST['form_subpage_puppetClient_attributes_remObjectClass'])) {
287 $this->attributes['objectClass'] = array_delete(['puppetClient'], $this->attributes['objectClass']);
288 for ($i = 0; $i < count($this->meta['attributes']); $i++) {
289 if (isset($this->attributes[$this->meta['attributes'][$i]])) {
290 unset($this->attributes[$this->meta['attributes'][$i]]);
291 }
292 }
293 return [];
294 }
295 if (!in_array('puppetClient', $this->attributes['objectClass'])) {
296 return [];
297 }
298
299 $errors = [];
300 // environment
301 $environmentCounter = 0;
302 while (isset($_POST['environment' . $environmentCounter])) {
303 $this->attributes['environment'][$environmentCounter] = $_POST['environment' . $environmentCounter];
304 if (!get_preg($this->attributes['environment'][$environmentCounter], 'ascii')) {
305 $errors[] = $this->messages['environment'][0];
306 }
307 if ($this->attributes['environment'][$environmentCounter] == '') {
308 unset($this->attributes['environment'][$environmentCounter]);
309 }
310 $environmentCounter++;
311 }
312 if (isset($_POST['addEnvironment'])) {
313 $this->attributes['environment'][] = '';
314 }
315 $this->attributes['environment'] = array_values($this->attributes['environment']);
316 // parent node
317 if (isset($this->attributes['parentnode'][0]) && ($_POST['parentnode'] == '-')) {
318 unset($this->attributes['parentnode'][0]);
319 }
320 elseif ($_POST['parentnode'] != '-') {
321 $this->attributes['parentnode'][0] = $_POST['parentnode'];
322 }
323 // classes
324 if (empty($this->moduleSettings['puppetClient_enforceClasses'][0])) {
325 $this->processMultiValueInputTextField('puppetclass', $errors, 'ascii');
326 }
327 else {
328 $this->processMultiValueSelectField('puppetclass');
329 }
330 // variables
331 $this->processMultiValueInputTextField('puppetvar', $errors, 'ascii');
332
333 return $errors;
334 }
335
336 /**
337 * {@inheritDoc}
338 */
339 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
340 $messages = [];
341 for ($i = 0; $i < count($rawAccounts); $i++) {
342 // add object class
343 if (!in_array("puppetClient", $partialAccounts[$i]['objectClass'])) {
344 $partialAccounts[$i]['objectClass'][] = "puppetClient";
345 }
346 // parent node
347 if ($rawAccounts[$i][$ids['puppetClient_parentnode']] != "") {
348 if (!in_array($rawAccounts[$i][$ids['puppetClient_parentnode']], $this->getPossibleParentNodes())) {
349 $messages[] = $this->messages['parentnode'][0];
350 }
351 else {
352 $partialAccounts[$i]['parentnode'][0] = $rawAccounts[$i][$ids['puppetClient_parentnode']];
353 }
354 }
355 // environment
356 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'puppetClient_environment', 'environment', 'ascii', $this->messages['environment'][1], $messages, '/;[ ]*/');
357 // classes
358 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'puppetClient_puppetclass', 'puppetclass', 'ascii', $this->messages['puppetclass'][1], $messages, '/;[ ]*/');
359 if (!empty($this->moduleSettings['puppetClient_enforceClasses'][0]) && !empty($partialAccounts[$i]['puppetclass'])) {
360 $invalidClassFound = false;
361 foreach ($partialAccounts[$i]['puppetclass'] as $singleClass) {
362 if (!in_array($singleClass, $this->moduleSettings['puppetClient_enforceClasses'])) {
363 $invalidClassFound = true;
364 break;
365 }
366 }
367 if ($invalidClassFound) {
368 $msg = $this->messages['puppetclass'][2];
369 $msg[] = $i;
370 $messages[] = $msg;
371 }
372 }
373 // variables
374 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'puppetClient_puppetvar', 'puppetvar', 'ascii', $this->messages['puppetvar'][1], $messages, '/;[ ]*/');
375 }
376 return $messages;
377 }
378
379 /**
380 * {@inheritDoc}
381 */
382 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
383 $return = [];
384 if (!in_array('puppetClient', $this->attributes['objectClass'])) {
385 return $return;
386 }
387 $this->addSimplePDFField($return, 'environment', _('Environment'));
388 $this->addSimplePDFField($return, 'parentnode', _('Parent node'));
389 if (isset($this->attributes['puppetclass'][0])) {
390 $pdfTable = new PDFTable(_('Classes'));
391 for ($i = 0; $i < count($this->attributes['puppetclass']); $i++) {
392 $pdfRow = new PDFTableRow();
393 $pdfRow->cells[] = new PDFTableCell($this->attributes['puppetclass'][$i]);
394 $pdfTable->rows[] = $pdfRow;
395 }
396 $this->addPDFTable($return, 'puppetclass', $pdfTable);
397 }
398 if (isset($this->attributes['puppetvar'][0])) {
399 $pdfTable = new PDFTable(_('Variables'));
400 for ($i = 0; $i < count($this->attributes['puppetvar']); $i++) {
401 $pdfRow = new PDFTableRow();
402 $pdfRow->cells[] = new PDFTableCell($this->attributes['puppetvar'][$i]);
403 $pdfTable->rows[] = $pdfRow;
404 }
405 $this->addPDFTable($return, 'puppetvar', $pdfTable);
406 }
407 return $return;
408 }
409
410 /**
411 * {@inheritDoc}
412 */
413 public function get_profileOptions(string $typeId): ?htmlResponsiveRow {
414 $return = parent::get_profileOptions($typeId);
415 $possibleParentNodes = $this->getPossibleParentNodes();
416 array_unshift($possibleParentNodes, '-');
417 $possibleParentNodes = array_values($possibleParentNodes);
418 $return->add(new htmlResponsiveSelect('puppetClient_parentnode', $possibleParentNodes, [], _('Parent node'), 'parentnode'));
419 return $return;
420 }
421
422 /**
423 * {@inheritDoc}
424 */
425 public function load_profile(array $profile): void {
426 // profile mappings in meta data
427 parent::load_profile($profile);
428 // add extension
429 if (isset($profile['puppetClient_addExt'][0])
430 && ($profile['puppetClient_addExt'][0] == "true")
431 && !in_array('puppetClient', $this->attributes['objectClass'])) {
432 $this->attributes['objectClass'][] = 'puppetClient';
433 }
434 // parent node
435 if (isset($profile['puppetClient_parentnode'][0]) && ($profile['puppetClient_parentnode'][0] != "-")) {
436 $this->attributes['parentnode'][0] = $profile['puppetClient_parentnode'][0];
437 }
438 // classes
439 if (isset($profile['puppetClient_puppetclass'][0]) && ($profile['puppetClient_puppetclass'][0] != '')) {
440 $this->attributes['puppetclass'] = $profile['puppetClient_puppetclass'];
441 }
442 // variables
443 if (isset($profile['puppetClient_puppetvar'][0]) && ($profile['puppetClient_puppetvar'][0] != '')) {
444 $this->attributes['puppetvar'] = $profile['puppetClient_puppetvar'];
445 }
446 }
447
448 /**
449 * Returns a list of valid parent nodes for this node.
450 *
451 * @return string[] parent nodes (e.g. array('node1', 'node2'))
452 */
453 private function getPossibleParentNodes(): array {
454 $searchResult = searchLDAPByAttribute('cn', '*', 'puppetClient', ['cn'], ['host']);
455 $possibleParentNodes = [];
456 for ($i = 0; $i < count($searchResult); $i++) {
457 if (!get_preg($searchResult[$i]['cn'][0], 'ascii')) {
458 continue;
459 }
460 if (($this->getAccountContainer() == null) || $this->getAccountContainer()->isNewAccount
461 || (!isset($this->getAccountContainer()->attributes_orig['cn'][0])
462 || ($this->getAccountContainer()->attributes_orig['cn'][0] != $searchResult[$i]['cn'][0]))) {
463 $possibleParentNodes[] = $searchResult[$i]['cn'][0];
464 }
465 }
466 return $possibleParentNodes;
467 }
468
469 /**
470 * Loads cached data from LDAP such as classes etc.
471 */
472 private function initCache(): void {
473 if ($this->classCache !== null) {
474 return;
475 }
476 $attrs = ['puppetclass', 'puppetvar'];
477 $classes = [];
478 $variables = [];
479 $result = searchLDAPByFilter('(objectClass=puppetClient)', $attrs, [$this->get_scope()]);
480 foreach ($result as $attributes) {
481 if (isset($attributes['puppetclass'])) {
482 foreach ($attributes['puppetclass'] as $val) {
483 $classes[] = $val;
484 }
485 }
486 if (isset($attributes['puppetvar'])) {
487 foreach ($attributes['puppetvar'] as $val) {
488 $variables[] = $val;
489 }
490 }
491 }
492 $this->classCache = array_values(array_unique($classes));
493 $this->variablesCache = array_values(array_unique($variables));
494 }
495
496 /**
497 * {@inheritDoc}
498 */
499 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
500 $return = new htmlResponsiveRow();
501 // config options
502 $return->add(new htmlResponsiveInputTextarea('puppetClient_environments', "production\r\ntesting", 30, 5, _('Predefined environments'), 'predefinedEnvironments'));
503 $return->add(new htmlResponsiveInputTextarea('puppetClient_enforceClasses', '', 30, 5, _('Enforce classes'), 'enforceClasses'));
504 return $return;
505 }
506
507 /**
508 * @inheritDoc
509 */
510 public function getListAttributeDescriptions(ConfiguredType $type): array {
511 return [
512 'environment' => _('Environment'),
513 'parentnode' => _('Parent node'),
514 'puppetclass' => _('Classes'),
515 'puppetvar' => _('Variables'),
516 ];
517 }
518
519 }