Debian Codegraph @

lib/modules/quota.inc

raw
1 <?php
2
3 use LAM\PDF\PDFTable;
4 use LAM\PDF\PDFTableCell;
5 use LAM\PDF\PDFTableRow;
6 use LAM\REMOTE\Remote;
7 use LAM\REMOTE\RemoteServerConfiguration;
8 use LAM\TYPES\ConfiguredType;
9
10 /*
11
12 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
13 Copyright (C) 2003 - 2006 Tilo Lutz
14 2007 - 2026 Roland Gruber
15
16 This program is free software; you can redistribute it and/or modify
17 it under the terms of the GNU General Public License as published by
18 the Free Software Foundation; either version 2 of the License, or
19 (at your option) any later version.
20
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 GNU General Public License for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 */
30
31
32 /**
33 * Manages quotas for users and groups.
34 *
35 * @package modules
36 *
37 * @author Tilo Lutz
38 * @author Roland Gruber
39 * @author Michael Duergner
40 */
41
42 /**
43 * Manages quotas for users and groups.
44 *
45 * @package modules
46 */
47 class quota extends baseModule {
48
49 /** delimiter for lamdaemon commands */
50 private static string $SPLIT_DELIMITER = "###x##y##x###";
51 /** prefix for lamdaemon results */
52 private static string $QUOTA_PREFIX = 'QUOTA_ENTRY ';
53
54 /**
55 * {@inheritDoc}
56 */
57 protected function load_Messages(): void {
58 // error messages for input checks
59 $this->messages['softblock'][0] = ['ERROR', _('Block soft quota'), _('Block soft quota contains invalid characters. Only natural numbers are allowed.')];
60 $this->messages['softblock'][1] = ['ERROR', _('Account %s:') . ' %s', _('Block soft quota contains invalid characters. Only natural numbers are allowed.')];
61 $this->messages['hardblock'][0] = ['ERROR', _('Block hard quota'), _('Block hard quota contains invalid characters. Only natural numbers are allowed.')];
62 $this->messages['hardblock'][1] = ['ERROR', _('Account %s:') . ' %s', _('Block hard quota contains invalid characters. Only natural numbers are allowed.')];
63 $this->messages['softinode'][0] = ['ERROR', _('Inode soft quota'), _('Inode soft quota contains invalid characters. Only natural numbers are allowed.')];
64 $this->messages['softinode'][1] = ['ERROR', _('Account %s:') . ' %s', _('Inode soft quota contains invalid characters. Only natural numbers are allowed.')];
65 $this->messages['hardinode'][0] = ['ERROR', _('Inode hard quota'), _('Inode hard quota contains invalid characters. Only natural numbers are allowed.')];
66 $this->messages['hardinode'][1] = ['ERROR', _('Account %s:') . ' %s', _('Inode hard quota contains invalid characters. Only natural numbers are allowed.')];
67 $this->messages['block_cmp'][0] = ['ERROR', _('Block quota'), _('Block soft quota must be smaller than block hard quota.')];
68 $this->messages['block_cmp'][1] = ['ERROR', _('Account %s:') . ' %s', _('Block soft quota must be smaller than block hard quota.')];
69 $this->messages['inode_cmp'][0] = ['ERROR', _('Inode quota'), _('Inode soft quota must be smaller than inode hard quota.')];
70 $this->messages['inode_cmp'][1] = ['ERROR', _('Account %s:') . ' %s', _('Inode soft quota must be smaller than inode hard quota.')];
71 $this->messages['upload'][0] = ['ERROR', _('Account %s:') . ' %s', _('Quota has wrong format!')];
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 public function can_manage(): bool {
78 return in_array($this->get_scope(), ['user', 'group']);
79 }
80
81 /**
82 * {@inheritDoc}
83 */
84 public function get_metaData(): array {
85 $return = [];
86 // icon
87 $return['icon'] = 'hard-drive.svg';
88 // alias name
89 $return["alias"] = _('Quota');
90 if ($this->get_scope() == 'group') {
91 // module dependencies
92 $return['dependencies'] = ['depends' => [['posixGroup', 'rfc2307bisPosixGroup', 'windowsPosixGroup']], 'conflicts' => []];
93 }
94 if ($this->get_scope() == 'user') {
95 // module dependencies
96 $return['dependencies'] = ['depends' => ['posixAccount'], 'conflicts' => []];
97 }
98 // managed attributes
99 $return['attributes'] = ['uid', 'cn'];
100 // available PDF fields
101 $return['PDF_fields'] = [
102 'quotas' => _('Quota')
103 ];
104 // help entries
105 $numbersHelp = _('Symbols K, M, G and T can be appended to numeric value to express kibibytes, mebibytes, gibibytes and tebibytes for blocks.')
106 . _(' Symbols k, m, g and t can be appended to numeric value to express multiples of 10^3, 10^6, 10^9 and 10^12 inodes.');
107 $return['help'] = [
108 "UsedBlocks" => [
109 "Headline" => _("Used blocks"),
110 "Text" => _("Used blocks. 1000 blocks are usually 1MB")
111 ],
112 "SoftBlockLimit" => [
113 "Headline" => _("Soft block limit"),
114 "Text" => _("Soft block limit.") . '<br>' . $numbersHelp, "SeeAlso" => [
115 'link' => 'https://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Quota.html#ss4.4',
116 'text' => 'Quota How-To']
117 ],
118 "HardBlockLimit" => [
119 "Headline" => _("Hard block limit"),
120 "Text" => _("Hard block limit") . '<br>' . $numbersHelp, "SeeAlso" => [
121 'link' => 'https://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Quota.html#ss4.5',
122 'text' => 'Quota How-To']
123 ],
124 "GraceBlockPeriod" => [
125 "Headline" => _("Grace block period"),
126 "Text" => _("Grace block period. Most filesystems use a fixed maximum value of 7 days."), "SeeAlso" => [
127 'link' => 'https://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Quota.html#ss4.6',
128 'text' => 'Quota How-To']
129 ],
130 "UsedInodes" => [
131 "Headline" => _("Used inodes"),
132 "Text" => _("Used inodes (files)") . '.'
133 ],
134 "SoftInodeLimit" => [
135 "Headline" => _("Soft inode limit"),
136 "Text" => _("Soft inode (files) limit.") . '<br>' . $numbersHelp, "SeeAlso" => [
137 'link' => 'https://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Quota.html#ss4.4',
138 'text' => 'Quota How-To']
139 ],
140 "HardInodeLimit" => [
141 "Headline" => _("Hard inode limit"),
142 "Text" => _("Hard inode (files) limit") . '<br>' . $numbersHelp, "SeeAlso" => [
143 'link' => 'https://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Quota.html#ss4.5',
144 'text' => 'Quota How-To']
145 ],
146 "GraceInodePeriod" => [
147 "Headline" => _("Grace inode period"),
148 "Text" => _("Grace inode (files) period. Most filesystems use a fixed maximum value of 7 days."), "SeeAlso" => [
149 'link' => 'https://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Quota.html#ss4.6',
150 'text' => 'Quota How-To']
151 ],
152 "upload" => [
153 "Headline" => _("Quota"),
154 "Text" => _("Please enter the quota settings for this mount point. The syntax is: {soft block limit},{hard block limit},{soft inode limit},{hard inode limit}")
155 ]
156 ];
157 // self-service field settings
158 $return['selfServiceFieldSettings'] = ['quota' => _('Quota (read-only)')];
159 return $return;
160 }
161
162 /** @var array<string, array<int, int|string>[]> Saves the quota settings */
163 private ?array $quota = null;
164
165 /**
166 * Initializes the quota values.
167 *
168 * @param string $userName user/group name
169 * @param RemoteServerConfiguration[] $lamdaemonServers server configurations
170 */
171 private function initQuotas($userName = null, $lamdaemonServers = null): void {
172 if ($this->quota !== null) {
173 return;
174 }
175 if ($userName === null) {
176 $userName = '+';
177 if (($this->getAccountContainer() != null) && !$this->getAccountContainer()->isNewAccount) {
178 if ($this->get_scope() == 'user') {
179 if (!isset($this->attributes['uid'][0])) {
180 return;
181 }
182 $userName = $this->attributes['uid'][0];
183 }
184 elseif ($this->get_scope() == 'group') {
185 if (!isset($this->attributes['cn'][0])) {
186 return;
187 }
188 $userName = $this->attributes['cn'][0];
189 }
190 }
191 }
192 // get list of lamdaemon servers
193 if ($lamdaemonServers === null) {
194 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
195 }
196 foreach ($lamdaemonServers as $lamdaemonServer) {
197 $server = $lamdaemonServer->getServer();
198 // get quotas
199 $remote = new Remote();
200 try {
201 $remote->connect($lamdaemonServer);
202 }
203 catch (LAMException $e) {
204 logNewMessage(LOG_ERR, $e->getMessage() . ' ' . $e->getTitle());
205 continue;
206 }
207 $quotas = $remote->execute(implode(self::$SPLIT_DELIMITER, [$userName, "quota", "get", $this->get_scope()]));
208 $remote->disconnect();
209 if (empty($quotas)) {
210 continue;
211 }
212 $allQuotas = explode(":", $quotas);
213 array_pop($allQuotas); // remove empty element at the end
214 for ($i = 0; $i < count($allQuotas); $i++) {
215 if (!str_starts_with($allQuotas[$i], self::$QUOTA_PREFIX)) {
216 continue;
217 }
218 $allQuotas[$i] = substr($allQuotas[$i], strlen(self::$QUOTA_PREFIX));
219 $singleQuota = explode(",", $allQuotas[$i]);
220 $singleQuota[1] = $this->formatBlockUsage((int) $singleQuota[1]);
221 $singleQuota[2] = $this->addBlockUnits((int) $singleQuota[2]);
222 $singleQuota[3] = $this->addBlockUnits((int) $singleQuota[3]);
223 $singleQuota[5] = $this->formatInodeUsage((int) $singleQuota[5]);
224 $singleQuota[6] = $this->addInodeUnits((int) $singleQuota[6]);
225 $singleQuota[7] = $this->addInodeUnits((int) $singleQuota[7]);
226 $this->quota[$server][$i] = $singleQuota;
227 if ($this->quota[$server][$i][4] < time()) {
228 $this->quota[$server][$i][4] = '-';
229 }
230 else {
231 $this->quota[$server][$i][4] = intval((((int) $this->quota[$server][$i][4]) - time()) / 3600) . ' ' . _('hours');
232 }
233 if ($this->quota[$server][$i][8] < time()) {
234 $this->quota[$server][$i][8] = '-';
235 }
236 else {
237 $this->quota[$server][$i][8] = intval((((int) $this->quota[$server][$i][8]) - time()) / 3600) . ' ' . _('hours');
238 }
239 }
240 }
241 }
242
243 /**
244 * Adds units (M/G/T) for block numbers.
245 *
246 * @param int $value raw value
247 * @return string value with unit
248 */
249 public function addBlockUnits($value): string {
250 $mebibytes = 1024;
251 $gibibytes = 1024 * $mebibytes;
252 $tebibytes = 1024 * $gibibytes;
253 if (empty($value) || !get_preg((string) $value, 'digit') || ($value < $mebibytes)) {
254 return (string) $value;
255 }
256 if (($value >= $tebibytes) && (($value % $tebibytes) === 0)) {
257 return ($value / $tebibytes) . 'T';
258 }
259 if (($value >= $gibibytes) && (($value % $gibibytes) === 0)) {
260 return ($value / $gibibytes) . 'G';
261 }
262 if (($value % $mebibytes) === 0) {
263 return ($value / $mebibytes) . 'M';
264 }
265 return (string) $value;
266 }
267
268 /**
269 * Formats block usage.
270 *
271 * @param int $value raw value
272 * @return string block usage
273 */
274 public function formatBlockUsage($value): string {
275 $mebibytes = 1024;
276 $gibibytes = 1024 * $mebibytes;
277 $tebibytes = 1024 * $gibibytes;
278 if (empty($value) || !get_preg((string) $value, 'digit') || ($value < $mebibytes)) {
279 return (string) $value;
280 }
281 if ($value >= $tebibytes) {
282 return round($value / $tebibytes, 2) . 'T';
283 }
284 if ($value >= $gibibytes) {
285 return round($value / $gibibytes, 2) . 'G';
286 }
287 return round($value / $mebibytes, 2) . 'M';
288 }
289
290 /**
291 * Adds units (m/g/t) for inode numbers.
292 *
293 * @param int $value raw value
294 * @return string value with unit
295 */
296 public function addInodeUnits($value): string {
297 $kilo = 1000;
298 $million = 1000 * $kilo;
299 $billion = 1000 * $million;
300 $trillion = 1000 * $billion;
301 if (empty($value) || !get_preg((string) $value, 'digit')) {
302 return (string) $value;
303 }
304 if (($value >= $trillion) && (($value % $trillion) === 0)) {
305 return ($value / $trillion) . 't';
306 }
307 if (($value >= $billion) && (($value % $billion) === 0)) {
308 return ($value / $billion) . 'g';
309 }
310 if (($value >= $million) && (($value % $million) === 0)) {
311 return ($value / $million) . 'm';
312 }
313 if (($value >= $kilo) && (($value % $kilo) === 0)) {
314 return ($value / $kilo) . 'k';
315 }
316 return (string) $value;
317 }
318
319 /**
320 * Formats the inode usage.
321 *
322 * @param int $value raw value
323 * @return string value with unit
324 */
325 public function formatInodeUsage($value): string {
326 $kilo = 1000;
327 $million = 1000 * $kilo;
328 $billion = 1000 * $million;
329 $trillion = 1000 * $billion;
330 if (empty($value) || !get_preg((string) $value, 'digit')) {
331 return '-';
332 }
333 if ($value >= $trillion) {
334 return round($value / $trillion, 2) . 't';
335 }
336 if ($value >= $billion) {
337 return round($value / $billion, 2) . 'g';
338 }
339 if ($value >= $million) {
340 return round($value / $million, 2) . 'm';
341 }
342 if ($value >= $kilo) {
343 return round($value / $kilo, 2) . 'k';
344 }
345 return (string) $value;
346 }
347
348 /**
349 * Gets the cn from the Unix group module.
350 *
351 * @return string|null cn attribute
352 */
353 private function getCn(): ?string {
354 $modules = ['posixGroup', 'windowsPosixGroup', 'rfc2307bisPosixGroup', 'groupOfNames', 'groupOfUniqueNames', 'windowsGroup'];
355 for ($i = 0; $i < count($modules); $i++) {
356 if ($this->getAccountContainer()->getAccountModule($modules[$i]) != null) {
357 $attrs = $this->getAccountContainer()->getAccountModule($modules[$i])->getAttributes();
358 if (isset($attrs['cn'][0])) {
359 return $attrs['cn'][0];
360 }
361 }
362 }
363 return null;
364 }
365
366 /**
367 * {@inheritDoc}
368 */
369 public function module_ready(): bool {
370 if ($this->get_scope() == 'user') {
371 $attrs = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
372 if (empty($attrs['uid'][0])) {
373 return false;
374 }
375 }
376 return ($this->get_scope() != 'group') || !empty($this->getCn());
377 }
378
379 /**
380 * {@inheritDoc}
381 */
382 public function postModifyActions(bool $newAccount, array $attributes): array {
383 $messages = [];
384 if (!is_array($this->quota)
385 || ($this->getAccountContainer() === null)
386 || ($this->getAccountContainer()->finalDN === null)) {
387 return $messages;
388 }
389 // determine if this is a user or group account
390 if ($this->get_scope() === 'user') {
391 $attrs = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
392 $id = $attrs['uid'][0];
393 }
394 else {
395 $id = $this->getCn();
396 }
397 // get list of lamdaemon servers
398 $servers = array_keys($this->quota);
399 for ($q = 0; $q < count($servers); $q++) {
400 $server = $servers[$q];
401 $quotastring = "";
402 for ($i = 0; $i < count($this->quota[$server]); $i++) {
403 $quotastring .= $this->quota[$server][$i][0];
404 $quotastring .= ',' . $this->getQuotaNumber($this->quota[$server][$i][2]);
405 $quotastring .= ',' . $this->getQuotaNumber($this->quota[$server][$i][3]);
406 $quotastring .= ',' . $this->getQuotaNumber($this->quota[$server][$i][6]);
407 $quotastring .= ',' . $this->getQuotaNumber($this->quota[$server][$i][7]) . ':';
408 }
409 $remote = new Remote();
410 $remoteServer = $_SESSION['config']->getScriptServerByName($server);
411 try {
412 $remote->connect($remoteServer);
413 }
414 catch (LAMException $e) {
415 $messages[] = ['ERROR', $e->getTitle(), $e->getMessage()];
416 continue;
417 }
418 $output = $remote->execute(implode(self::$SPLIT_DELIMITER, [$id, "quota", "set", $this->get_scope(), "$quotastring\n"]));
419 if (str_starts_with($output, 'ERROR,')) {
420 $messages[] = ['ERROR', $server, _('Unable to set quota.')];
421 }
422 $remote->disconnect();
423 }
424 return $messages;
425 }
426
427 /**
428 * Returns the quota value as plain number.
429 *
430 * @param string $quotaInput quota value (might contain e.g. "K" for KB)
431 * @return int quota number
432 */
433 public function getQuotaNumber($quotaInput) {
434 if (empty($quotaInput) || (strlen($quotaInput) < 2)) {
435 return (int) $quotaInput;
436 }
437 if (str_ends_with($quotaInput, 'K')) {
438 return (int) substr($quotaInput, 0, -1);
439 }
440 if (str_ends_with($quotaInput, 'M')) {
441 return 1024 * ((int) substr($quotaInput, 0, -1));
442 }
443 if (str_ends_with($quotaInput, 'G')) {
444 return 1024 * 1024 * ((int) substr($quotaInput, 0, -1));
445 }
446 if (str_ends_with($quotaInput, 'T')) {
447 return 1024 * 1024 * 1024 * ((int) substr($quotaInput, 0, -1));
448 }
449 if (str_ends_with($quotaInput, 'k')) {
450 return 1000 * ((int) substr($quotaInput, 0, -1));
451 }
452 if (str_ends_with($quotaInput, 'm')) {
453 return 1000 * 1000 * ((int) substr($quotaInput, 0, -1));
454 }
455 if (str_ends_with($quotaInput, 'g')) {
456 return 1000 * 1000 * 1000 * ((int) substr($quotaInput, 0, -1));
457 }
458 if (str_ends_with($quotaInput, 't')) {
459 return 1000 * 1000 * 1000 * 1000 * ((int) substr($quotaInput, 0, -1));
460 }
461 return (int) $quotaInput;
462 }
463
464 /**
465 * {@inheritDoc}
466 */
467 public function preDeleteActions(): array {
468 try {
469 $this->initQuotas();
470 }
471 catch (LAMException $e) {
472 return [['ERROR', $e->getTitle(), $e->getMessage()]];
473 }
474 if (!is_array($this->quota)) {
475 return [];
476 }
477 // determine if this is a user or group account
478 if ($this->get_scope() === 'user') {
479 $attrs = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
480 $id = $attrs['uid'][0];
481 }
482 else {
483 $id = $this->getCn();
484 }
485 $messages = [];
486 // get list of lamdaemon servers
487 $servers = array_keys($this->quota);
488 for ($q = 0; $q < count($servers); $q++) {
489 $server = $servers[$q];
490 $i = 0;
491 $quotastring = "";
492 while (isset($this->quota[$server][$i][0])) {
493 $quotastring = $quotastring . $this->quota[$server][$i][0] . ',0,0,0,0:';
494 $i++;
495 }
496 $remote = new Remote();
497 $remoteServer = $_SESSION['config']->getScriptServerByName($server);
498 try {
499 $remote->connect($remoteServer);
500 }
501 catch (LAMException $e) {
502 $messages[] = ['ERROR', $e->getTitle(), $e->getMessage()];
503 continue;
504 }
505 $remote->execute(implode(self::$SPLIT_DELIMITER, [$id, "quota", "set", $this->get_scope(), "$quotastring\n"]));
506 $remote->disconnect();
507 }
508 return $messages;
509 }
510
511 /**
512 * {@inheritDoc}
513 */
514 public function process_attributes(): array {
515 if (!is_array($this->quota)) {
516 return [];
517 }
518 $errors = [];
519 // get list of lamdaemon servers
520 $servers = array_keys($this->quota);
521 for ($q = 0; $q < count($servers); $q++) {
522 $server = $servers[$q];
523 $id = $this->replaceSpecialChars($server);
524 $i = 0;
525 // loop for every mointpoint with quotas
526 while (isset($this->quota[$server][$i][0])) {
527 $this->quota[$server][$i][2] = $_POST[$i . '_2_' . $id];
528 $this->quota[$server][$i][3] = $_POST[$i . '_3_' . $id];
529 $this->quota[$server][$i][6] = $_POST[$i . '_6_' . $id];
530 $this->quota[$server][$i][7] = $_POST[$i . '_7_' . $id];
531 // Check if values are OK and set automatic values. if not error-variable will be set
532 if (!get_preg($this->quota[$server][$i][2], 'quotaNumber')) {
533 $errors[] = $this->messages['softblock'][0];
534 }
535 if (!get_preg($this->quota[$server][$i][3], 'quotaNumber')) {
536 $errors[] = $this->messages['hardblock'][0];
537 }
538 if (!get_preg($this->quota[$server][$i][6], 'quotaNumber')) {
539 $errors[] = $this->messages['softinode'][0];
540 }
541 if (!get_preg($this->quota[$server][$i][7], 'quotaNumber')) {
542 $errors[] = $this->messages['hardinode'][0];
543 }
544 if ($this->getQuotaNumber($this->quota[$server][$i][2]) > $this->getQuotaNumber($this->quota[$server][$i][3])) {
545 $errors[] = $this->messages['block_cmp'][0];
546 }
547 if ($this->getQuotaNumber($this->quota[$server][$i][6]) > $this->getQuotaNumber($this->quota[$server][$i][7])) {
548 $errors[] = $this->messages['inode_cmp'][0];
549 }
550 $i++;
551 }
552 }
553 return $errors;
554 }
555
556 /**
557 * {@inheritDoc}
558 */
559 public function display_html_attributes(): htmlElement|array {
560 $return = new htmlResponsiveRow();
561 try {
562 $this->initQuotas();
563 }
564 catch (LAMException $e) {
565 $return->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage()));
566 return $return;
567 }
568 if (!is_array($this->quota)) {
569 $return->add(new htmlStatusMessage('ERROR', _('Unable to read quota.')));
570 return $return;
571 }
572 // get list of lamdaemon servers
573 $serverDescriptions = [];
574 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
575 for ($s = 0; $s < count($lamdaemonServers); $s++) {
576 $lamdaemonServer = $lamdaemonServers[$s];
577 $serverDescriptions[$lamdaemonServer->getServer()] = $lamdaemonServer->getLabel();
578 }
579 $servers = array_keys($this->quota);
580 for ($q = 0; $q < count($servers); $q++) {
581 $server = $servers[$q];
582 $id = $this->replaceSpecialChars($server);
583 $title = $server;
584 if ($serverDescriptions[$server] != $server) {
585 $title = $serverDescriptions[$server] . " (" . $server . ")";
586 }
587 $return->add(new htmlSubTitle($title));
588
589 $i = 0;
590 // loop for every mointpoint with enabled quotas
591 while (isset($this->quota[$server][$i][0])) {
592 $return->addLabel(new htmlOutputText(_('Mountpoint')));
593 $return->addField(new htmlOutputText($this->quota[$server][$i][0]));
594 $return->addVerticalSpacer('0.5rem');
595 $usedBlockGroup = new htmlGroup();
596 $usedBlockGroup->addElement(new htmlOutputText($this->quota[$server][$i][1]));
597 $usedBlockGroup->addElement(new htmlSpacer('0.5rem'));
598 $usedBlockGroup->addElement(new htmlHelpLink('UsedBlocks'));
599 $return->addLabel(new htmlOutputText(_('Used blocks')));
600 $return->addField($usedBlockGroup);
601 $return->add(new htmlResponsiveInputField(_('Soft block limit'), $i . '_2_' . $id, $this->quota[$server][$i][2], 'SoftBlockLimit'));
602 $return->add(new htmlResponsiveInputField(_('Hard block limit'), $i . '_3_' . $id, $this->quota[$server][$i][3], 'HardBlockLimit'));
603 $graceBlockPeriodGroup = new htmlGroup();
604 $graceBlockPeriodGroup->addElement(new htmlOutputText($this->quota[$server][$i][4]));
605 $graceBlockPeriodGroup->addElement(new htmlSpacer('0.5rem'));
606 $graceBlockPeriodGroup->addElement(new htmlHelpLink('GraceBlockPeriod'));
607 $return->addLabel(new htmlOutputText(_('Grace block period')));
608 $return->addField($graceBlockPeriodGroup);
609 $usedInodesGroup = new htmlGroup();
610 $usedInodesGroup->addElement(new htmlOutputText($this->quota[$server][$i][5]));
611 $usedInodesGroup->addElement(new htmlSpacer('0.5rem'));
612 $usedInodesGroup->addElement(new htmlHelpLink('UsedInodes'));
613 $return->addLabel(new htmlOutputText(_('Used inodes')));
614 $return->addField($usedInodesGroup);
615 $return->add(new htmlResponsiveInputField(_('Soft inode limit'), $i . '_6_' . $id, $this->quota[$server][$i][6], 'SoftInodeLimit'));
616 $return->add(new htmlResponsiveInputField(_('Hard inode limit'), $i . '_7_' . $id, $this->quota[$server][$i][7], 'HardInodeLimit'));
617 $graceInodePeriodGroup = new htmlGroup();
618 $graceInodePeriodGroup->addElement(new htmlOutputText($this->quota[$server][$i][8]));
619 $graceInodePeriodGroup->addElement(new htmlSpacer('0.5rem'));
620 $graceInodePeriodGroup->addElement(new htmlHelpLink('GraceInodePeriod'));
621 $return->addLabel(new htmlOutputText(_('Grace inode period')));
622 $return->addField($graceInodePeriodGroup);
623 $return->addVerticalSpacer('3rem');
624 $i++;
625 }
626 }
627 return $return;
628 }
629
630 /**
631 * Replaces special characters in HTML name values.
632 *
633 * @param string $input input string
634 * @return string output string
635 */
636 private function replaceSpecialChars($input) {
637 return str_replace(".", "_", $input);
638 }
639
640 /**
641 * {@inheritDoc}
642 */
643 public function get_profileOptions(string $typeId): ?htmlResponsiveRow {
644 $return = new htmlResponsiveRow();
645 $optionsAvailable = false;
646 // get list of lamdaemon servers
647 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
648 try {
649 foreach ($lamdaemonServers as $lamdaemonServer) {
650 $server = $lamdaemonServer->getServer();
651 $id = $this->replaceSpecialChars($server);
652 $description = $lamdaemonServer->getLabel();
653 if ($description != $server) {
654 $description = $description . ' (' . $server . ')';
655 }
656 // Get quotas
657 $remote = new Remote();
658 $remote->connect($lamdaemonServer);
659 $quotas = $remote->execute(implode(self::$SPLIT_DELIMITER, ["+", "quota", "get", $this->get_scope()]));
660 $remote->disconnect();
661 if (empty($quotas)) {
662 continue;
663 }
664 $dirs = explode(":", $quotas);
665 array_pop($dirs); // remove the empty element at the end
666 if (empty($dirs)) {
667 continue;
668 }
669 for ($i = 0; $i < count($dirs); $i++) {
670 if (!str_starts_with($dirs[$i], self::$QUOTA_PREFIX)) {
671 unset($dirs[$i]);
672 $dirs = array_values($dirs);
673 $i--;
674 continue;
675 }
676 $dirs[$i] = substr($dirs[$i], strlen(self::$QUOTA_PREFIX));
677 $dirs[$i] = explode(",", $dirs[$i]);
678 $dirs[$i] = $dirs[$i][0];
679 }
680 $dirs = array_values($dirs);
681 if (count($dirs) < 1) {
682 continue; // stop if no quota directories were found
683 }
684 $optionsAvailable = true;
685 $return->add(new htmlSubTitle($description));
686 for ($i = 0; $i < count($dirs); $i++) {
687 $return->add(new htmlOutputText($dirs[$i]));
688 $sbLimit = new htmlResponsiveInputField(_('Soft block limit'), "quota_softblock_" . $id . "_" . $dirs[$i], null, 'SoftBlockLimit');
689 $sbLimit->setFieldMaxLength(20);
690 $return->add($sbLimit);
691 $hbLimit = new htmlResponsiveInputField(_('Hard block limit'), "quota_hardblock_" . $id . "_" . $dirs[$i], null, 'HardBlockLimit');
692 $hbLimit->setFieldMaxLength(20);
693 $return->add($hbLimit);
694 $siLimit = new htmlResponsiveInputField(_('Soft inode limit'), "quota_softinode_" . $id . "_" . $dirs[$i], null, 'SoftInodeLimit');
695 $siLimit->setFieldMaxLength(20);
696 $return->add($siLimit);
697 $hiLimit = new htmlResponsiveInputField(_('Hard inode limit'), "quota_hardinode_" . $id . "_" . $dirs[$i], null, 'HardInodeLimit');
698 $hiLimit->setFieldMaxLength(20);
699 $return->add($hiLimit);
700 }
701 }
702 }
703 catch (LAMException $e) {
704 $return->add(new htmlStatusMessage('WARN', $e->getTitle()));
705 return $return;
706 }
707 if (!$optionsAvailable) {
708 return null;
709 }
710 return $return;
711 }
712
713 /**
714 * {@inheritDoc}
715 */
716 public function check_profileOptions(array $options, string $typeId): array {
717 $return = [];
718 // get list of lamdaemon servers
719 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
720 foreach ($lamdaemonServers as $lamdaemonServer) {
721 $server = $lamdaemonServer->getServer();
722 $id = $this->replaceSpecialChars($server);
723 // Get quotas
724 $remote = new Remote();
725 try {
726 $remote->connect($lamdaemonServer);
727 }
728 catch (LAMException $e) {
729 $return[] = ['ERROR', $e->getTitle(), $e->getMessage()];
730 continue;
731 }
732 $quotas = $remote->execute(implode(self::$SPLIT_DELIMITER, ["+", "quota", "get", $this->get_scope()]));
733 $remote->disconnect();
734 $dirs = explode(":", $quotas);
735 array_pop($dirs); // remove empty element at the end
736 if (empty($dirs)) {
737 continue;
738 }
739 $quotaDirs = [];
740 foreach ($dirs as $dirString) {
741 if (!str_starts_with($dirString, self::$QUOTA_PREFIX)) {
742 continue;
743 }
744 $dirData = explode(",", substr($dirString, strlen(self::$QUOTA_PREFIX)));
745 $quotaDirs[] = $dirData[0];
746 }
747 foreach ($quotaDirs as $dirName) {
748 if (!empty($options["quota_softblock_" . $id . "_" . $dirName][0]) && !get_preg($options["quota_softblock_" . $id . "_" . $dirName][0], 'quotaNumber')) {
749 $return[] = $this->messages['softblock'][0];
750 }
751 if (!empty($options["quota_hardblock_" . $id . "_" . $dirName][0]) && !get_preg($options["quota_hardblock_" . $id . "_" . $dirName][0], 'quotaNumber')) {
752 $return[] = $this->messages['hardblock'][0];
753 }
754 if (!empty($options["quota_softinode_" . $id . "_" . $dirName][0]) && !get_preg($options["quota_softinode_" . $id . "_" . $dirName][0], 'quotaNumber')) {
755 $return[] = $this->messages['softinode'][0];
756 }
757 if (!empty($options["quota_hardinode_" . $id . "_" . $dirName][0]) && !get_preg($options["quota_hardinode_" . $id . "_" . $dirName][0], 'quotaNumber')) {
758 $return[] = $this->messages['hardinode'][0];
759 }
760 if (!empty($options["quota_softblock_" . $id . "_" . $dirName][0])
761 && !empty($options["quota_hardblock_" . $id . "_" . $dirName][0])
762 && ($this->getQuotaNumber($options["quota_softblock_" . $id . "_" . $dirName][0]) > $this->getQuotaNumber($options["quota_hardblock_" . $id . "_" . $dirName][0]))) {
763 $return[] = $this->messages['block_cmp'][0];
764 }
765 if (!empty($options["quota_softinode_" . $id . "_" . $dirName][0])
766 && !empty($options["quota_hardinode_" . $id . "_" . $dirName][0])
767 && ($this->getQuotaNumber($options["quota_softinode_" . $id . "_" . $dirName][0]) > $this->getQuotaNumber($options["quota_hardinode_" . $id . "_" . $dirName][0]))) {
768 $return[] = $this->messages['inode_cmp'][0];
769 }
770 }
771 }
772 return $return;
773 }
774
775 /**
776 * {@inheritDoc}
777 */
778 public function load_profile(array $profile): void {
779 try {
780 $this->initQuotas();
781 }
782 catch (LAMException $e) {
783 logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
784 }
785 if (!is_array($this->quota)) {
786 return;
787 }
788 $servers = array_keys($this->quota);
789 for ($s = 0; $s < count($servers); $s++) {
790 $server = $servers[$s];
791 $id = $this->replaceSpecialChars($server);
792 for ($i = 0; $i < count($this->quota[$server]); $i++) {
793 $dir = $this->quota[$server][$i][0];
794 if (isset($profile["quota_softblock_" . $id . "_" . $dir])) {
795 $this->quota[$server][$i][2] = $profile["quota_softblock_" . $id . "_" . $dir][0];
796 }
797 if (isset($profile["quota_hardblock_" . $id . "_" . $dir])) {
798 $this->quota[$server][$i][3] = $profile["quota_hardblock_" . $id . "_" . $dir][0];
799 }
800 if (isset($profile["quota_softinode_" . $id . "_" . $dir])) {
801 $this->quota[$server][$i][6] = $profile["quota_softinode_" . $id . "_" . $dir][0];
802 }
803 if (isset($profile["quota_hardinode_" . $id . "_" . $dir])) {
804 $this->quota[$server][$i][7] = $profile["quota_hardinode_" . $id . "_" . $dir][0];
805 }
806 }
807 }
808 }
809
810 /**
811 * {@inheritDoc}
812 */
813 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
814 try {
815 $this->initQuotas();
816 }
817 catch (LAMException $e) {
818 logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
819 return [];
820 }
821 if (!is_array($this->quota)) {
822 return [];
823 }
824 if ($this->quota !== []) {
825 $pdfTable = new PDFTable();
826 // get list of lamdaemon servers
827 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
828 foreach ($lamdaemonServers as $lamdaemonServer) {
829 $server = $lamdaemonServer->getServer();
830 $description = $lamdaemonServer->getLabel();
831 if ($description != $server) {
832 $description = $description . " (" . $server . ")";
833 }
834 if (!isset($this->quota[$server]) || (count($this->quota[$server]) < 1)) {
835 continue;
836 }
837 $pdfRow = new PDFTableRow();
838 $pdfRow->cells[] = new PDFTableCell($description, null, null, true);
839 $pdfTable->rows[] = $pdfRow;
840 $pdfRow = new PDFTableRow();
841 $pdfRow->cells[] = new PDFTableCell(_('Mountpoint'), '28%', null, true);
842 $pdfRow->cells[] = new PDFTableCell(_('Soft block'), '18%', null, true);
843 $pdfRow->cells[] = new PDFTableCell(_('Hard block'), '18%', null, true);
844 $pdfRow->cells[] = new PDFTableCell(_('Soft inode'), '18%', null, true);
845 $pdfRow->cells[] = new PDFTableCell(_('Hard inode'), '18%', null, true);
846 $pdfTable->rows[] = $pdfRow;
847 for ($i = 0; $i < count($this->quota[$server]); $i++) {
848 $pdfRow = new PDFTableRow();
849 $pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][0], '28%');
850 $pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][2], '18%');
851 $pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][3], '18%');
852 $pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][6], '18%');
853 $pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][7], '18%');
854 $pdfTable->rows[] = $pdfRow;
855 }
856 $pdfRow = new PDFTableRow();
857 $pdfRow->cells[] = new PDFTableCell(' ');
858 $pdfTable->rows[] = $pdfRow;
859 }
860 $return = [];
861 $this->addPDFTable($return, 'quotas', $pdfTable);
862 return $return;
863 }
864 else {
865 return [];
866 }
867 }
868
869 /**
870 * {@inheritDoc}
871 */
872 public function get_uploadColumns(array $selectedModules, ConfiguredType $type): array {
873 try {
874 $this->initQuotas();
875 }
876 catch (LAMException $e) {
877 logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
878 return [];
879 }
880 if (!is_array($this->quota)) {
881 return [];
882 }
883 $return = [];
884 if ($this->quota !== []) {
885 // get list of lamdaemon servers
886 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
887 foreach ($lamdaemonServers as $lamdaemonServer) {
888 $server = $lamdaemonServer->getServer();
889 // Get quotas
890 $remote = new Remote();
891 try {
892 $remote->connect($lamdaemonServer);
893 }
894 catch (LAMException $e) {
895 logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
896 continue;
897 }
898 $quotas = $remote->execute(implode(self::$SPLIT_DELIMITER, ["+", "quota", "get", $this->get_scope()]));
899 $remote->disconnect();
900 $dirs = explode(":", $quotas);
901 array_pop($dirs); // remove empty element at the end
902 for ($i = 0; $i < count($dirs); $i++) {
903 if (!str_starts_with($dirs[$i], self::$QUOTA_PREFIX)) {
904 unset($dirs[$i]);
905 $i--;
906 continue;
907 }
908 $dirs[$i] = substr($dirs[$i], strlen(self::$QUOTA_PREFIX));
909 $dirs[$i] = explode(",", $dirs[$i]);
910 $dirs[$i] = $dirs[$i][0];
911 }
912 $dirs = array_values($dirs);
913 for ($i = 0; $i < count($dirs); $i++) {
914 $return[] = [
915 'name' => 'quota_' . $server . ':' . $dirs[$i],
916 'description' => sprintf(_('Quota for %s on %s'), $dirs[$i], $server),
917 'help' => 'upload',
918 'example' => '2000,2500,3000,3500'];
919 }
920 }
921 }
922 return $return;
923 }
924
925 /**
926 * {@inheritDoc}
927 */
928 public function doUploadPostActions(array &$data, array $ids, array $failed, array &$temp, array &$accounts,
929 array $selectedModules, ConfiguredType $type): array {
930 $errors = [];
931 // first call, get list of user names and quota values
932 if (!isset($temp['counter'])) {
933 $temp['counter'] = 0;
934 // create list of quota columns
935 $temp['quotas'] = [];
936 $columns = array_keys($ids);
937 for ($i = 0; $i < count($columns); $i++) {
938 if (str_starts_with($columns[$i], 'quota_')) {
939 $temp['quotas'][] = substr($columns[$i], 6);
940 }
941 }
942 // select user/group name depending on current scope
943 $temp['accounts'] = [];
944 $col = 'invalid';
945 if ($this->get_scope() == 'user') {
946 $col = $ids['posixAccount_userName'];
947 }
948 elseif ($this->get_scope() == 'group') {
949 $col = $ids['posixGroup_cn'];
950 }
951 // create list of account names and their quota values
952 for ($i = 0; $i < count($data); $i++) {
953 if (in_array($i, $failed)) {
954 continue; // ignore failed accounts
955 }
956 $name = $data[$i][$col];
957 for ($m = 0; $m < count($temp['quotas']); $m++) {
958 if ($data[$i][$ids['quota_' . $temp['quotas'][$m]]] != '') {
959 $parts = explode(',', $data[$i][$ids['quota_' . $temp['quotas'][$m]]]);
960 // check syntax
961 if (count($parts) !== 4) {
962 $errMsg = $this->messages['upload'][0];
963 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
964 $errors[] = $errMsg;
965 continue;
966 }
967 if (!get_preg($parts[0], 'quotaNumber')) {
968 $errMsg = $this->messages['softblock'][1];
969 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
970 $errors[] = $errMsg;
971 continue;
972 }
973 if (!get_preg($parts[1], 'quotaNumber')) {
974 $errMsg = $this->messages['hardblock'][1];
975 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
976 $errors[] = $errMsg;
977 continue;
978 }
979 if (!get_preg($parts[2], 'quotaNumber')) {
980 $errMsg = $this->messages['softinode'][1];
981 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
982 $errors[] = $errMsg;
983 continue;
984 }
985 if (!get_preg($parts[3], 'quotaNumber')) {
986 $errMsg = $this->messages['hardinode'][1];
987 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
988 $errors[] = $errMsg;
989 continue;
990 }
991 if ($this->getQuotaNumber($parts[0]) > $this->getQuotaNumber($parts[1])) {
992 $errMsg = $this->messages['block_cmp'][1];
993 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
994 $errors[] = $errMsg;
995 continue;
996 }
997 if ($this->getQuotaNumber($parts[2]) > $this->getQuotaNumber($parts[3])) {
998 $errMsg = $this->messages['inode_cmp'][1];
999 $errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
1000 $errors[] = $errMsg;
1001 continue;
1002 }
1003 $parts[0] = $this->getQuotaNumber($parts[0]);
1004 $parts[1] = $this->getQuotaNumber($parts[1]);
1005 $parts[2] = $this->getQuotaNumber($parts[2]);
1006 $parts[3] = $this->getQuotaNumber($parts[3]);
1007 // save quota settings
1008 $temp['accounts'][$name][$temp['quotas'][$m]] = $parts;
1009 }
1010 }
1011 }
1012 return ['status' => 'inProgress', 'progress' => 5, 'errors' => $errors];
1013 }
1014 // quotas are ready to set
1015 elseif ($temp['counter'] < count($temp['accounts'])) {
1016 $names = array_keys($temp['accounts']);
1017 $name = $names[$temp['counter']];
1018 $mountPoints = array_keys($temp['accounts'][$name]);
1019 // set quota
1020 for ($m = 0; $m < count($mountPoints); $m++) {
1021 $mpParts = explode(":", $mountPoints[$m]);
1022 $server = $mpParts[0];
1023 $dir = $mpParts[1];
1024 $quotaString = implode(self::$SPLIT_DELIMITER, [$name, "quota", "set", $this->get_scope(), $dir . ',' .
1025 implode(',', $temp['accounts'][$name][$mountPoints[$m]]) . "\n"]);
1026 $remote = new Remote();
1027 $remoteServer = $_SESSION['config']->getScriptServerByName($server);
1028 try {
1029 $remote->connect($remoteServer);
1030 }
1031 catch (LAMException $e) {
1032 $errors[] = ['ERROR', $e->getTitle(), $e->getMessage()];
1033 continue;
1034 }
1035 $result = $remote->execute($quotaString);
1036 $remote->disconnect();
1037 if (!empty($result)) {
1038 $parts = explode(",", $result);
1039 if ($parts[0] === 'ERROR') {
1040 $errors[] = ['ERROR', $parts[1], $parts[2]];
1041 }
1042 }
1043 }
1044 // set counters to next account/mount point
1045 $temp['counter']++;
1046 return [
1047 'status' => 'inProgress',
1048 'progress' => 5 + (95 * ($temp['counter'] / count($temp['accounts']))),
1049 'errors' => $errors];
1050 }
1051 return ['status' => 'finished'];
1052 }
1053
1054 /**
1055 * {@inheritDoc}
1056 */
1057 public function save_attributes(): array {
1058 // no LDAP changes
1059 return $this->getAccountContainer()->save_module_attributes([], []);
1060 }
1061
1062 /**
1063 * {@inheritDoc}
1064 */
1065 public function getSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
1066 $return = [];
1067 if ($passwordChangeOnly) {
1068 return $return; // no fields as long no LDAP content can be read
1069 }
1070 if (in_array('quota', $fields) && !empty($attributes['uid'][0])) {
1071 $profile = $this->selfServiceSettings;
1072 $lamdaemonServers = LAMConfig::parseConfiguredScriptServers($profile->scriptServer, $profile->scriptPath,
1073 $profile->scriptUserName, $profile->scriptSSHKey, deobfuscateText($profile->scriptSSHKeyPassword));
1074 $this->initQuotas($attributes['uid'][0], $lamdaemonServers);
1075 if (is_array($this->quota)) {
1076 $serverDescriptions = [];
1077 foreach ($lamdaemonServers as $lamdaemonServer) {
1078 $serverDescriptions[$lamdaemonServer->getServer()] = $lamdaemonServer->getLabel();
1079 }
1080 $quotaRow = new htmlResponsiveRow();
1081 foreach ($this->quota as $server => $quotaDatas) {
1082 $title = $server;
1083 if ($serverDescriptions[$server] != $server) {
1084 $title = $serverDescriptions[$server] . " (" . $server . ")";
1085 }
1086 $quotaRow->add(new htmlSubTitle($title));
1087
1088 $titles = [
1089 _('Mountpoint'), _('Used blocks'), _('Soft block limit'), _('Hard block limit'),
1090 _('Used inodes'), _('Soft inode limit'), _('Hard inode limit')
1091 ];
1092 $data = [];
1093 // loop for every mointpoint with enabled quotas
1094 foreach ($quotaDatas as $quotaData) {
1095 $dataRow = [];
1096 $mountPoint = new htmlOutputText($quotaData[0]);
1097 $mountPoint->setNoWrap(true);
1098 $dataRow[] = $mountPoint;
1099 $dataRow[] = new htmlOutputText($quotaData[1]);
1100 $dataRow[] = new htmlOutputText($quotaData[2]);
1101 $dataRow[] = new htmlOutputText($quotaData[3]);
1102 $dataRow[] = new htmlOutputText($quotaData[5]);
1103 $dataRow[] = new htmlOutputText($quotaData[6]);
1104 $dataRow[] = new htmlOutputText($quotaData[7]);
1105 $data[] = $dataRow;
1106 }
1107 $table = new htmlResponsiveTable($titles, $data);
1108 $table->setCSSClasses(['responsive-table-wrap-th']);
1109 $table->setWidths(['20%', '5%', '10%', '10%', '5%', '5%', '10%', '10%', '5%']);
1110 $quotaRow->add($table);
1111 }
1112 $return['quota'] = $quotaRow;
1113 }
1114 }
1115 return $return;
1116 }
1117
1118 }