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