Debian Codegraph @

lib/export.inc

raw
1 <?php
2
3 namespace LAM\TOOLS\IMPORT_EXPORT;
4
5 use htmlStatusMessage;
6 use LAMException;
7 use LamTemporaryFilesManager;
8
9 /*
10
11 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
12 Copyright (C) 2018 - 2026 Roland Gruber
13
14 This program is free software; you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation; either version 2 of the License, or
17 (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27
28 */
29
30 /**
31 * LDIF export.
32 *
33 * @author Roland Gruber
34 * @package tools
35 */
36
37 /** LDAP handle */
38 include_once(__DIR__ . '/ldap.inc');
39
40 /**
41 * Creates LDAP accounts for file upload.
42 *
43 * @author Roland Gruber
44 * @package tools
45 */
46 class Exporter {
47
48 private const DATA = 'data';
49 private const STATUS = 'status';
50 private const FILE = 'file';
51 private const OUTPUT = 'output';
52
53 private string $baseDn;
54 private string $searchScope;
55 private string $filter;
56 private string $attributes;
57 private bool $includeSystem;
58 private bool $saveAsFile;
59 private string $format;
60 private string $ending;
61
62 /**
63 * Constructor.
64 *
65 * @param string $baseDn base DN
66 * @param string $searchScope search scope (base, one, sub)
67 * @param string $filter search filter
68 * @param string $attributes attributes to return
69 * @param bool $includeSystem include system attributes
70 * @param bool $saveAsFile return as file
71 * @param string $format output format (LDIF, CSV)
72 * @param string $ending line endings (windows, unix)
73 */
74 public function __construct(string $baseDn, string $searchScope, string $filter, string $attributes, bool $includeSystem, bool $saveAsFile, string $format, string $ending) {
75 $this->baseDn = $baseDn;
76 $this->searchScope = $searchScope;
77 $this->filter = $filter;
78 $this->attributes = $attributes;
79 $this->includeSystem = $includeSystem;
80 $this->saveAsFile = $saveAsFile;
81 $this->format = $format;
82 $this->ending = $ending;
83 }
84
85 /**
86 * Starts the export process.
87 *
88 * @return string JSON result
89 */
90 public function doExport(): string {
91 try {
92 $this->checkParameters();
93 $results = $this->getLDAPData();
94 return $this->writeDataAndReturnJson($results);
95 }
96 catch (LAMException $e) {
97 $data = self::formatMessage('ERROR', $e->getTitle(), $e->getMessage());
98 $status = [
99 self::STATUS => 'failed',
100 self::DATA => $data
101 ];
102 return json_encode($status);
103 }
104 }
105
106 /**
107 * Returns the HTML for an error message.
108 *
109 * @param string $type message type (e.g. INFO)
110 * @param string|null $title title
111 * @param string|null $message message
112 * @return string HTML
113 */
114 public static function formatMessage(string $type, ?string $title, ?string $message): string {
115 $msg = new htmlStatusMessage($type, $title, $message);
116 ob_start();
117 $msg->generateHTML(null, [$msg], [], true);
118 $data = ob_get_contents();
119 ob_clean();
120 return $data;
121 }
122
123 /**
124 * Checks the input parameters for validity.
125 *
126 * @throws LAMException in case of errors
127 */
128 private function checkParameters(): void {
129 if (!get_preg($this->baseDn, 'dn')) {
130 throw new LAMException(_('Please enter a valid DN in the field:'), _('Base DN'));
131 }
132 }
133
134 /**
135 * Returns the LDAP entries
136 *
137 * @return array<string, string[]|string>[] LDAP entries
138 * @throws LAMException error reading data
139 */
140 private function getLDAPData(): array {
141 $attributes = preg_split('/,[ ]*/', $this->attributes);
142 if ($this->includeSystem) {
143 $attributes = array_merge($attributes, ['+', 'passwordRetryCount', 'accountUnlockTime', 'nsAccountLock',
144 'nsRoleDN', 'passwordExpirationTime', 'pwdChangedTime']);
145 }
146 $attributes = array_unique($attributes);
147 switch ($this->searchScope) {
148 case 'base':
149 return [ldapGetDN($this->baseDn, $attributes)];
150 case 'one':
151 $entries = ldapListDN($this->baseDn, $this->filter, $attributes);
152 usort($entries, compareLDAPEntriesByDn(...));
153 return $entries;
154 case 'sub':
155 $entries = searchLDAP($this->baseDn, $this->filter, $attributes);
156 usort($entries, compareLDAPEntriesByDn(...));
157 return $entries;
158 default:
159 throw new LAMException('Invalid scope');
160 }
161 }
162
163 /**
164 * Writes the entries to file/response and prints JSON.
165 *
166 * @param array<string, string[]|string>[] $entries LDAP entries
167 * @return string JSON
168 * @throws LAMException error writing PDF
169 */
170 private function writeDataAndReturnJson(array &$entries): string {
171 $lineEnding = ($this->ending === 'windows') ? "\r\n" : "\n";
172 if ($this->format === 'csv') {
173 $output = $this->getCsvOutput($entries, $lineEnding);
174 }
175 elseif ($this->format === 'ldif') {
176 $output = $this->getLdifOutput($entries, $lineEnding);
177 }
178 else {
179 throw new LAMException(_('Invalid format'));
180 }
181 if ($this->saveAsFile) {
182 $temporaryFilesManager = new LamTemporaryFilesManager();
183 $filename = $temporaryFilesManager->registerTemporaryFile('.' . $this->format);
184 $handle = $temporaryFilesManager->openTemporaryFileForWrite($filename);
185 fwrite($handle, $output);
186 fclose($handle);
187 return json_encode([
188 self::FILE => $temporaryFilesManager->getDownloadLink($filename),
189 self::STATUS => 'done'
190 ]);
191 }
192 return json_encode([
193 self::OUTPUT => htmlspecialchars($output, ENT_NOQUOTES),
194 self::STATUS => 'done'
195 ]);
196 }
197
198 /**
199 * Converts the given LDAP entries to CSV format.
200 *
201 * @param array<string, string[]|string>[] $entries entries
202 * @param string $lineEnding line ending
203 * @return string CSV
204 */
205 private function getCsvOutput(array &$entries, string $lineEnding): string {
206 $attributeNames = [];
207 foreach ($entries as $entry) {
208 $entryAttributeNames = array_keys($entry);
209 foreach ($entryAttributeNames as $name) {
210 if (!in_array($name, $attributeNames)) {
211 $attributeNames[] = $name;
212 }
213 }
214 }
215 $attributeNames = array_delete(['dn'], $attributeNames);
216 sort($attributeNames);
217 array_unshift($attributeNames, 'dn');
218
219 $attributeNamesQuoted = array_map($this->escapeCsvAndAddQuotes(...), $attributeNames);
220 $output = '';
221 // header
222 $output .= implode(',', $attributeNamesQuoted) . $lineEnding;
223 // content
224 foreach ($entries as $entry) {
225 $values = [];
226 foreach ($attributeNames as $name) {
227 if (!isset($entry[$name])) {
228 $values[] = $this->escapeCsvAndAddQuotes('');
229 }
230 elseif (is_array($entry[$name])) {
231 $values[] = $this->escapeCsvAndAddQuotes(implode(' | ', $entry[$name]));
232 }
233 else {
234 $values[] = $this->escapeCsvAndAddQuotes($entry[$name]);
235 }
236 }
237 $output .= implode(',', $values) . $lineEnding;
238 }
239 return $output;
240 }
241
242 /**
243 * Escapes a CSV value and adds quotes around it.
244 *
245 * @param string $value CSV value
246 * @return string escaped and quoted value
247 */
248 private function escapeCsvAndAddQuotes(string $value): string {
249 return '"' . str_replace('"', '""', $value) . '"';
250 }
251
252 /**
253 * Converts the given LDAP entries to LDIF format.
254 *
255 * @param array<string, string[]|string>[] $entries entries
256 * @param string $lineEnding line ending
257 * @return string LDIF
258 */
259 private function getLdifOutput(array &$entries, string $lineEnding): string {
260 $output = '#' . $lineEnding;
261 $output .= '# ' . _('Base DN') . ': ' . $this->baseDn . $lineEnding;
262 $output .= '# ' . _('Search scope') . ': ' . $this->searchScope . $lineEnding;
263 $output .= '# ' . _('Search filter') . ': ' . $this->filter . $lineEnding;
264 $output .= '# ' . _('Total entries') . ': ' . count($entries) . $lineEnding;
265 $output .= '#' . $lineEnding;
266 $output .= '# Generated by LDAP Account Manager on ' . date('Y-m-d H:i:s') . $lineEnding;
267 $output .= $lineEnding;
268 $output .= $lineEnding;
269 $output .= 'version: 1';
270 $output .= $lineEnding;
271 $output .= $lineEnding;
272 foreach ($entries as $entry) {
273 $output .= 'dn: ' . $entry['dn'] . $lineEnding;
274 unset($entry['dn']);
275 ksort($entry);
276 foreach ($entry as $attributeName => $values) {
277 foreach ($values as $value) {
278 if ($this->isPlainAscii($value)) {
279 $output .= $this->wrapLdif($attributeName . ': ' . $value, $lineEnding) . $lineEnding;
280 }
281 else {
282 $output .= $this->wrapLdif($attributeName . ':: ' . base64_encode($value), $lineEnding) . $lineEnding;
283 }
284 }
285 }
286 $output .= $lineEnding;
287 }
288
289 return $output;
290 }
291
292 /**
293 * Splits the LDIF line if needed.
294 *
295 * @param string $content line content
296 * @param string $lineEnding line ending
297 * @return string wrapped string
298 */
299 private function wrapLdif(string $content, string $lineEnding): string {
300 $line_length = 76;
301 if (strlen($content) <= $line_length) {
302 return $content;
303 }
304 $wrappedContent = substr($content, 0, $line_length) . $lineEnding;
305 $contentLeft = substr($content, $line_length);
306 $line_length -= 1;
307 $lines = str_split($contentLeft, $line_length);
308 foreach ($lines as $line) {
309 $wrappedContent .= ' ' . $line . $lineEnding;
310 }
311 return trim($wrappedContent);
312 }
313
314 /**
315 * Checks if the value is plain ASCII.
316 *
317 * @param string $content content to check
318 * @return bool is plain ASCII
319 */
320 private function isPlainAscii($content) {
321 for ($i = 0; $i < strlen($content); $i++) {
322 if (ord($content[$i]) < 32 || ord($content[$i]) > 127) {
323 return false;
324 }
325 }
326 return true;
327 }
328
329 }