Debian Codegraph @

lib/modules/pykotaUser.inc

raw
1 <?php
2
3 use LAM\PDF\PDFTable;
4 use LAM\PDF\PDFTableCell;
5 use LAM\PDF\PDFTableRow;
6 use LAM\TYPES\ConfiguredType;
7 use LAM\TYPES\TypeManager;
8
9 /*
10
11 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
12 Copyright (C) 2013 - 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 * Manages PyKota user accounts.
31 *
32 * @package modules
33 * @author Roland Gruber
34 */
35
36 /**
37 * Manages PyKota user accounts.
38 *
39 * @package modules
40 */
41 class pykotaUser extends baseModule {
42
43 /**
44 * These attributes will be ignored by default if a new account is copied from an existing one.
45 */
46 private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['pykotaUserName', 'pykotaBalance', 'pykotaLifeTimePaid',
47 'pykotaPayments'];
48
49 /** @var string[]|null $uidCache cache for uid attribute */
50 private ?array $uidCache = null;
51 /** @var string[]|null $pykotaUserNameCache cache for pykotaUserName attribute */
52 private ?array $pykotaUserNameCache = null;
53 /** @var array<string, string> $limitOptions list of limit options label => value */
54 private array $limitOptions;
55
56 /**
57 * Returns if this module also manages the structural object class pykotaObject.
58 * This is overridden by a submodule that must provide the structural object class.
59 *
60 * @return bool structural usage
61 */
62 public function isStructural(): bool {
63 return false;
64 }
65
66 /**
67 * Creates a new pykotaUser object.
68 *
69 * @param string $scope account type (user, group, host)
70 */
71 public function __construct($scope) {
72 $this->limitOptions = [
73 _('Quota') => 'quota',
74 _('Balance') => 'balance',
75 _('No quota') => 'noquota',
76 _('Free printing') => 'nochange',
77 _('Deny printing') => 'noprint',
78 ];
79 // call parent constructor
80 parent::__construct($scope);
81 $this->autoAddObjectClasses = $this->isStructural();
82 }
83
84 /**
85 * {@inheritDoc}
86 */
87 public function can_manage(): bool {
88 return $this->get_scope() === 'user';
89 }
90
91 /**
92 * {@inheritDoc}
93 */
94 public function get_metaData(): array {
95 $return = [];
96 // icon
97 $return['icon'] = 'printer.svg';
98 // alias name
99 $return["alias"] = _("PyKota");
100 // this is a base module
101 $return["is_base"] = $this->isStructural();
102 // LDAP filter
103 $return["ldap_filter"] = ['or' => "(objectClass=pykotaAccount)"];
104 // module dependencies
105 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
106 // managed object classes
107 $return['objectClasses'] = ['pykotaAccount', 'pykotaAccountBalance'];
108 // managed attributes
109 $return['attributes'] = ['uid', 'mail', 'description', 'pykotaLimitBy', 'pykotaUserName', 'pykotaBalance', 'pykotaLifeTimePaid',
110 'pykotaOverCharge', 'pykotaPayments'];
111 // help Entries
112 $return['help'] = [
113 'cn' => [
114 "Headline" => _("Common name"), 'attr' => 'cn',
115 "Text" => _("This is the natural name of the user.")
116 ],
117 'uid' => [
118 "Headline" => _("User name"), 'attr' => 'uid',
119 "Text" => _("User name of the user who should be created. Valid characters are: a-z,A-Z,0-9, @.-_.")
120 ],
121 'mail' => [
122 "Headline" => _("Email address"), 'attr' => 'mail',
123 "Text" => _("The user's email address.")
124 ],
125 'description' => [
126 "Headline" => _("Description"), 'attr' => 'description',
127 "Text" => _("User description.")
128 ],
129 'pykotaUserName' => [
130 "Headline" => _("PyKota user name"), 'attr' => 'pykotaUserName',
131 "Text" => _("User name that is used for PyKota.")
132 ],
133 'pykotaLimitBy' => [
134 "Headline" => _("Limit type"), 'attr' => 'pykotaLimitBy',
135 "Text" => _("Specifies the type of limit for printing if any. Please note that in contrast to \"Free printing\" the option \"No quota\" includes accounting.")
136 ],
137 'pykotaBalance' => [
138 "Headline" => _('Balance'), 'attr' => 'pykotaBalance',
139 "Text" => _('Current account balance for the user.')
140 ],
141 'pykotaBalanceComment' => [
142 "Headline" => _('Balance comment'), 'attr' => 'pykotaPayments',
143 "Text" => _('Comment for initial balance.')
144 ],
145 'pykotaLifeTimePaid' => [
146 "Headline" => _('Total paid'), 'attr' => 'pykotaLifeTimePaid',
147 "Text" => _('Total money paid by the user.')
148 ],
149 'pykotaOverCharge' => [
150 "Headline" => _('Overcharge factor'), 'attr' => 'pykotaOverCharge',
151 "Text" => _('Overcharge factor that is applied when computing the cost of a print job. The number of pages is not changed.')
152 ],
153 'pykotaPayments' => [
154 "Headline" => _('Payment and job history'), 'attr' => 'pykotaPayments',
155 "Text" => _('Payment and job history for this user.')
156 ],
157 'pykotaPaymentsAdd' => [
158 "Headline" => _('Payment'), 'attr' => 'pykotaBalance, pykotaPayments',
159 "Text" => _('Adds the amount to the user\'s balance. You can also specify a comment.')
160 ],
161 'jobSuffix' => [
162 "Headline" => _('Job suffix'),
163 "Text" => _('Please enter the LDAP suffix where the PyKota job entries are stored (configuration option "jobbase").')
164 ],
165 'autoAdd' => [
166 "Headline" => _("Automatically add this extension"),
167 "Text" => _("This will enable the extension automatically if this profile is loaded.")
168 ],
169 ];
170 // profile options
171 $profileContainer = new htmlResponsiveRow();
172 if (!$this->isStructural()) {
173 $profileContainer->add(new htmlResponsiveInputCheckbox('pykotaUser_addExt', false, _('Automatically add this extension'), 'autoAdd'));
174 }
175 $pykotaLimitByProfileOption = new htmlResponsiveSelect('pykotaUser_pykotaLimitBy', $this->limitOptions, [], _('Limit type'), 'pykotaLimitBy');
176 $pykotaLimitByProfileOption->setHasDescriptiveElements(true);
177 $pykotaLimitByProfileOption->setSortElements(false);
178 $profileContainer->add($pykotaLimitByProfileOption);
179 $profileContainer->add(new htmlResponsiveInputField(_('Balance'), 'pykotaUser_pykotaBalance', '', 'pykotaBalance'));
180 $profileContainer->add(new htmlResponsiveInputField(_('Overcharge factor'), 'pykotaUser_pykotaOverCharge', '', 'pykotaOverCharge'));
181 $return['profile_options'] = $profileContainer;
182 $return['profile_mappings']['pykotaUser_pykotaLimitBy'] = 'pykotaLimitBy';
183 $return['profile_mappings']['pykotaUser_pykotaOverCharge'] = 'pykotaOverCharge';
184 $return['profile_checks']['pykotaUser_pykotaBalance'] = [
185 'type' => 'ext_preg',
186 'regex' => 'float',
187 'error_message' => $this->messages['pykotaBalance'][0]];
188 $return['profile_checks']['pykotaUser_pykotaOverCharge'] = [
189 'type' => 'ext_preg',
190 'regex' => 'float',
191 'error_message' => $this->messages['pykotaOverCharge'][0]];
192 // upload fields
193 $return['upload_columns'] = [
194 [
195 'name' => 'pykotaUser_pykotaUserName',
196 'description' => _('PyKota user name'),
197 'help' => 'pykotaUserName',
198 'example' => _('smiller'),
199 'unique' => true,
200 ]
201 ];
202 if ($this->isStructural()) {
203 $return['upload_columns'][] = [
204 'name' => 'pykotaUser_cn',
205 'description' => _('Common name'),
206 'help' => 'cn',
207 'example' => _('Steve Miller'),
208 'required' => true,
209 ];
210 }
211 $return['upload_columns'][] = [
212 'name' => 'pykotaUser_pykotaLimitBy',
213 'description' => _('Limit type'),
214 'help' => 'pykotaLimitBy',
215 'example' => _('Quota'),
216 'default' => _('Quota'),
217 'values' => implode(', ', array_keys($this->limitOptions))
218 ];
219 $return['upload_columns'][] = [
220 'name' => 'pykotaUser_pykotaBalance',
221 'description' => _('Balance'),
222 'help' => 'pykotaBalance',
223 'example' => '10.0',
224 ];
225 $return['upload_columns'][] = [
226 'name' => 'pykotaUser_pykotaBalanceComment',
227 'description' => _('Balance comment'),
228 'help' => 'pykotaBalanceComment',
229 'example' => _('Initial payment'),
230 ];
231 $return['upload_columns'][] = [
232 'name' => 'pykotaUser_pykotaOverCharge',
233 'description' => _('Overcharge factor'),
234 'help' => 'pykotaOverCharge',
235 'example' => '1.0',
236 'default' => '1.0'
237 ];
238 // available PDF fields
239 $return['PDF_fields'] = [
240 'pykotaUserName' => _('PyKota user name'),
241 'pykotaLimitBy' => _('Limit type'),
242 'pykotaBalance' => _('Balance'),
243 'pykotaOverCharge' => _('Overcharge factor'),
244 'pykotaLifeTimePaid' => _('Total paid'),
245 'pykotaPayments' => _('Payment history'),
246 ];
247 if ($this->isStructural()) {
248 $return['PDF_fields']['cn'] = _('Common name');
249 }
250 // self-service
251 $return['selfServiceFieldSettings'] = [
252 'pykotaBalance' => _('Balance (read-only)'),
253 'pykotaLifeTimePaid' => _('Total paid (read-only)'),
254 'pykotaPayments' => _('Payment history'),
255 'pykotaJobHistory' => _('Job history'),
256 ];
257 // self-service settings
258 if (static::class === 'pykotaUser') {
259 $selfServiceContainer = new htmlResponsiveRow();
260 $selfServiceContainer->add(new htmlResponsiveInputField(_('Job suffix'), 'pykotaUser_jobSuffix', null, ['jobSuffix', static::class]));
261 $return['selfServiceSettings'] = $selfServiceContainer;
262 }
263 // configuration checks
264 $return['config_checks']['all']['pykotaUser_jobSuffix'] = [
265 'type' => 'ext_preg',
266 'regex' => 'dn',
267 'required' => false,
268 'required_message' => $this->messages['jobSuffix'][0],
269 'error_message' => $this->messages['jobSuffix'][0]];
270 return $return;
271 }
272
273 /**
274 * {@inheritDoc}
275 */
276 protected function load_Messages(): void {
277 $this->messages['uid'][0] = ['ERROR', _('User name'), _('User name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
278 $this->messages['uid'][1] = ['ERROR', _('Account %s:') . ' pykotaUser_uid', _('User name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
279 $this->messages['uid'][2] = ['ERROR', _('User name'), _('User name already exists!')];
280 $this->messages['uid'][3] = ['ERROR', _('Account %s:') . ' pykotaUser_uid', _('User name already exists!')];
281 $this->messages['pykotaUserName'][0] = ['ERROR', _('PyKota user name'), _('User name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
282 $this->messages['pykotaUserName'][1] = ['ERROR', _('Account %s:') . ' pykotaUser_pykotaUserName', _('User name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
283 $this->messages['pykotaUserName'][2] = ['ERROR', _('PyKota user name'), _('User name already exists!')];
284 $this->messages['pykotaUserName'][3] = ['ERROR', _('Account %s:') . ' pykotaUser_pykotaUserName', _('User name already exists!')];
285 $this->messages['mail'][0] = ['ERROR', _('Email address'), _('Please enter a valid email address!')];
286 $this->messages['mail'][1] = ['ERROR', _('Account %s:') . ' pykotaUser_mail', _('Please enter a valid email address!')];
287 $this->messages['pykotaLimitBy'][0] = ['ERROR', _('Account %s:') . ' pykotaUser_pykotaLimitBy', _('Please enter a valid limit type.')];
288 $this->messages['pykotaBalance'][0] = ['ERROR', _('Balance'), _('Please enter a valid number (e.g. "1.5").')];
289 $this->messages['pykotaBalance'][1] = ['ERROR', _('Account %s:') . ' pykotaUser_pykotaBalance', _('Please enter a valid number (e.g. "1.5").')];
290 $this->messages['pykotaOverCharge'][0] = ['ERROR', _('Overcharge factor'), _('Please enter a valid number (e.g. "1.5").')];
291 $this->messages['pykotaOverCharge'][1] = ['ERROR', _('Account %s:') . ' pykotaUser_pykotaOverCharge', _('Please enter a valid number (e.g. "1.5").')];
292 $this->messages['pykotaPayments'][0] = ['ERROR', _('Payment'), _('Please enter a valid number (e.g. "1.5").')];
293 $this->messages['jobSuffix'][0] = ['ERROR', _('Job suffix'), _('Please enter a valid job suffix.')];
294 }
295
296 /**
297 * {@inheritDoc}
298 */
299 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
300 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY));
301 }
302
303 /**
304 * {@inheritDoc}
305 */
306 public function display_html_attributes(): htmlElement|array {
307 $container = new htmlResponsiveRow();
308 $modules = $this->getAccountContainer()->get_type()->getModules();
309 if ($this->isStructural() || (isset($this->attributes['objectClass']) && in_array('pykotaAccount', $this->attributes['objectClass']))) {
310 // uid
311 if ($this->manageUid($modules)) {
312 $this->addSimpleInputTextField($container, 'uid', _('User name'), true);
313 }
314 else {
315 // require uid
316 $uid = $this->getCurrentUserName();
317 if (empty($uid)) {
318 $page = '';
319 if ($this->getAccountContainer()->getAccountModule('posixAccount') != null) {
320 $page = $this->getAccountContainer()->getAccountModule('posixAccount')->get_alias();
321 }
322 elseif ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
323 $page = $this->getAccountContainer()->getAccountModule('inetOrgPerson')->get_alias();
324 }
325 $msg = new htmlStatusMessage('INFO', sprintf(_("Please enter an user name on this page: %s"), $page));
326 $container->add($msg);
327 }
328 }
329 // pykotaUserName
330 $this->addSimpleInputTextField($container, 'pykotaUserName', _('Pykota user name'));
331 // balance
332 $pykotaBalance = '';
333 if (isset($this->attributes['pykotaBalance'][0])) {
334 $pykotaBalance = $this->attributes['pykotaBalance'][0];
335 }
336 $container->addLabel(new htmlOutputText(_('Balance')));
337 $balanceGroup = new htmlGroup();
338 $balanceGroup->addElement(new htmlOutputText($pykotaBalance));
339 $balanceGroup->addElement(new htmlSpacer('0.5rem', null));
340 $balanceGroup->addElement(new htmlHelpLink('pykotaBalance'));
341 $container->addField($balanceGroup);
342 $container->addLabel(new htmlOutputText('&nbsp;', false));
343 $historyGroup = new htmlGroup();
344 $historyGroup->addElement(new htmlAccountPageButton(static::class, 'payments', 'open', _('Payment history')));
345 if (!$this->getAccountContainer()->isNewAccount && !empty($this->moduleSettings['pykotaUser_jobSuffix'][0])) {
346 $historyGroup->addElement(new htmlSpacer('5px', null));
347 $historyGroup->addElement(new htmlAccountPageButton(static::class, 'jobs', 'open', _('Job history')));
348 }
349 $historyGroup->addElement(new htmlSpacer('5px', null));
350 $historyGroup->addElement(new htmlHelpLink('pykotaPayments'));
351 $container->addField($historyGroup);
352 // limit by
353 $limitOption = 'quota';
354 if (!empty($this->attributes['pykotaLimitBy'][0])) {
355 $limitOption = $this->attributes['pykotaLimitBy'][0];
356 }
357 $limitSelect = new htmlResponsiveSelect('pykotaLimitBy', $this->limitOptions, [$limitOption], _('Limit type'), 'pykotaLimitBy');
358 $limitSelect->setHasDescriptiveElements(true);
359 $limitSelect->setSortElements(false);
360 $container->add($limitSelect);
361 // overcharge factor
362 $this->addSimpleInputTextField($container, 'pykotaOverCharge', _('Overcharge factor'));
363 // cn
364 if ($this->isStructural()) {
365 $this->addSimpleInputTextField($container, 'cn', _('Common name'), true);
366 }
367 // mail
368 if ($this->manageMail($modules)) {
369 $this->addSimpleInputTextField($container, 'mail', _('Email address'));
370 }
371 // description
372 if ($this->manageDescription($modules)) {
373 $this->addMultiValueInputTextField($container, 'description', _('Description'), false, null, true);
374 }
375 // new payment
376 $container->add(new htmlSubTitle(_('Payment')));
377 $newPaymentAmount = new htmlResponsiveInputField(_('Amount'), 'pykotaBalanceAdd', '', '5em');
378 $container->add($newPaymentAmount);
379 $newPaymentComment = new htmlResponsiveInputField(_('Comment'), 'pykotaBalanceComment', '', '20em');
380 $container->add($newPaymentComment);
381 $newPaymentBtn = new htmlButton('addPayment', _('Add'));
382 $newPaymentGroup = new htmlGroup();
383 $newPaymentGroup->addElement($newPaymentBtn);
384 $newPaymentGroup->addElement(new htmlSpacer('0.5rem', null));
385 $newPaymentGroup->addElement(new htmlHelpLink('pykotaPaymentsAdd'));
386 $container->add($newPaymentGroup, 12, 12, 12, 'text-center');
387 // remove button
388 if (!$this->isStructural()) {
389 $container->addVerticalSpacer('2rem');
390 $remButton = new htmlButton('remObjectClass', _('Remove PyKota extension'));
391 $remButton->setCSSClasses(['lam-danger']);
392 $container->add($remButton, 12, 12, 12, 'text-center');
393 }
394 }
395 else {
396 // add button
397 $container->add(new htmlButton('addObjectClass', _('Add PyKota extension')));
398 }
399 return $container;
400 }
401
402 /**
403 * {@inheritDoc}
404 */
405 public function process_attributes(): array {
406 $errors = [];
407 if (isset($_POST['addObjectClass'])) {
408 if (!isset($this->attributes['objectClass'])) {
409 $this->attributes['objectClass'] = [];
410 }
411 if (!in_array('pykotaAccount', $this->attributes['objectClass'])) {
412 $this->attributes['objectClass'][] = 'pykotaAccount';
413 }
414 if (!in_array('pykotaAccountBalance', $this->attributes['objectClass'])) {
415 $this->attributes['objectClass'][] = 'pykotaAccountBalance';
416 }
417 if (!isset($this->attributes['pykotaUserName'][0])) {
418 $this->attributes['pykotaUserName'][0] = $this->getCurrentUserName();
419 }
420 return $errors;
421 }
422 $modules = $this->getAccountContainer()->get_type()->getModules();
423 if (isset($_POST['remObjectClass'])) {
424 $this->attributes['objectClass'] = array_delete(['pykotaAccount', 'pykotaAccountBalance'], $this->attributes['objectClass']);
425 $attrs = ['pykotaLimitBy', 'pykotaUserName'];
426 if ($this->manageDescription($modules)) {
427 $attrs[] = 'description';
428 }
429 if ($this->manageMail($modules)) {
430 $attrs[] = 'mail';
431 }
432 if ($this->manageUid($modules)) {
433 $attrs[] = 'uid';
434 }
435 foreach ($attrs as $name) {
436 if (isset($this->attributes[$name])) {
437 unset($this->attributes[$name]);
438 }
439 }
440 return $errors;
441 }
442 // skip processing if object class is not set
443 if (!isset($this->attributes['objectClass']) || !in_array('pykotaAccount', $this->attributes['objectClass'])) {
444 return $errors;
445 }
446 // uid
447 if ($this->manageUid($modules)) {
448 if (isset($_POST['uid']) && ($_POST['uid'] != '')) {
449 if (!get_preg($_POST['uid'], 'username')) {
450 $errors[] = $this->messages['uid'][0];
451 }
452 else {
453 $this->attributes['uid'][0] = $_POST['uid'];
454 if ((!isset($this->orig['uid'][0]) || ($this->attributes['uid'][0] != $this->orig['uid'][0]))
455 && $this->uidExists($_POST['uid'])) {
456 $errors[] = $this->messages['uid'][2];
457 }
458 }
459 }
460 elseif (isset($this->attributes['uid'][0])) {
461 unset($this->attributes['uid'][0]);
462 }
463 }
464 // PyKota user name
465 if (!empty($_POST['pykotaUserName'])) {
466 if (!get_preg($_POST['pykotaUserName'], 'username')) {
467 $errors[] = $this->messages['pykotaUserName'][0];
468 }
469 else {
470 $this->attributes['pykotaUserName'][0] = $_POST['pykotaUserName'];
471 if ((!isset($this->orig['pykotaUserName'][0]) || ($this->attributes['pykotaUserName'][0] != $this->orig['pykotaUserName'][0]))
472 && $this->pykotaUserNameExists($_POST['pykotaUserName'])) {
473 $errors[] = $this->messages['pykotaUserName'][2];
474 }
475 }
476 }
477 else {
478 $this->attributes['pykotaUserName'][0] = $this->getCurrentUserName();
479 }
480 // limit by
481 $this->attributes['pykotaLimitBy'][0] = $_POST['pykotaLimitBy'];
482 // cn
483 if ($this->isStructural()) {
484 $this->attributes['cn'][0] = $_POST['cn'];
485 if (empty($this->attributes['cn'][0])) {
486 $this->attributes['cn'][0] = $_POST['uid'];
487 }
488 }
489 // mail
490 if ($this->manageMail($modules)) {
491 $this->attributes['mail'][0] = $_POST['mail'];
492 if (!empty($_POST['mail']) && !get_preg($_POST['mail'], 'email')) {
493 $errors[] = $this->messages['mail'][0];
494 }
495 }
496 // description
497 if ($this->manageDescription($modules)) {
498 $this->processMultiValueInputTextField('description', $errors);
499 }
500 // overcharge factor
501 $this->attributes['pykotaOverCharge'][0] = empty($_POST['pykotaOverCharge']) ? '1.0' : $_POST['pykotaOverCharge'];
502 // add payment
503 if (isset($_POST['addPayment'])) {
504 $amount = $_POST['pykotaBalanceAdd'];
505 if (!empty($amount) && (str_contains($amount, ','))) {
506 $amount = str_replace(',', '.', $amount);
507 }
508 if (!empty($amount) && (!str_contains($amount, '.'))) {
509 $amount .= '.0';
510 }
511 $comment = $_POST['pykotaBalanceComment'];
512 if (!empty($comment)) {
513 $comment = base64_encode($comment);
514 }
515 if (empty($amount) || (floatval($amount) === 0.0)) {
516 $errors[] = $this->messages['pykotaPayments'][0];
517 }
518 else {
519 $this->attributes['pykotaPayments'][] = getFormattedTime('Y-m-d H:i:s,00') . ' # ' . $amount . ' # ' . $comment;
520 // new balance
521 $newBalance = 0.0;
522 if (!empty($this->attributes['pykotaBalance'][0])) {
523 $newBalance = floatval($this->attributes['pykotaBalance'][0]);
524 }
525 $newBalance += $amount;
526 $this->attributes['pykotaBalance'][0] = strval($newBalance);
527 // total paid
528 $total = 0.0;
529 if (!empty($this->attributes['pykotaLifeTimePaid'][0])) {
530 $total = floatval($this->attributes['pykotaLifeTimePaid'][0]);
531 }
532 $total += $amount;
533 $this->attributes['pykotaLifeTimePaid'][0] = strval($total);
534 }
535 }
536 return $errors;
537 }
538
539 /**
540 * Returns the HTML meta data for the payments page.
541 *
542 * @return htmlElement HTML meta data
543 */
544 public function display_html_payments(): htmlElement {
545 $container = new htmlResponsiveRow();
546 // total paid
547 $total = '';
548 if (!empty($this->attributes['pykotaLifeTimePaid'][0])) {
549 $total = $this->attributes['pykotaLifeTimePaid'][0];
550 }
551 $container->addLabel(new htmlOutputText(_('Total paid')));
552 $totalPaidGroup = new htmlGroup();
553 $totalPaidGroup->addElement(new htmlOutputText($total));
554 $totalPaidGroup->addElement(new htmlSpacer('0.5rem', null));
555 $totalPaidGroup->addElement(new htmlHelpLink('pykotaLifeTimePaid'));
556 $container->addField($totalPaidGroup);
557 // payment/job history
558 if (!empty($this->attributes['pykotaPayments'][0])) {
559 $container->add(new htmlSubTitle(_('Payment history')));
560 $labels = [_('Date'), _('Amount'), _('Comment')];
561 $data = [];
562 rsort($this->attributes['pykotaPayments']);
563 foreach ($this->attributes['pykotaPayments'] as $payment) {
564 $parts = explode(' # ', $payment);
565 $comment = empty($parts[2]) ? '' : base64_decode($parts[2]);
566 $commentField = new htmlOutputText($comment);
567 $amountFied = new htmlOutputText($parts[1]);
568 $data[] = [
569 new htmlOutputText($parts[0]),
570 $amountFied,
571 $commentField
572 ];
573 }
574 $historyTable = new htmlResponsiveTable($labels, $data);
575 $historyTable->setWidths(['20%', '15%', '65%']);
576 $container->add($historyTable);
577 }
578 // back button
579 $container->addVerticalSpacer('2rem');
580 $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back'));
581 $container->add($backButton);
582 return $container;
583 }
584
585 /**
586 * Processes user input of the payments module page.
587 * It checks if all input values are correct and updates the associated LDAP attributes.
588 *
589 * @return string[][] list of info/error messages
590 */
591 public function process_payments(): array {
592 return [];
593 }
594
595 /**
596 * Returns the HTML meta data for the jobs page.
597 *
598 * @return htmlElement HTML meta data
599 */
600 public function display_html_jobs(): htmlElement {
601 $container = new htmlResponsiveRow();
602 // jobs
603 $jobs = $this->getJobs($this->getCurrentUserName(), $this->moduleSettings['pykotaUser_jobSuffix'][0]);
604 $titles = [
605 _('Date'), _('Printer'), _('Price'), _('Size'), _('Title')
606 ];
607 $data = [];
608 foreach ($jobs as $job) {
609 $data[] = [
610 new htmlOutputText(formatLDAPTimestamp($job['createtimestamp'][0])),
611 new htmlOutputText($job['pykotaprintername'][0]),
612 new htmlOutputText($job['pykotajobprice'][0]),
613 new htmlOutputText($job['pykotajobsize'][0]),
614 new htmlOutputText($job['pykotatitle'][0])
615 ];
616 }
617 $table = new htmlResponsiveTable($titles, $data);
618 $table->setWidths(['20%', '20%', '10%', '10%', '40%']);
619 $container->add($table);
620 // back button
621 $container->addVerticalSpacer('2rem');
622 $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back'));
623 $container->add($backButton);
624 return $container;
625 }
626
627 /**
628 * Processes user input of the jobs module page.
629 * It checks if all input values are correct and updates the associated LDAP attributes.
630 *
631 * @return string[][] list of info/error messages
632 */
633 public function process_jobs(): array {
634 return [];
635 }
636
637 /**
638 * {@inheritDoc}
639 */
640 public function save_attributes(): array {
641 if (!in_array('pykotaAccount', $this->attributes['objectClass']) && !in_array('pykotaAccount', $this->orig['objectClass'])) {
642 // skip saving if the extension was not added/modified
643 return [];
644 }
645 return parent::save_attributes();
646 }
647
648 /**
649 * {@inheritDoc}
650 */
651 public function module_complete(): bool {
652 if (in_array('pykotaAccount', $this->attributes['objectClass'])) {
653 // require uid
654 $uid = $this->getCurrentUserName();
655 return !empty($uid);
656 }
657 return true;
658 }
659
660 /**
661 * {@inheritDoc}
662 */
663 public function load_profile(array $profile): void {
664 // profile mappings in meta data
665 parent::load_profile($profile);
666 // add extension
667 if (isset($profile['pykotaUser_addExt'][0]) && ($profile['pykotaUser_addExt'][0] == "true")) {
668 if (!in_array('pykotaAccount', $this->attributes['objectClass'])) {
669 $this->attributes['objectClass'][] = 'pykotaAccount';
670 }
671 if (!in_array('pykotaAccountBalance', $this->attributes['objectClass'])) {
672 $this->attributes['objectClass'][] = 'pykotaAccountBalance';
673 }
674 }
675 if (isset($profile['pykotaUser_pykotaBalance'][0]) && ($profile['pykotaUser_pykotaBalance'][0] !== '') && empty($this->attributes['pykotaBalance'][0])) {
676 $amount = $profile['pykotaUser_pykotaBalance'][0];
677 if (!str_contains($amount, '.')) {
678 $amount .= '.0';
679 }
680 $this->attributes['pykotaBalance'][0] = $amount;
681 $this->attributes['pykotaLifeTimePaid'][0] = $amount;
682 $this->attributes['pykotaPayments'][] = getFormattedTime('Y-m-d H:i:s,00') . ' # ' . $amount . ' # ';
683 }
684 }
685
686 /**
687 * {@inheritDoc}
688 */
689 public function get_uploadColumns(array $selectedModules, ConfiguredType $type): array {
690 $return = parent::get_uploadColumns($selectedModules, $type);
691 if ($this->manageUid($selectedModules)) {
692 $return[] = [
693 'name' => 'pykotaUser_uid',
694 'description' => _('User name'),
695 'help' => 'uid',
696 'example' => _('smiller'),
697 'required' => true,
698 'unique' => true,
699 ];
700 }
701 if ($this->manageMail($selectedModules)) {
702 $return[] = [
703 'name' => 'pykotaUser_mail',
704 'description' => _('Email address'),
705 'help' => 'mail',
706 'example' => _('[email protected]'),
707 ];
708 }
709 if ($this->manageDescription($selectedModules)) {
710 $return[] = [
711 'name' => 'pykotaUser_description',
712 'description' => _('Description'),
713 'help' => 'description',
714 'example' => _('Temp, contract till December'),
715 ];
716 }
717 return $return;
718 }
719
720 /**
721 * {@inheritDoc}
722 */
723 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
724 $messages = [];
725 for ($i = 0; $i < count($rawAccounts); $i++) {
726 // add object classes
727 if (!in_array('pykotaAccount', $partialAccounts[$i]['objectClass'])) {
728 $partialAccounts[$i]['objectClass'][] = 'pykotaAccount';
729 }
730 if (!in_array('pykotaAccountBalance', $partialAccounts[$i]['objectClass'])) {
731 $partialAccounts[$i]['objectClass'][] = 'pykotaAccountBalance';
732 }
733 if ($this->isStructural() && !in_array('pykotaObject', $partialAccounts[$i]['objectClass'])) {
734 $partialAccounts[$i]['objectClass'][] = 'pykotaObject';
735 }
736 // cn
737 if ($this->isStructural()) {
738 $partialAccounts[$i]['cn'] = $rawAccounts[$i][$ids['pykotaUser_cn']];
739 }
740 // uid
741 if ($this->manageUid($selectedModules) && !empty($rawAccounts[$i][$ids['pykotaUser_uid']])) {
742 if (!get_preg($rawAccounts[$i][$ids['pykotaUser_uid']], 'username')) {
743 $errMsg = $this->messages['uid'][1];
744 $errMsg[] = [$i];
745 $messages[] = $errMsg;
746 }
747 elseif ($this->uidExists($rawAccounts[$i][$ids['pykotaUser_uid']])) {
748 $errMsg = $this->messages['uid'][3];
749 $errMsg[] = [$i];
750 $messages[] = $errMsg;
751 }
752 else {
753 $partialAccounts[$i]['uid'] = $rawAccounts[$i][$ids['pykotaUser_uid']];
754 }
755 }
756 // mail
757 if ($this->manageUid($selectedModules) && !empty($rawAccounts[$i][$ids['pykotaUser_mail']])) {
758 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'pykotaUser_mail', 'mail',
759 'email', $this->messages['mail'][1], $messages);
760 }
761 // description
762 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'pykotaUser_description', 'description');
763 // PyKota user name
764 if (!empty($rawAccounts[$i][$ids['pykotaUser_pykotaUserName']])) {
765 if (!get_preg($rawAccounts[$i][$ids['pykotaUser_pykotaUserName']], 'username')) {
766 $errMsg = $this->messages['pykotaUserName'][1];
767 $errMsg[] = [$i];
768 $messages[] = $errMsg;
769 }
770 elseif ($this->pykotaUserNameExists($rawAccounts[$i][$ids['pykotaUser_pykotaUserName']])) {
771 $errMsg = $this->messages['pykotaUserName'][3];
772 $errMsg[] = [$i];
773 $messages[] = $errMsg;
774 }
775 else {
776 $partialAccounts[$i]['pykotaUserName'] = $rawAccounts[$i][$ids['pykotaUser_pykotaUserName']];
777 }
778 }
779 // limit by
780 if (!empty($rawAccounts[$i][$ids['pykotaUser_pykotaLimitBy']])) {
781 if (isset($this->limitOptions[$rawAccounts[$i][$ids['pykotaUser_pykotaLimitBy']]])) {
782 $partialAccounts[$i]['pykotaLimitBy'] = $this->limitOptions[$rawAccounts[$i][$ids['pykotaUser_pykotaLimitBy']]];
783 }
784 else {
785 $errMsg = $this->messages['pykotaLimitBy'][0];
786 $errMsg[] = [$i];
787 $messages[] = $errMsg;
788 }
789 }
790 else {
791 $partialAccounts[$i]['pykotaLimitBy'] = 'quota';
792 }
793 // overcharge factor
794 if (!empty($rawAccounts[$i][$ids['pykotaUser_pykotaOverCharge']])) {
795 $pykotaOverCharge = $rawAccounts[$i][$ids['pykotaUser_pykotaOverCharge']];
796 if (!str_contains($pykotaOverCharge, '.')) {
797 $pykotaOverCharge .= '.0';
798 }
799 if (!get_preg($pykotaOverCharge, 'float')) {
800 $errMsg = $this->messages['pykotaOverCharge'][1];
801 $errMsg[] = [$i];
802 $messages[] = $errMsg;
803 }
804 else {
805 $partialAccounts[$i]['pykotaOverCharge'] = $pykotaOverCharge;
806 }
807 }
808 else {
809 $partialAccounts[$i]['pykotaOverCharge'] = '1.0';
810 }
811 // balance
812 if (!empty($rawAccounts[$i][$ids['pykotaUser_pykotaBalance']])) {
813 $balance = $rawAccounts[$i][$ids['pykotaUser_pykotaBalance']];
814 if (!str_contains($balance, '.')) {
815 $balance .= '.0';
816 }
817 if (!get_preg($balance, 'float')) {
818 $errMsg = $this->messages['pykotaBalance'][1];
819 $errMsg[] = [$i];
820 $messages[] = $errMsg;
821 }
822 else {
823 $partialAccounts[$i]['pykotaBalance'] = $balance;
824 $partialAccounts[$i]['pykotaLifeTimePaid'] = $balance;
825 $comment = '';
826 if (!empty($rawAccounts[$i][$ids['pykotaUser_pykotaBalanceComment']])) {
827 $comment = base64_encode($rawAccounts[$i][$ids['pykotaUser_pykotaBalanceComment']]);
828 }
829 $partialAccounts[$i]['pykotaPayments'][0] = getFormattedTime('Y-m-d H:i:s,00') . ' # ' . $balance . ' # ' . $comment;
830 }
831 }
832 }
833 return $messages;
834 }
835
836 /**
837 * {@inheritDoc}
838 */
839 public function get_pdfFields(string $typeId): array {
840 $fields = parent::get_pdfFields($typeId);
841 $typeManager = new TypeManager();
842 $modules = $typeManager->getConfiguredType($typeId)->getModules();
843 if ($this->manageUid($modules)) {
844 $fields['uid'] = _('User name');
845 }
846 if ($this->manageMail($modules)) {
847 $fields['mail'] = _('Email address');
848 }
849 if ($this->manageDescription($modules)) {
850 $fields['description'] = _('Description');
851 }
852 return $fields;
853 }
854
855 /**
856 * {@inheritDoc}
857 */
858 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
859 $return = [];
860 $this->addSimplePDFField($return, 'cn', _('Common name'));
861 $this->addSimplePDFField($return, 'uid', _('User name'));
862 $this->addSimplePDFField($return, 'mail', _('Email address'));
863 $this->addSimplePDFField($return, 'pykotaUserName', _('PyKota user name'));
864 $this->addSimplePDFField($return, 'description', _('Description'));
865 $limitByOptions = array_flip($this->limitOptions);
866 $limitByValue = '';
867 if (!empty($this->attributes['pykotaLimitBy'][0]) && isset($limitByOptions[$this->attributes['pykotaLimitBy'][0]])) {
868 $limitByValue = $limitByOptions[$this->attributes['pykotaLimitBy'][0]];
869 }
870 $this->addPDFKeyValue($return, 'pykotaLimitBy', _('Limit type'), $limitByValue);
871 $this->addSimplePDFField($return, 'pykotaOverCharge', _('Overcharge factor'));
872 $this->addSimplePDFField($return, 'pykotaBalance', _('Balance'));
873 $this->addSimplePDFField($return, 'pykotaLifeTimePaid', _('Total paid'));
874 // payment history
875 if (!empty($this->attributes['pykotaPayments'][0])) {
876 $pdfTable = new PDFTable();
877 $pdfRow = new PDFTableRow();
878 $pdfRow->cells[] = new PDFTableCell(_('Date'), '20%', null, true);
879 $pdfRow->cells[] = new PDFTableCell(_('Amount'), '10%', null, true);
880 $pdfRow->cells[] = new PDFTableCell(_('Comment'), '70%', null, true);
881 $pdfTable->rows[] = $pdfRow;
882 for ($i = 0; $i < count($this->attributes['pykotaPayments']); $i++) {
883 $parts = explode(' # ', $this->attributes['pykotaPayments'][$i]);
884 $comment = ' ';
885 if (!empty($parts[2])) {
886 $comment = base64_decode($parts[2]);
887 }
888 $pdfRow = new PDFTableRow();
889 $pdfRow->cells[] = new PDFTableCell($parts[0], '20%');
890 $pdfRow->cells[] = new PDFTableCell($parts[1], '10%', PDFTableCell::ALIGN_RIGHT);
891 $pdfRow->cells[] = new PDFTableCell($comment, '70%');
892 $pdfTable->rows[] = $pdfRow;
893 }
894 $this->addPDFTable($return, 'pykotaPayments', $pdfTable);
895 }
896 return $return;
897 }
898
899 /**
900 * {@inheritDoc}
901 */
902 public function getSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
903 if ($passwordChangeOnly) {
904 return []; // no Kolab fields as long no LDAP content can be read
905 }
906 if (!in_array('pykotaAccount', $attributes['objectClass'])) {
907 return [];
908 }
909 $return = [];
910 if (in_array('pykotaBalance', $fields)) {
911 $pykotaBalance = '';
912 if (isset($attributes['pykotaBalance'][0])) {
913 $pykotaBalance = $attributes['pykotaBalance'][0];
914 }
915 $row = new htmlResponsiveRow();
916 $row->addLabel(new htmlOutputText($this->getSelfServiceLabel('pykotaBalance', _('Balance'))));
917 $row->addField(new htmlOutputText($pykotaBalance));
918 $return['pykotaBalance'] = $row;
919 }
920 if (in_array('pykotaLifeTimePaid', $fields)) {
921 $pykotaLifeTimePaid = '';
922 if (isset($attributes['pykotaLifeTimePaid'][0])) {
923 $pykotaLifeTimePaid = $attributes['pykotaLifeTimePaid'][0];
924 }
925 $row = new htmlResponsiveRow();
926 $row->addLabel(new htmlOutputText($this->getSelfServiceLabel('pykotaLifeTimePaid', _('Total paid'))));
927 $row->addField(new htmlOutputText($pykotaLifeTimePaid));
928 $return['pykotaLifeTimePaid'] = $row;
929 }
930 // payment history
931 if (in_array('pykotaPayments', $fields)) {
932 $pykotaPayments = new htmlResponsiveRow();
933 if (!empty($attributes['pykotaPayments'][0])) {
934 $pykotaPayments->add(new htmlOutputText(_('Date')), 3, 3, 3, 'bold');
935 $pykotaPayments->add(new htmlOutputText(_('Amount')), 3, 3, 3, 'bold');
936 $pykotaPayments->add(new htmlOutputText(_('Comment')), 6, 6, 6, 'bold');
937 rsort($attributes['pykotaPayments']);
938 foreach ($attributes['pykotaPayments'] as $payment) {
939 $parts = explode(' # ', $payment);
940 $pykotaPayments->add(new htmlOutputText($parts[0]), 3);
941 $amount = new htmlOutputText($parts[1]);
942 $amount->alignment = htmlElement::ALIGN_RIGHT;
943 $pykotaPayments->add($amount, 3);
944 $pykotaPayments->add(new htmlOutputText(base64_decode($parts[2])), 6);
945 }
946 }
947 $row = new htmlResponsiveRow();
948 $row->add(new htmlSpacer(null, '10px'));
949 $row = new htmlResponsiveRow();
950 $row->add(new htmlOutputText($this->getSelfServiceLabel('pykotaPayments', _('Payment history'))), 12, 12, 12, 'bold text-left');
951 $row->add($pykotaPayments);
952 $return['pykotaPayments'] = $row;
953 }
954 // job history
955 if (in_array('pykotaJobHistory', $fields) && !empty($this->selfServiceSettings->moduleSettings['pykotaUser_jobSuffix'][0]) && !empty($attributes['pykotaUserName'][0])) {
956 $jobs = $this->getJobs($attributes['pykotaUserName'][0], $this->selfServiceSettings->moduleSettings['pykotaUser_jobSuffix'][0]);
957 $pykotaJobs = new htmlResponsiveRow();
958 $pykotaJobs->add(new htmlOutputText(_('Date')), 3, 3, 3, 'bold');
959 $pykotaJobs->add(new htmlOutputText(_('Printer')), 3, 3, 3, 'bold');
960 $pykotaJobs->add(new htmlOutputText(_('Price')), 2, 2, 2, 'bold');
961 $pykotaJobs->add(new htmlOutputText(_('Size')), 1, 1, 1, 'bold');
962 $title = new htmlOutputText(_('Title'));
963 $title->alignment = htmlElement::ALIGN_LEFT;
964 $pykotaJobs->add($title, 3, 3, 3, 'bold');
965 foreach ($jobs as $job) {
966 $pykotaJobs->add(new htmlOutputText(formatLDAPTimestamp($job['createtimestamp'][0])), 3);
967 $pykotaJobs->add(new htmlOutputText($job['pykotaprintername'][0]), 3);
968 $price = new htmlOutputText($job['pykotajobprice'][0]);
969 $price->alignment = htmlElement::ALIGN_RIGHT;
970 $pykotaJobs->add($price, 2);
971 $size = new htmlOutputText($job['pykotajobsize'][0]);
972 $size->alignment = htmlElement::ALIGN_RIGHT;
973 $pykotaJobs->add($size, 1);
974 $pykotaJobs->add(new htmlOutputText($job['pykotatitle'][0]), 3);
975 }
976 $row = new htmlResponsiveRow();
977 $row->add(new htmlSpacer(null, '10px'));
978 $row->add(new htmlOutputText($this->getSelfServiceLabel('pykotaJobHistory', _('Job history'))), 12, 12, 12, 'bold text-left');
979 $row->add($pykotaJobs);
980 $return['pykotaJobHistory'] = $row;
981 }
982 return $return;
983 }
984
985 /**
986 * {@inheritDoc}
987 */
988 public function checkSelfServiceSettings(array &$options, selfServiceProfile &$profile): array {
989 $errors = [];
990 if ((static::class === 'pykotaUser')
991 && !empty($options['pykotaUser_jobSuffix'][0])
992 && !get_preg($options['pykotaUser_jobSuffix'][0], 'dn')) {
993 $errors[] = $this->messages['jobSuffix'][0];
994 }
995 return $errors;
996 }
997
998 /**
999 * Returns if the uid attribute should be managed.
1000 *
1001 * @param string[] $modules account modules
1002 * @return boolean manage uid attribute
1003 */
1004 private function manageUid($modules) {
1005 return !in_array('inetOrgPerson', $modules) && !in_array('posixAccount', $modules);
1006 }
1007
1008 /**
1009 * Returns if the mail attribute should be managed.
1010 *
1011 * @param string[] $modules account modules
1012 * @return boolean manage mail attribute
1013 */
1014 private function manageMail($modules) {
1015 return !in_array('inetOrgPerson', $modules);
1016 }
1017
1018 /**
1019 * Returns if the description attribute should be managed.
1020 *
1021 * @param string[] $modules account modules
1022 * @return boolean manage description attribute
1023 */
1024 private function manageDescription($modules) {
1025 return !in_array('inetOrgPerson', $modules);
1026 }
1027
1028 /**
1029 * Returns if the given uid already exists.
1030 *
1031 * @param String $uid uid attribute value
1032 * @return boolean uid exists
1033 */
1034 private function uidExists($uid) {
1035 if ($this->uidCache === null) {
1036 $this->loadUserNameCache();
1037 }
1038 return in_array($uid, $this->uidCache);
1039 }
1040
1041 /**
1042 * Returns if the given pykotaUserName already exists.
1043 *
1044 * @param String $pykotaUserName pykotaUserName attribute value
1045 * @return boolean pykotaUserName exists
1046 */
1047 private function pykotaUserNameExists($pykotaUserName) {
1048 if ($this->pykotaUserNameCache === null) {
1049 $this->loadUserNameCache();
1050 }
1051 return in_array($pykotaUserName, $this->pykotaUserNameCache);
1052 }
1053
1054 /**
1055 * Loads the list of user names into the cache.
1056 */
1057 private function loadUserNameCache(): void {
1058 $results = searchLDAPByFilter('(|(uid=*)(pykotaUserName=*))', ['uid', 'pykotaUserName'], [$this->get_scope()]);
1059 $this->uidCache = [];
1060 $this->pykotaUserNameCache = [];
1061 foreach ($results as $result) {
1062 if (isset($result['uid'][0])) {
1063 $this->uidCache[] = $result['uid'][0];
1064 }
1065 if (isset($result['pykotausername'][0])) {
1066 $this->pykotaUserNameCache[] = $result['pykotausername'][0];
1067 }
1068 }
1069 }
1070
1071 /**
1072 * Returns the current user name (uid) of this account.
1073 *
1074 * @return String user name
1075 */
1076 private function getCurrentUserName() {
1077 if (!empty($this->attributes['uid'][0])) {
1078 return $this->attributes['uid'][0];
1079 }
1080 if ($this->getAccountContainer()->getAccountModule('posixAccount') != null) {
1081 $posix = $this->getAccountContainer()->getAccountModule('posixAccount');
1082 $attrs = $posix->getAttributes();
1083 if (!empty($attrs['uid'][0])) {
1084 return $attrs['uid'][0];
1085 }
1086 }
1087 if ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
1088 $personal = $this->getAccountContainer()->getAccountModule('inetOrgPerson');
1089 $attrs = $personal->getAttributes();
1090 if (!empty($attrs['uid'][0])) {
1091 return $attrs['uid'][0];
1092 }
1093 }
1094 return '';
1095 }
1096
1097 /**
1098 * Returns a list of jobs for the given user reverse-sorted by date.
1099 * The number of jobs is limited to 100.
1100 *
1101 * @param string $user user name
1102 * @param string $suffix LDAP suffix for job objects
1103 * @return array<string, string[]|string>[] jobs
1104 */
1105 private function getJobs($user, $suffix): array {
1106 $attrs = ['createTimestamp', 'pykotaTitle', 'pykotaPrinterName', 'pykotaJobPrice', 'pykotaJobSize'];
1107 $filter = '(&(objectClass=pykotaJob)(pykotaUserName=' . $user . '))';
1108 $jobList = searchLDAP($suffix, $filter, $attrs);
1109 $jobs = [];
1110 foreach ($jobList as $index => $job) {
1111 $jobs[$job['createtimestamp'][0] . $index] = $job;
1112 }
1113 krsort($jobs);
1114 if (count($jobs) > 100) {
1115 $jobs = array_slice($jobs, 0, 100);
1116 }
1117 return array_values($jobs);
1118 }
1119
1120 /**
1121 * {@inheritDoc}
1122 */
1123 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
1124 $configContainer = new htmlResponsiveRow();
1125 $configContainer->add(new htmlResponsiveInputField(_('Job suffix'), 'pykotaUser_jobSuffix', '', 'jobSuffix'));
1126 return $configContainer;
1127 }
1128
1129 /**
1130 * @inheritDoc
1131 */
1132 public function getListAttributeDescriptions(ConfiguredType $type): array {
1133 return [
1134 'pykotausername' => _('PyKota user name'),
1135 'pykotalimitby' => _('Limit type'),
1136 'pykotabalance' => _('Balance'),
1137 'pykotaovercharge' => _('Overcharge factor'),
1138 'pykotalifetimepaid' => _('Total paid'),
1139 'pykotapayments' => _('Payment history'),
1140 ];
1141 }
1142
1143 /**
1144 * @inheritDoc
1145 */
1146 public function getListRenderFunction(string $attributeName, ConfiguredType $type): ?callable {
1147 if ($attributeName === 'mail') {
1148 return function(array $entry, string $attribute): htmlElement {
1149 $group = new htmlGroup();
1150 if (isset($entry[$attribute][0]) && ($entry[$attribute][0] != '')) {
1151 for ($i = 0; $i < count($entry[$attribute]); $i++) {
1152 if ($i > 0) {
1153 $group->addElement(new htmlOutputText(", "));
1154 }
1155 $group->addElement(new htmlLink($entry[$attribute][$i], "mailto:" . $entry[$attribute][$i]));
1156 }
1157 }
1158 return $group;
1159 };
1160 }
1161 return null;
1162 }
1163
1164 }