Debian Codegraph @

lib/import.inc

raw
1 <?php
2
3 namespace LAM\TOOLS\IMPORT_EXPORT;
4
5 use htmlStatusMessage;
6 use LAMException;
7
8 /*
9
10 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
11 Copyright (C) 2018 - 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 * LDIF import.
31 *
32 * @author Roland Gruber
33 * @package tools
34 */
35
36 /** LDAP handle */
37 include_once(__DIR__ . '/ldap.inc');
38
39 /**
40 * Imports LDIF files.
41 *
42 * @author Roland Gruber
43 * @package tools
44 */
45 class Importer {
46
47 public const SESSION_KEY_TASKS = 'import_tasks';
48 public const SESSION_KEY_COUNT = 'import_count';
49 public const SESSION_KEY_STOP_ON_ERROR = 'import_stop_on_error';
50 public const STATUS = 'status';
51 public const PROGRESS = 'progress';
52 public const DATA = 'data';
53 private const TIME_LIMIT = 10;
54 public const KEY = 0;
55 public const VALUE = 1;
56 private const CHANGETYPE = 'changetype';
57
58 /**
59 * Extracts the single entries in the file.
60 *
61 * @param string[] $lines LDIF lines
62 * @return array<string[]> array of string[]
63 * @throws LAMException invalid format
64 */
65 private function extractImportChunks(array $lines): array {
66 $entries = [];
67 $currentEntry = [];
68 foreach ($lines as $line) {
69 $trimmedLine = trim($line);
70 if (str_starts_with($trimmedLine, '#')) {
71 // skip comments
72 continue;
73 }
74 if (empty($trimmedLine)) {
75 // end of entry
76 if (!empty($currentEntry)) {
77 $entries[] = $currentEntry;
78 $currentEntry = [];
79 }
80 }
81 elseif (str_starts_with($line, ' ')) {
82 // append to last line if starting with a space
83 if (empty($currentEntry)) {
84 throw new LAMException(_('Invalid data'), htmlspecialchars($line));
85 }
86 else {
87 $currentEntry[count($currentEntry) - 1] .= substr($line, 1);
88 }
89 }
90 elseif ($line === '-') {
91 $currentEntry[] = $line;
92 }
93 else {
94 $parts = explode(':', $line, 2);
95 if (count($parts) < 2) {
96 throw new LAMException(_('Invalid data'), htmlspecialchars($line));
97 }
98 $currentEntry[] = $line;
99 }
100 }
101 if (!empty($currentEntry)) {
102 $entries[] = $currentEntry;
103 }
104 return $entries;
105 }
106
107 /**
108 * Converts the lines to LDAP import tasks.
109 *
110 * @param string[] $lines import lines
111 * @return ImporterTask[] tasks
112 * @throws LAMException if invalid format was found
113 */
114 public function getTasks(array $lines): array {
115 $chunks = $this->extractImportChunks($lines);
116 return $this->convertToTasks($chunks);
117 }
118
119 /**
120 * Processes the import data stored in session.
121 *
122 * @return string result
123 */
124 public function doImport(): string {
125 $data = '';
126 $tasks = &$_SESSION[Importer::SESSION_KEY_TASKS];
127 $stopOnError = $_SESSION[Importer::SESSION_KEY_STOP_ON_ERROR];
128 // check if any actions are needed at all
129 if (empty($tasks)) {
130 return $this->getStatus($data);
131 }
132 $endTime = $this->getEndTime();
133 while ((!empty($tasks)) && ($endTime > time())) {
134 $task = array_shift($tasks);
135 try {
136 $data .= $task->run();
137 }
138 catch (LAMException $e) {
139 if ($stopOnError) {
140 return $this->stopImport($data, $e);
141 }
142 else {
143 $data .= Importer::formatMessage('ERROR', $e->getTitle(), $e->getMessage());
144 }
145 }
146 }
147 return $this->getStatus($data);
148 }
149
150 /**
151 * Stops the import process because of an exception.
152 *
153 * @param string $data HTML output
154 * @param LAMException $e exception
155 * @return string JSON status
156 */
157 private function stopImport($data, LAMException $e) {
158 $data .= Importer::formatMessage('ERROR', $e->getTitle(), $e->getMessage());
159 if (isset($_SESSION[Importer::SESSION_KEY_TASKS])) {
160 unset($_SESSION[Importer::SESSION_KEY_TASKS]);
161 }
162 $status = [
163 Importer::STATUS => 'failed',
164 Importer::DATA => $data
165 ];
166 return json_encode($status);
167 }
168
169 /**
170 * Returns the current status as JSON.
171 *
172 * @param string $data HTML output to display
173 * @return string JSON status
174 */
175 private function getStatus($data) {
176 if (empty($_SESSION[Importer::SESSION_KEY_TASKS])) {
177 if (isset($_SESSION[Importer::SESSION_KEY_TASKS])) {
178 unset($_SESSION[Importer::SESSION_KEY_TASKS]);
179 }
180 $status = [
181 Importer::STATUS => 'done',
182 Importer::DATA => $data
183 ];
184 return json_encode($status);
185 }
186 $progress = (count($_SESSION[Importer::SESSION_KEY_TASKS]) / $_SESSION[Importer::SESSION_KEY_COUNT]) * 100.0;
187 $progress = floor(100 - $progress);
188 $status = [
189 Importer::STATUS => 'inProgress',
190 Importer::PROGRESS => $progress,
191 Importer::DATA => $data
192 ];
193 return json_encode($status);
194 }
195
196 /**
197 * Returns the time when processing should end.
198 *
199 * @return int end time as Unix timestamp
200 */
201 private function getEndTime(): int {
202 $startTime = time();
203 $maxTime = get_cfg_var('max_execution_time') - 10;
204 if ($maxTime > self::TIME_LIMIT) {
205 $maxTime = self::TIME_LIMIT;
206 }
207 if ($maxTime <= 0) {
208 $maxTime = self::TIME_LIMIT;
209 }
210 return $startTime + $maxTime;
211 }
212
213 /**
214 * Continues the import with processing of a single entry.
215 *
216 * @param string[][] $entries import entries
217 * @return ImporterTask[] tasks
218 */
219 private function convertToTasks(array $entries): array {
220 $tasks = [];
221 $count = count($entries);
222 for ($i = 0; $i < $count; $i++) {
223 $entry = $entries[$i];
224 $firstParts = explode(':', $entry[0], 2);
225 if ($firstParts[Importer::KEY] === 'version') {
226 if ($i > 0) {
227 // allow version only as first chunk
228 throw new LAMException(_('Invalid data'), _('Duplicate version entry found.'));
229 }
230 $this->processVersion($entry);
231 }
232 elseif ($firstParts[Importer::KEY] === 'dn') {
233 $tasks[] = $this->processDnEntry($entry);
234 }
235 else {
236 throw new LAMException(_('A valid dn line is required'), htmlspecialchars($entry[0]));
237 }
238 }
239 return $tasks;
240 }
241
242 /**
243 * Checks a version entry.
244 *
245 * @param string[] $entry entry
246 * @throws LAMException if version is invalid
247 */
248 private function processVersion($entry): void {
249 $keyValue = $this->getLineKeyValue($entry[0]);
250 if (($keyValue[Importer::VALUE] != '1') || (count($entry) > 1)) {
251 $escapedLines = array_map(htmlspecialchars(...), $entry);
252 throw new LAMException(_('LDIF import only supports version 1'), implode('<br>', $escapedLines));
253 }
254 }
255
256 /**
257 * Checks a dn entry.
258 *
259 * @param string[] $entry entry
260 * @return ImporterTask task
261 * @throws LAMException if invalid format
262 */
263 private function processDnEntry($entry) {
264 $dnLine = array_shift($entry);
265 $keyValue = $this->getLineKeyValue($dnLine);
266 $dn = $keyValue[Importer::VALUE];
267 if (empty($entry)) {
268 throw new LAMException(_('Invalid data'), htmlspecialchars($dnLine));
269 }
270 $firstAttributeLine = array_shift($entry);
271 $firstAttribute = $this->getLineKeyValue($firstAttributeLine);
272 if ($firstAttribute[Importer::KEY] != self::CHANGETYPE) {
273 // complete DN
274 $attributes = [
275 $firstAttribute[Importer::KEY] => [$firstAttribute[Importer::VALUE]]
276 ];
277 foreach ($entry as $attributeLine) {
278 $attribute = $this->getLineKeyValue($attributeLine);
279 $attributes[$attribute[Importer::KEY]][] = $attribute[Importer::VALUE];
280 }
281 return new AddEntryTask($dn, $attributes);
282 }
283 else {
284 $type = $firstAttribute[Importer::VALUE];
285 if ($type === 'add') {
286 $attributes = [];
287 foreach ($entry as $line) {
288 $lineData = $this->getLineKeyValue($line);
289 $attributes[$lineData[Importer::KEY]][] = $lineData[Importer::VALUE];
290 }
291 return new AddEntryTask($dn, $attributes);
292 }
293 elseif ($type === 'modrdn') {
294 return $this->createModRdnTask($dn, $entry);
295 }
296 elseif ($type === 'delete') {
297 if (!empty($entry)) {
298 throw new LAMException(_('Invalid data'), htmlspecialchars($dn));
299 }
300 return new DeleteEntryTask($dn);
301 }
302 elseif ($type !== 'modify') {
303 throw new LAMException(_('Invalid data'), htmlspecialchars($dn) . ' - changetype: ' . htmlspecialchars($type));
304 }
305 $subtasks = [];
306 $currentLines = [];
307 $linesCount = count($entry);
308 for ($i = 0; $i < $linesCount; $i++) {
309 $line = $entry[$i];
310 if ($line === '-') {
311 $subtasks[] = $this->getChangeTypeTask($dn, $currentLines);
312 $currentLines = [];
313 }
314 else {
315 $currentLines[] = $line;
316 }
317 }
318 $subtasks[] = $this->getChangeTypeTask($dn, $currentLines);
319 return new MultiTask($subtasks, $dn);
320 }
321 }
322
323 /**
324 * Returns a modrdn task.
325 *
326 * @param string $dn DN
327 * @param string[] $entry entry lines
328 * @return RenameEntryTask task
329 * @throws LAMException syntax error
330 */
331 private function createModRdnTask($dn, $entry) {
332 if (count($entry) !== 2) {
333 throw new LAMException(_('Invalid data'), htmlspecialchars($dn));
334 }
335 $newRdnData = $this->getLineKeyValue($entry[0]);
336 if ($newRdnData[Importer::KEY] !== 'newrdn') {
337 throw new LAMException(_('Invalid data'), htmlspecialchars($dn) . '<br>' . print_r($newRdnData, true));
338 }
339 $newRdn = $newRdnData[Importer::VALUE];
340 $delOldRdnData = $this->getLineKeyValue($entry[1]);
341 if (($delOldRdnData[Importer::KEY] !== 'deleteoldrdn') || !in_array($delOldRdnData[Importer::VALUE], ['0', '1'], true)) {
342 throw new LAMException(_('Invalid data'), htmlspecialchars($dn) . '<br>' . $entry[1]);
343 }
344 $delOldRdn = ($delOldRdnData[Importer::VALUE] !== '0');
345 return new RenameEntryTask($dn, $newRdn, $delOldRdn);
346 }
347
348 /**
349 * Returns a task for LDIF changetype entry.
350 *
351 * @param string $dn DN
352 * @param string[] $lines lines
353 * @return ImporterTask task
354 */
355 private function getChangeTypeTask($dn, $lines) {
356 $firstLine = array_shift($lines);
357 $firstLineData = $this->getLineKeyValue($firstLine);
358 $type = $firstLineData[Importer::KEY];
359 $attributeName = $firstLineData[Importer::VALUE];
360 $attributes = [];
361 foreach ($lines as $line) {
362 $lineData = $this->getLineKeyValue($line);
363 if ($lineData[Importer::KEY] !== $attributeName) {
364 throw new LAMException(_('Invalid data'), htmlspecialchars($dn) . ' - ' . htmlspecialchars($type));
365 }
366 $attributes[$attributeName][] = $lineData[Importer::VALUE];
367 }
368 if ($type === 'add') {
369 return new AddAttributesTask($dn, $attributes);
370 }
371 elseif ($type === 'delete') {
372 return new DeleteAttributesTask($dn, $attributeName, $attributes);
373 }
374 elseif ($type === 'replace') {
375 return new ReplaceAttributesTask($dn, $attributes);
376 }
377 throw new LAMException(_('Invalid data'), htmlspecialchars($dn) . ' - ' . htmlspecialchars($type));
378 }
379
380 /**
381 * Returns the HTML for an error message.
382 *
383 * @param string $type message type (e.g. INFO)
384 * @param string $title title
385 * @param string $message message
386 * @return string HTML
387 */
388 public static function formatMessage($type, $title, $message) {
389 $msg = new htmlStatusMessage($type, $title, $message);
390 ob_start();
391 $msg->generateHTML(null, [$msg], [], true);
392 $data = ob_get_contents();
393 ob_clean();
394 return $data;
395 }
396
397 /**
398 * Returns the key and value part of the line.
399 *
400 * @param string $line line
401 * @return string[] array(key, value)
402 */
403 private function getLineKeyValue($line) {
404 $parts = explode(':', $line, 2);
405 if (count($parts) !== 2) {
406 throw new LAMException(_('Invalid data'), htmlspecialchars($line));
407 }
408 if (str_starts_with($parts[Importer::VALUE], ':')) {
409 $value = base64_decode(trim(substr($parts[Importer::VALUE], 1)));
410 }
411 else {
412 $value = trim($parts[Importer::VALUE]);
413 }
414 return [$parts[Importer::KEY], $value];
415 }
416
417 }
418
419 /**
420 * A single import task.
421 *
422 * @author Roland Gruber
423 */
424 interface ImporterTask {
425
426 /**
427 * Runs the task.
428 *
429 * @throws LAMException error during import
430 * @return string HTML output or LAMException if error occurred
431 */
432 public function run(): string;
433
434 }
435
436 /**
437 * Adds a complete LDAP entry.
438 *
439 * @author Roland Gruber
440 */
441 class AddEntryTask implements ImporterTask {
442
443 private string $dn;
444 /** @var array<string, string[]> $attributes attributes */
445 private array $attributes;
446
447 /**
448 * Constructor
449 *
450 * @param string $dn DN
451 * @param array<string, string[]> $attributes list of attributes
452 */
453 public function __construct(string $dn, array $attributes) {
454 $this->dn = $dn;
455 $this->attributes = $attributes;
456 }
457
458 /**
459 * {@inheritDoc}
460 * @see ImporterTask::run
461 */
462 public function run(): string {
463 $ldap = $_SESSION['ldap']->server();
464 $success = @ldap_add($ldap, $this->dn, $this->attributes);
465 if ($success) {
466 return Importer::formatMessage('INFO', _('Entry created'), htmlspecialchars($this->dn));
467 }
468 throw new LAMException(sprintf(_('Was unable to create DN: %s.'), $this->dn), getExtendedLDAPErrorMessage($ldap));
469 }
470
471 }
472
473 /**
474 * Renames an LDAP entry.
475 *
476 * @author Roland Gruber
477 */
478 class RenameEntryTask implements ImporterTask {
479
480 private string $dn;
481 private string $newRdn;
482 private bool $deleteOldRdn;
483
484 /**
485 * Constructor
486 *
487 * @param string $dn DN
488 * @param string $newRdn new RDN value
489 * @param bool $deleteOldRdn delete old RDN value
490 */
491 public function __construct(string $dn, string $newRdn, bool $deleteOldRdn) {
492 $this->dn = $dn;
493 $this->newRdn = $newRdn;
494 $this->deleteOldRdn = $deleteOldRdn;
495 }
496
497 /**
498 * {@inheritDoc}
499 * @see ImporterTask::run
500 */
501 public function run(): string {
502 $ldap = $_SESSION['ldap']->server();
503 $success = @ldap_rename($ldap, $this->dn, $this->newRdn, '', $this->deleteOldRdn);
504 if ($success) {
505 return Importer::formatMessage('INFO', _('Rename successful!'), htmlspecialchars($this->dn));
506 }
507 throw new LAMException(_('Could not rename the entry.') . '<br>' . $this->dn, getExtendedLDAPErrorMessage($ldap));
508 }
509
510 }
511
512 /**
513 * Deletes an LDAP entry.
514 *
515 * @author Roland Gruber
516 */
517 class DeleteEntryTask implements ImporterTask {
518
519 private string $dn;
520
521 /**
522 * Constructor
523 *
524 * @param string $dn DN
525 */
526 public function __construct(string $dn) {
527 $this->dn = $dn;
528 }
529
530 /**
531 * {@inheritDoc}
532 * @see ImporterTask::run
533 */
534 public function run(): string {
535 $ldap = $_SESSION['ldap']->server();
536 $success = @ldap_delete($ldap, $this->dn);
537 if ($success) {
538 return Importer::formatMessage('INFO', sprintf(_('Successfully deleted DN %s'), $this->dn), '');
539 }
540 throw new LAMException(_('Could not delete the entry.') . '<br>' . $this->dn, getExtendedLDAPErrorMessage($ldap));
541 }
542
543 }
544
545 /**
546 * Combines multiple import tasks.
547 *
548 * @author Roland Gruber
549 */
550 class MultiTask implements ImporterTask {
551
552 /**
553 * @var ImporterTask[] tasks
554 */
555 private array $tasks;
556
557 /**
558 * @var string DN
559 */
560 private string $dn;
561
562 /**
563 * Constructor
564 *
565 * @param ImporterTask[] $tasks tasks
566 * @param string $dn DN
567 */
568 public function __construct(array $tasks, string $dn) {
569 $this->tasks = $tasks;
570 $this->dn = $dn;
571 }
572
573 /**
574 * {@inheritDoc}
575 * @see ImporterTask::run
576 */
577 public function run(): string {
578 foreach ($this->tasks as $task) {
579 $task->run();
580 }
581 return Importer::formatMessage('INFO', _('LDAP operation successful.'), htmlspecialchars($this->dn));
582 }
583
584 /**
585 * Returns the list of subtasks.
586 *
587 * @return ImporterTask[]
588 */
589 public function getTasks(): array {
590 return $this->tasks;
591 }
592
593 }
594
595 /**
596 * Adds attributes to an existing LDAP entry.
597 *
598 * @author Roland Gruber
599 */
600 class AddAttributesTask implements ImporterTask {
601
602 private string $dn;
603 /** @var array<string, string[]> $attributes attributes */
604 private array $attributes;
605
606 /**
607 * Constructor
608 *
609 * @param string $dn DN
610 * @param array<string, string[]> $attributes list of attributes
611 */
612 public function __construct(string $dn, array $attributes) {
613 $this->dn = $dn;
614 $this->attributes = $attributes;
615 }
616
617 /**
618 * {@inheritDoc}
619 * @see ImporterTask::run
620 */
621 public function run(): string {
622 $ldap = $_SESSION['ldap']->server();
623 $success = @ldap_mod_add($ldap, $this->dn, $this->attributes);
624 if ($success) {
625 return '';
626 }
627 throw new LAMException(sprintf(_('Was unable to create DN: %s.'), $this->dn), getExtendedLDAPErrorMessage($ldap));
628 }
629
630 /**
631 * Returns the DN.
632 *
633 * @return string DN
634 */
635 public function getDn(): string {
636 return $this->dn;
637 }
638
639 /**
640 * Returns the attributes to add.
641 *
642 * @return array<string, string[]> attributes (array('attr' => array('val1', 'val2')))
643 */
644 public function getAttributes(): array {
645 return $this->attributes;
646 }
647
648 }
649
650 /**
651 * Deletes attributes from an existing LDAP entry.
652 *
653 * @author Roland Gruber
654 */
655 class DeleteAttributesTask implements ImporterTask {
656
657 private string $dn;
658 /** @var array<string, string[]> $attributes attributes */
659 private array $attributes;
660 private string $attributeName;
661
662 /**
663 * Constructor
664 *
665 * @param string $dn DN
666 * @param string $attributeName attribute name
667 * @param array<string, string[]> $attributes list of attributes
668 */
669 public function __construct(string $dn, string $attributeName, array $attributes) {
670 $this->dn = $dn;
671 $this->attributeName = $attributeName;
672 $this->attributes = $attributes;
673 }
674
675 /**
676 * {@inheritDoc}
677 * @see ImporterTask::run
678 */
679 public function run(): string {
680 $ldap = $_SESSION['ldap']->server();
681 if (!empty($this->attributes)) {
682 $success = @ldap_mod_del($ldap, $this->dn, $this->attributes);
683 }
684 else {
685 $success = @ldap_modify($ldap, $this->dn, [$this->attributeName => []]);
686 }
687 if ($success) {
688 return '';
689 }
690 throw new LAMException(sprintf(_('Was unable to create DN: %s.'), $this->dn), getExtendedLDAPErrorMessage($ldap));
691 }
692
693 /**
694 * Returns the DN.
695 *
696 * @return string DN
697 */
698 public function getDn(): string {
699 return $this->dn;
700 }
701
702 /**
703 * Returns the attributes to add.
704 *
705 * @return array<string, string[]> attributes (array('attr' => array('val1', 'val2')))
706 */
707 public function getAttributes(): array {
708 return $this->attributes;
709 }
710
711 /**
712 * Returns the attributes name.
713 *
714 * @return string name
715 */
716 public function getAttributeName(): string {
717 return $this->attributeName;
718 }
719
720 }
721
722 /**
723 * Replaces attributes in an existing LDAP entry.
724 *
725 * @author Roland Gruber
726 */
727 class ReplaceAttributesTask implements ImporterTask {
728
729 private string $dn;
730 /** @var array<string, string[]> $attributes attributes */
731 private array $attributes;
732
733 /**
734 * Constructor
735 *
736 * @param string $dn DN
737 * @param array<string, string[]> $attributes list of attributes
738 */
739 public function __construct(string $dn, array $attributes) {
740 $this->dn = $dn;
741 $this->attributes = $attributes;
742 }
743
744 /**
745 * {@inheritDoc}
746 * @see ImporterTask::run
747 */
748 public function run(): string {
749 $ldap = $_SESSION['ldap']->server();
750 $success = @ldap_modify($ldap, $this->dn, $this->attributes);
751 if ($success) {
752 return '';
753 }
754 throw new LAMException(sprintf(_('Was unable to create DN: %s.'), $this->dn), getExtendedLDAPErrorMessage($ldap));
755 }
756
757 /**
758 * Returns the DN. Used for unit test.
759 *
760 * @return string DN
761 */
762 public function getDn(): string {
763 return $this->dn;
764 }
765
766 /**
767 * Returns the attributes to add. Used for unit test.
768 *
769 * @return array<string, string[]> attributes (array('attr' => array('val1', 'val2')))
770 */
771 public function getAttributes(): array {
772 return $this->attributes;
773 }
774
775 }