Debian Codegraph @

templates/tools/importexport.php

raw
1 <?php
2 namespace LAM\TOOLS\IMPORT_EXPORT;
3 use htmlProgressbar;
4 use htmlTitle;
5 use htmlResponsiveRadio;
6 use htmlResponsiveRow;
7 use htmlResponsiveInputFileUpload;
8 use htmlResponsiveInputTextarea;
9 use htmlButton;
10 use htmlStatusMessage;
11 use htmlDiv;
12 use htmlOutputText;
13 use htmlJavaScript;
14 use LAM\TOOLS\TREEVIEW\TreeViewTool;
15 use LAMException;
16 use htmlLink;
17 use htmlResponsiveInputCheckbox;
18 use htmlResponsiveSelect;
19 use htmlResponsiveInputField;
20 use htmlHiddenInput;
21 use LAM\TYPES\TypeManager;
22
23 /*
24
25 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
26 Copyright (C) 2018 - 2026 Roland Gruber
27
28 This program is free software; you can redistribute it and/or modify
29 it under the terms of the GNU General Public License as published by
30 the Free Software Foundation; either version 2 of the License, or
31 (at your option) any later version.
32
33 This program is distributed in the hope that it will be useful,
34 but WITHOUT ANY WARRANTY; without even the implied warranty of
35 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 GNU General Public License for more details.
37
38 You should have received a copy of the GNU General Public License
39 along with this program; if not, write to the Free Software
40 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
41
42 */
43
44 /**
45 * Multi edit tool that allows LDAP operations on multiple entries.
46 *
47 * @author Roland Gruber
48 * @package tools
49 */
50
51 /** security functions */
52 include_once(__DIR__ . "/../../lib/security.inc");
53 /** access to configuration data */
54 include_once(__DIR__ . "/../../lib/config.inc");
55 /** access LDAP server */
56 include_once(__DIR__ . "/../../lib/ldap.inc");
57 /** used to print status messages */
58 include_once(__DIR__ . "/../../lib/status.inc");
59 /** import class */
60 include_once(__DIR__ . "/../../lib/import.inc");
61
62 // start session
63 startSecureSession();
64 enforceUserIsLoggedIn();
65
66 // die if no write access
67 if (!checkIfWriteAccessIsAllowed()) {
68 die();
69 }
70
71 checkIfToolIsActive('ImportExport');
72
73 setlanguage();
74
75 if (!empty($_POST)) {
76 validateSecurityToken();
77 }
78
79 // clean old data
80 if (isset($_SESSION[Importer::SESSION_KEY_TASKS])) {
81 unset($_SESSION[Importer::SESSION_KEY_TASKS]);
82 }
83 if (isset($_SESSION[Importer::SESSION_KEY_COUNT])) {
84 unset($_SESSION[Importer::SESSION_KEY_COUNT]);
85 }
86 if (isset($_SESSION[Importer::SESSION_KEY_STOP_ON_ERROR])) {
87 unset($_SESSION[Importer::SESSION_KEY_STOP_ON_ERROR]);
88 }
89
90 include __DIR__ . '/../../lib/adminHeader.inc';
91
92 $tabImportClass = 'lam-tab-active';
93 $tabExportClass = '';
94 if (!empty($_GET['tab']) && ($_GET['tab'] === 'export')) {
95 $tabImportClass = '';
96 $tabExportClass = 'lam-tab-active';
97 }
98
99 ?>
100
101 <div class="smallPaddingContent">
102 <div id="tabs" class="lam-tab-container">
103 <ul class="lam-tab-navigation">
104 <li id="tab_import" data-tabid="1" class="lam-tab <?php echo $tabImportClass; ?>">
105 <a class="lam-tab-anchor" href="#tab-import"><img alt="import" src="../../graphics/import.svg"> <?php echo _('Import') ?> </a>
106 </li>
107 <li id="tab_export" data-tabid="2" class="lam-tab <?php echo $tabExportClass; ?>">
108 <a class="lam-tab-anchor" href="#tab-export"><img alt="export" src="../../graphics/export.svg"> <?php echo _('Export') ?> </a>
109 </li>
110 </ul>
111 <div class="lam-tab-content <?php echo $tabImportClass; ?>" id="tab-import" data-tabid="1">
112 <?php
113 if (isset($_POST['submitImport'])) {
114 printImportTabProcessing();
115 }
116 else {
117 printImportTabContent();
118 }
119 ?>
120 </div>
121 <div class="lam-tab-content <?php echo $tabExportClass; ?>" id="tab-export" data-tabid="2">
122 <?php
123 if (isset($_POST['submitExport'])) {
124 printExportTabProcessing();
125 }
126 else {
127 printExportTabContent();
128 }
129 ?>
130 </div>
131 </div>
132 </div>
133
134 <?php
135
136 /**
137 * Prints the content area for the import tab.
138 */
139 function printImportTabContent(): void {
140 echo "<form class=\"inputForm\" enctype=\"multipart/form-data\" action=\"importexport.php\" method=\"post\">\n";
141 $container = new htmlResponsiveRow();
142 $container->add(new htmlTitle(_("Import")));
143 $sources = [
144 _('Text input') => 'text',
145 _('File') => 'file',
146 ];
147 $sourceRadio = new htmlResponsiveRadio(_('Source'), 'source', $sources, 'text');
148 $sourceRadio->setTableRowsToHide(
149 [
150 'file' => ['text'],
151 'text' => ['file']
152 ]
153 );
154 $sourceRadio->setTableRowsToShow(
155 [
156 'text' => ['text'],
157 'file' => ['file']
158 ]
159 );
160 $container->add($sourceRadio);
161 $container->addVerticalSpacer('1rem');
162 $container->add(new htmlResponsiveInputFileUpload('file', _('File'), '750'));
163 $ldifValue = $_POST['text'] ?? '';
164 $container->add(new htmlResponsiveInputTextarea('text', $ldifValue, 60, 20, _('LDIF data'), '750'));
165 $container->add(new htmlResponsiveInputCheckbox('noStop', false, _('Don\'t stop on errors')));
166
167 $container->addVerticalSpacer('3rem');
168 $button = new htmlButton('submitImport', _('Submit'));
169 $container->add($button, 12, 12, 12, 'text-center');
170
171 addSecurityTokenToMetaHTML($container);
172
173 parseHtml(null, $container, [], false, 'user');
174 echo "</form>\n";
175 }
176
177 /**
178 * Prints the content area for the import tab during processing state.
179 */
180 function printImportTabProcessing(): void {
181 try {
182 checkImportData();
183 }
184 catch (LAMException $e) {
185 $container = new htmlResponsiveRow();
186 $container->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage()));
187 parseHtml(null, $container, [], false, 'user');
188 printImportTabContent();
189 return;
190 }
191 echo "<form class=\"inputForm\" enctype=\"multipart/form-data\" action=\"importexport.php\" method=\"post\">\n";
192 $container = new htmlResponsiveRow();
193 $container->add(new htmlTitle(_("Import")));
194
195 $container->add(new htmlDiv('statusImportInprogress', new htmlOutputText(_('Status') . ': ' . _('in progress'))));
196 $container->add(new htmlDiv('statusImportDone', new htmlOutputText(_('Status') . ': ' . _('done')), ['hidden']));
197 $container->add(new htmlDiv('statusImportFailed', new htmlOutputText(_('Status') . ': ' . _('failed')), ['hidden']));
198 $container->addVerticalSpacer('1rem');
199 $container->add(new htmlProgressbar('progressbarImport'));
200 $container->addVerticalSpacer('3rem');
201 $button = new htmlButton('submitImportCancel', _('Cancel'));
202 $container->add($button, 12, 12, 12, 'text-center');
203
204 $newImportButton = new htmlLink(_('New import'), '');
205 $container->add($newImportButton, 12, 12, 12, 'text-center hidden newimport');
206
207 $container->addVerticalSpacer('3rem');
208
209 $container->add(new htmlDiv('importResults', new htmlOutputText('')));
210 $container->add(new htmlJavaScript(
211 'window.lam.importexport.startImport(\'' . getSecurityTokenName() . '\', \'' . getSecurityTokenValue() . '\');'
212 ));
213
214 addSecurityTokenToMetaHTML($container);
215
216 parseHtml(null, $container, [], false, 'user');
217 echo "</form>\n";
218 }
219
220 /**
221 * Checks if the import data is ok.
222 *
223 * @throws LAMException error message if not valid
224 */
225 function checkImportData(): void {
226 $source = $_POST['source'];
227 if ($source == 'text') {
228 $ldif = $_POST['text'];
229 }
230 else {
231 $handle = fopen($_FILES['file']['tmp_name'], "r");
232 if ($handle === false) {
233 throw new LAMException(_('Unable to create temporary file.'));
234 }
235 $ldif = fread($handle, 100_000_000);
236 if ($ldif === false) {
237 throw new LAMException(_('Unable to create temporary file.'));
238 }
239 fclose($handle);
240 }
241 if (empty($ldif)) {
242 throw new LAMException(_('You must either upload a file or provide an import in the text box.'));
243 }
244 $lines = preg_split("/\n|\r\n|\r/", $ldif);
245 if ($lines === false) {
246 throw new LAMException(_('You must either upload a file or provide an import in the text box.'));
247 }
248 $importer = new Importer();
249 $tasks = $importer->getTasks($lines);
250 $_SESSION[Importer::SESSION_KEY_TASKS] = $tasks;
251 $_SESSION[Importer::SESSION_KEY_COUNT] = count($tasks);
252 $_SESSION[Importer::SESSION_KEY_STOP_ON_ERROR] = (!isset($_POST['noStop']) || ($_POST['noStop'] != 'on'));
253 }
254
255 /**
256 * Prints the content area for the export tab.
257 */
258 function printExportTabContent(): void {
259 echo "<form class=\"inputForm\" enctype=\"multipart/form-data\" action=\"importexport.php?tab=export\" method=\"post\">\n";
260 $container = new htmlResponsiveRow();
261 $container->add(new htmlTitle(_("Export")));
262
263 $baseDn = getDefaultBaseDn();
264 if (!empty($_GET['dn'])) {
265 $preSetDn = base64_decode($_GET['dn']);
266 if (isValidExportDn($preSetDn)) {
267 $baseDn = $preSetDn;
268 }
269 }
270 $baseDnField = new htmlResponsiveInputField(_('Base DN'), 'baseDn', $baseDn, '751', true);
271 $baseDnField->showDnSelection();
272 $container->add($baseDnField);
273
274 $searchScopes = [
275 _('Base (base dn only)') => 'base',
276 _('One (one level beneath base)') => 'one',
277 _('Sub (entire subtree)') => 'sub'
278 ];
279 $searchScopeSelect = new htmlResponsiveSelect('searchScope', $searchScopes, ['sub'], _('Search scope'));
280 $searchScopeSelect->setHasDescriptiveElements(true);
281 $searchScopeSelect->setSortElements(false);
282 $container->add($searchScopeSelect);
283 $container->add(new htmlResponsiveInputField(_('Search filter'), 'filter', '(objectClass=*)', '752'));
284 $container->add(new htmlResponsiveInputField(_('Attributes'), 'attributes', '*', '753'));
285 $container->add(new htmlResponsiveInputCheckbox('includeSystem', false, _('Include system attributes'), '754'));
286 $container->add(new htmlResponsiveInputCheckbox('saveAsFile', false, _('Save as file')));
287
288 $formats = [
289 'CSV' => 'csv',
290 'LDIF' => 'ldif'
291 ];
292 $formatSelect = new htmlResponsiveSelect('format', $formats, ['ldif'], _('Export format'));
293 $formatSelect->setHasDescriptiveElements(true);
294 $formatSelect->setSortElements(false);
295 $container->add($formatSelect);
296
297 $endings = [
298 'Windows' => 'windows',
299 'Unix' => 'unix'
300 ];
301 $endingsSelect = new htmlResponsiveSelect('ending', $endings, ['unix'], _('End of line'));
302 $endingsSelect->setHasDescriptiveElements(true);
303 $endingsSelect->setSortElements(false);
304 $container->add($endingsSelect);
305
306 $container->addVerticalSpacer('3rem');
307 $button = new htmlButton('submitExport', _('Submit'));
308 $container->add($button, 12, 12, 12, 'text-center');
309
310 addSecurityTokenToMetaHTML($container);
311
312 parseHtml(null, $container, [], false, 'user');
313 echo "</form>\n";
314 }
315
316 /**
317 * Returns the default base DN.
318 *
319 * @return string base DN
320 */
321 function getDefaultBaseDn(): string {
322 $typeManager = new TypeManager();
323 $baseDn = '';
324 foreach ($typeManager->getConfiguredTypes() as $type) {
325 $suffix = $type->getSuffix();
326 if (empty($baseDn) || (!empty($suffix) && (strlen($suffix) < strlen($baseDn)))) {
327 $baseDn = $suffix;
328 }
329 }
330 if ($_SESSION['config']->isToolActive('TreeViewTool')) {
331 $treeSuffixes = TreeViewTool::getRootDns();
332 if (empty($baseDn) || (!empty($treeSuffixes) && (strlen($treeSuffixes[0]) < strlen($baseDn)))) {
333 $baseDn = $treeSuffixes[0];
334 }
335 }
336 return $baseDn;
337 }
338
339 /**
340 * Checks if the given DN is valid for exporting.
341 *
342 * @param string $dn DN
343 * @return bool valid
344 */
345 function isValidExportDn(string $dn): bool {
346 $dn = strtolower($dn);
347 $typeManager = new TypeManager();
348 foreach ($typeManager->getConfiguredTypes() as $type) {
349 $suffix = strtolower($type->getSuffix());
350 if (str_ends_with($dn, $suffix)) {
351 return true;
352 }
353 }
354 if ($_SESSION['config']->isToolActive('TreeViewTool')) {
355 $treeSuffixes = TreeViewTool::getRootDns();
356 foreach ($treeSuffixes as $treeSuffix) {
357 $treeSuffix = strtolower($treeSuffix);
358 if (str_ends_with($dn, $treeSuffix)) {
359 return true;
360 }
361 }
362 }
363 return false;
364 }
365
366 /**
367 * Prints the content area for the export tab during processing state.
368 */
369 function printExportTabProcessing(): void {
370 try {
371 checkExportData();
372 }
373 catch (LAMException $e) {
374 $container = new htmlResponsiveRow();
375 $container->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage()));
376 parseHtml(null, $container, [], false, 'user');
377 printExportTabContent();
378 return;
379 }
380 echo "<form class=\"inputForm\" enctype=\"multipart/form-data\" action=\"importexport.php?tab=export\" method=\"post\">\n";
381 $container = new htmlResponsiveRow();
382 $container->add(new htmlTitle(_("Export")));
383
384 $container->add(new htmlHiddenInput('baseDn', $_POST['baseDn']));
385 $container->add(new htmlHiddenInput('searchScope', $_POST['searchScope']));
386 $container->add(new htmlHiddenInput('filter', $_POST['filter']));
387 $container->add(new htmlHiddenInput('attributes', $_POST['attributes']));
388 $container->add(new htmlHiddenInput('format', $_POST['format']));
389 $container->add(new htmlHiddenInput('ending', $_POST['ending']));
390 $container->add(new htmlHiddenInput('includeSystem', isset($_POST['includeSystem']) && ($_POST['includeSystem'] === 'on') ? 'true' : 'false'));
391 $container->add(new htmlHiddenInput('saveAsFile', isset($_POST['saveAsFile']) && ($_POST['saveAsFile'] === 'on') ? 'true' : 'false'));
392
393 $container->add(new htmlDiv('statusExportInprogress', new htmlOutputText(_('Status') . ': ' . _('in progress'))));
394 $container->add(new htmlDiv('statusExportDone', new htmlOutputText(_('Status') . ': ' . _('done')), ['hidden']));
395 $container->add(new htmlDiv('statusExportFailed', new htmlOutputText(_('Status') . ': ' . _('failed')), ['hidden']));
396 $container->addVerticalSpacer('1rem');
397 $container->add(new htmlProgressbar('progressbarExport'));
398 $container->addVerticalSpacer('3rem');
399 $button = new htmlButton('submitExportCancel', _('Cancel'));
400 $container->add($button, 12, 12, 12, 'text-center');
401
402 $newExportButton = new htmlLink(_('New export'), '');
403 $container->add($newExportButton, 12, 12, 12, 'text-center hidden newexport');
404
405 $container->addVerticalSpacer('3rem');
406
407 $exportText = new htmlOutputText('');
408 $exportText->setPreformatted();
409 $container->add(new htmlDiv('exportResults', $exportText));
410 $container->add(new htmlJavaScript(
411 'window.lam.importexport.startExport(\'' . getSecurityTokenName() . '\', \'' . getSecurityTokenValue() . '\');'
412 ));
413
414 addSecurityTokenToMetaHTML($container);
415
416 parseHtml(null, $container, [], false, 'user');
417 echo "</form>\n";
418 }
419
420 /**
421 * Checks if the export data is ok.
422 *
423 * @throws LAMException error message if not valid
424 */
425 function checkExportData(): void {
426 if (empty($_POST['baseDn'])) {
427 throw new LAMException(_('This field is required.'), _('Base DN'));
428 }
429 }
430
431 include __DIR__ . '/../../lib/adminFooter.inc';