Debian Codegraph @

lib/upload.inc

raw
1 <?php
2
3 namespace LAM\UPLOAD;
4
5 use LAM\TYPES\ConfiguredType;
6 use LAMException;
7 use LamTemporaryFilesManager;
8 use ZipArchive;
9 use accountContainer;
10 use function LAM\PDF\createModulePDF;
11
12 /*
13
14 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
15 Copyright (C) 2016 - 2025 Roland Gruber
16
17 This program is free software; you can redistribute it and/or modify
18 it under the terms of the GNU General Public License as published by
19 the Free Software Foundation; either version 2 of the License, or
20 (at your option) any later version.
21
22 This program is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 GNU General Public License for more details.
26
27 You should have received a copy of the GNU General Public License
28 along with this program; if not, write to the Free Software
29 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30
31 */
32
33 /**
34 * Creates LDAP accounts for file upload.
35 *
36 * @author Roland Gruber
37 * @package tools
38 */
39
40 /** LDAP handle */
41 include_once(__DIR__ . '/ldap.inc');
42 /** PDF */
43 include_once(__DIR__ . '/pdf.inc');
44
45 /**
46 * Creates LDAP accounts for file upload.
47 *
48 * @author Roland Gruber
49 * @package tools
50 */
51 class Uploader {
52
53 /**
54 * @var array<string, string|string[]>[] $accounts LDAP accounts
55 */
56 private array $accounts;
57 /**
58 * @var array<int, string>[] $data data
59 */
60 private array $data;
61 private ConfiguredType $type;
62 private int $endTime;
63
64 private const TIME_LIMIT = 10;
65
66 /**
67 * Cleans old session data.
68 */
69 public static function cleanSession(): void {
70 foreach (array_keys($_SESSION) as $key) {
71 if (str_starts_with($key, 'mass_')) {
72 unset($_SESSION[$key]);
73 }
74 }
75 }
76
77 /**
78 * Constructor
79 *
80 * @param ConfiguredType $type account type
81 */
82 public function __construct(ConfiguredType $type) {
83 $this->accounts = json_decode(lamDecrypt($_SESSION['mass_accounts']), true);
84 $this->data = json_decode(lamDecrypt($_SESSION['mass_data']), true);
85 $this->type = $type;
86 $startTime = time();
87 $maxTime = get_cfg_var('max_execution_time') - 5;
88 if ($maxTime > self::TIME_LIMIT) {
89 $maxTime = self::TIME_LIMIT;
90 }
91 if ($maxTime <= 0) {
92 $maxTime = self::TIME_LIMIT;
93 }
94 $this->endTime = $startTime + $maxTime;
95 }
96
97 /**
98 * Start or continues the file upload.
99 *
100 * @return string JSON of upload status
101 */
102 public function doUpload(): string {
103 $this->securityCheck();
104 if (!isset($_SESSION['mass_counter'])) {
105 return $this->startUpload();
106 }
107 elseif ($_SESSION['mass_counter'] < count($this->accounts)) {
108 return $this->continueUpload();
109 }
110 elseif (!isset($_SESSION['mass_postActions']['finished'])) {
111 return $this->runPostActions();
112 }
113 elseif (($_SESSION['mass_pdf']['structure'] != null) && !isset($_SESSION['mass_pdf']['finished'])) {
114 return $this->createPDF();
115 }
116 return $this->buildUploadStatus(100, true, '', 100, true, 100);
117 }
118
119 /**
120 * Continues to upload accounts.
121 *
122 * @return string JSON of upload status
123 */
124 private function continueUpload(): string {
125 while (($_SESSION['mass_counter'] < count($this->accounts)) && ($this->endTime > time())) {
126 $this->uploadEntry($_SESSION['mass_counter']);
127 $_SESSION['mass_counter']++;
128 }
129 $accountsProgress = round(($_SESSION['mass_counter'] * 100) / count($this->accounts));
130 $accountsFinished = ($_SESSION['mass_counter'] == count($this->accounts));
131 return $this->buildUploadStatus($accountsProgress, $accountsFinished);
132 }
133
134 /**
135 * Performs the upload of a single LDAP entry.
136 *
137 * @param int $position position in $this->accounts.
138 */
139 private function uploadEntry($position): void {
140 $attrs = $this->accounts[$position];
141 $dn = $attrs['dn'];
142 unset($attrs['dn']);
143 // remove informational attributes
144 foreach ($attrs as $key => $value) {
145 if (str_starts_with($key, 'INFO.')) {
146 unset($attrs[$key]);
147 }
148 }
149 // run preactions
150 $preAttributes = [];
151 foreach ($attrs as $key => $value) {
152 $preAttributes[$key] = &$attrs[$key];
153 }
154 $preAttributes['dn'] = &$dn;
155 $preMessages = doUploadPreActions($this->type, $_SESSION['mass_selectedModules'], $preAttributes);
156 $preActionOk = true;
157 for ($i = 0; $i < count($preMessages); $i++) {
158 if (($preMessages[$i][0] == 'ERROR') || ($preMessages[$i][0] == 'WARN')) {
159 $preActionOk = false;
160 $_SESSION['mass_errors'][] = $preMessages[$i];
161 }
162 }
163 if ($preActionOk) {
164 $errors = $this->deleteOldEntryIfNeeded($dn, $this->accounts[$position]);
165 if (!empty($errors)) {
166 $_SESSION['mass_errors'] = array_merge($_SESSION['mass_errors'], $errors);
167 $_SESSION['mass_failed'][] = $position;
168 return;
169 }
170 // add LDAP entry
171 $success = @ldap_add($_SESSION['ldap']->server(), $dn, $attrs);
172 if (!$success) {
173 $errorMessage = [
174 "ERROR",
175 _("LAM was unable to create account %s! An LDAP error occurred."),
176 getDefaultLDAPErrorString($_SESSION['ldap']->server()),
177 [$position]];
178 $_SESSION['mass_errors'][] = $errorMessage;
179 $_SESSION['mass_failed'][] = $position;
180 }
181 }
182 }
183
184 /**
185 * Deletes an existing entry if the overwrite option is used.
186 *
187 * @param string $dn DN
188 * @param array<string, string|string[]> $attributes attribute list
189 * @return string[][] list of error messages
190 */
191 private function deleteOldEntryIfNeeded($dn, $attributes): array {
192 if (isset($attributes['INFO.overwrite']) && ($attributes['INFO.overwrite'] === 'true')) {
193 $attrs = ldapGetDN($dn, ['dn']);
194 if ($attrs !== null) {
195 return deleteDN($dn, true);
196 }
197 }
198 return [];
199 }
200
201 /**
202 * Starts the file upload.
203 *
204 * @return string JSON of upload status
205 */
206 private function startUpload(): string {
207 $_SESSION['mass_counter'] = 0;
208 return $this->buildUploadStatus();
209 }
210
211 /**
212 * Returns the upload status as JSON.
213 *
214 * @param number $accountsProgress progress for LDAP entries
215 * @param bool $accountsFinished all entries in LDAP
216 * @param string $postActionsTitle title for current post action
217 * @param number $postActionsProgress progress for post actions
218 * @param bool $postActionsFinished post actions finished
219 * @param number $pdfProgress PDF creation progress
220 * @return string JSON status
221 */
222 private function buildUploadStatus($accountsProgress = 0, $accountsFinished = false,
223 $postActionsTitle = '', $postActionsProgress = 0, $postActionsFinished = false,
224 $pdfProgress = 0): string {
225 $pdfFinished = ($_SESSION['mass_pdf']['structure'] == null) || isset($_SESSION['mass_pdf']['finished']);
226 $allDone = $accountsFinished && $postActionsFinished && $pdfFinished;
227 $errorHtml = '';
228 if ($allDone && !empty($_SESSION['mass_errors'])) {
229 foreach ($_SESSION['mass_errors'] as $error) {
230 $text = $error[2] ?? '';
231 $vars = $error[3] ?? [];
232 $errorHtml .= StatusMessage($error[0], $error[1], $text, $vars, true);
233 }
234 }
235 $status = [
236 'title' => _("LDAP upload in progress. Please wait."),
237 'titleFinished' => _("Upload has finished"),
238 'titleErrors' => _("There were errors while uploading:"),
239 'titlePDF' => _('Create PDF files'),
240 'accountsProgress' => $accountsProgress,
241 'accountsFinished' => $accountsFinished,
242 'postActionsTitle' => $postActionsTitle,
243 'postActionsProgress' => $postActionsProgress,
244 'postActionsFinished' => $postActionsFinished,
245 'pdfProgress' => $pdfProgress,
246 'pdfFinished' => $pdfFinished,
247 'allDone' => $allDone,
248 'errorHtml' => $errorHtml,
249 'typeId' => $this->type->getId()
250 ];
251 return json_encode($status);
252 }
253
254 /**
255 * Checks for security violations and stops processing if needed.
256 */
257 private function securityCheck(): void {
258 if (!isLoggedIn()
259 || $this->type->isHidden()
260 || !checkIfNewEntriesAreAllowed($this->type->getId())
261 || !checkIfWriteAccessIsAllowed($this->type->getId())) {
262 die;
263 }
264 }
265
266 /**
267 * Performs any post-create actions by modules.
268 *
269 * @return string JSON of upload status
270 */
271 private function runPostActions(): string {
272 $return = $this->runModulePostActions();
273 while (!isset($_SESSION['mass_postActions']['finished']) && ($this->endTime > time())) {
274 $return = $this->runModulePostActions();
275 }
276 $title = _("Additional tasks for module:") . ' ' . getModuleAlias($return['module'], $this->type->getScope());
277 $progress = round($return['progress']);
278 $finished = isset($_SESSION['mass_postActions']['finished']);
279 return $this->buildUploadStatus(100, true, $title, $progress, $finished);
280 }
281
282 /**
283 * Runs a single post create action by modules.
284 *
285 * @return array<string, string|int|string[]> status array
286 */
287 private function runModulePostActions(): array {
288 $return = doUploadPostActions($this->type, $this->data, $_SESSION['mass_ids'], $_SESSION['mass_failed'], $_SESSION['mass_selectedModules'], $this->accounts);
289 if ($return['status'] == 'finished') {
290 $_SESSION['mass_postActions']['finished'] = true;
291 }
292 if (isset($return['errors'])) {
293 for ($i = 0; $i < count($return['errors']); $i++) {
294 $_SESSION['mass_errors'][] = $return['errors'][$i];
295 }
296 }
297 return $return;
298 }
299
300 /**
301 * Creates the PDF files.
302 *
303 * @return string JSON of upload status
304 * @throws LAMException error during PDF creation
305 */
306 private function createPDF(): string {
307 $file = $_SESSION['mass_pdf']['file'];
308 $pdfStructure = $_SESSION['mass_pdf']['structure'];
309 $font = $_SESSION['mass_pdf']['font'];
310 $pdfZip = new ZipArchive();
311 $tempFilesManager = new LamTemporaryFilesManager();
312 if ($_SESSION['mass_pdf']['counter'] == 0) {
313 $pdfZipResult = @$pdfZip->open($tempFilesManager->getFileSystemPath($file), ZipArchive::OVERWRITE);
314 if (!$pdfZipResult) {
315 $_SESSION['mass_errors'][] = ['ERROR', _('Unable to create ZIP file for PDF export.')];
316 $_SESSION['mass_pdf']['finished'] = true;
317 }
318 }
319 else {
320 @$pdfZip->open($tempFilesManager->getFileSystemPath($file));
321 }
322 while (!isset($_SESSION['mass_pdf']['finished']) && ($this->endTime > time())) {
323 $attrs = $this->accounts[$_SESSION['mass_pdf']['counter']];
324 $dn = $attrs['dn'];
325 // get informational attributes
326 $infoAttributes = [];
327 foreach ($attrs as $key => $value) {
328 if (str_starts_with($key, 'INFO.')) {
329 $infoAttributes[$key] = $value;
330 }
331 }
332 // load account
333 $_SESSION['mass_pdfAccount'] = new accountContainer($this->type, 'mass_pdfAccount');
334 $pdfErrors = $_SESSION['mass_pdfAccount']->load_account($dn, $infoAttributes);
335 if (count($pdfErrors) > 0) {
336 $_SESSION['mass_errors'] = array_merge($_SESSION['mass_errors'], $pdfErrors);
337 $_SESSION['mass_pdf']['finished'] = true;
338 break;
339 }
340 // create and save PDF
341 $pdfContent = createModulePDF([$_SESSION['mass_pdfAccount']], $pdfStructure, $font, true);
342 $fileName = $dn . '.pdf';
343 $pdfZip->addFromString($fileName, $pdfContent);
344 $_SESSION['mass_pdf']['counter']++;
345 if ($_SESSION['mass_pdf']['counter'] >= count($this->accounts)) {
346 $_SESSION['mass_pdf']['finished'] = true;
347 }
348 }
349 @$pdfZip->close();
350 $progress = round(($_SESSION['mass_pdf']['counter'] * 100) / count($this->accounts));
351 return $this->buildUploadStatus(100, true, '', 100, true, $progress);
352 }
353
354 }