Debian Codegraph @

lib/modules/asteriskExtension.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
8 /*
9
10 This code is part of LDAP Account Manager (http://www.sourceforge.net/projects/lam)
11 Copyright (C) 2009 - 2012 Pavel Pozdniak
12 2009 - 2026 Roland Gruber
13
14 This program is free software; you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation; either version 2 of the License, or
17 (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27
28 */
29
30
31 /**
32 * Manages Asterisk extensions.
33 *
34 * @package modules
35 *
36 * @author Pavel Pozdniak
37 * @author Roland Gruber
38 */
39
40 /**
41 * Manages Asterisk extensions.
42 *
43 * @package modules
44 */
45 class asteriskExtension extends baseModule {
46
47 /**
48 * These attributes will be ignored by default if a new account is copied from an existing one.
49 */
50 private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['AstExtension'];
51
52 /** if true then only Asterisk accounts are shown as possible owners */
53 private bool $filterOwnerForAsteriskAccounts = true;
54
55 /** @var array<int, array<string, array<int, string>|string>> $extensionRows Contains all attributes information for set of accounts */
56 private array $extensionRows = [];
57 /** @var array<int, array<string, array<int, string>|string>> $extensionRowsOrig Contains all original attributes information for set of accounts */
58 private array $extensionRowsOrig = [];
59 /** @var array<int, string> $extensionOwners extension owners */
60 private array $extensionOwners = [];
61 /** flag if new rule should be added */
62 private bool $addRuleFlag = false;
63
64 /**
65 * {@inheritDoc}
66 */
67 public function can_manage(): bool {
68 return $this->get_scope() === 'asteriskExt';
69 }
70
71 /**
72 * {@inheritDoc}
73 */
74 public function get_metaData(): array {
75 $return = [];
76 $return["is_base"] = true;
77 // RDN attribute
78 $return["RDN"] = ["cn" => "normal"];
79 // LDAP filter
80 $return["ldap_filter"] = ['or' => "(objectClass=AsteriskExtension)"];
81 // alias name
82 $return["alias"] = _("Asterisk extension");
83 // module dependencies
84 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
85 // managed object classes
86 $return['objectClasses'] = ['AsteriskExtension', 'groupOfNames'];
87 // managed attributes
88 $return['attributes'] = ['cn', 'member', 'AstExtension', 'AstPriority',
89 'AstApplication', 'AstApplicationData', 'AstContext'];
90 //ldap aliases
91 $return['LDAPaliases'] = ['commonName' => 'cn'];
92 // icon
93 $return['icon'] = 'asterisk.png';
94 // help
95 $return['help'] = [
96 'AstApplicationData' => [
97 "Headline" => _("Application data"), 'attr' => 'AstApplicationData',
98 "Text" => _("This defines what application Asterisk has to start for this user (e.g. SIP/user1).")
99 ],
100 'AstContext' => [
101 "Headline" => _("Account context"), 'attr' => 'AstContext',
102 "Text" => _("The account context stores information about the dial plan.")
103 ],
104 'AstExtension' => [
105 "Headline" => _("Extension name"), 'attr' => 'AstExtension',
106 "Text" => _("The name of the extension (e.g. voicemail or sip).")
107 ],
108 'AstPriority' => [
109 "Headline" => _("Priority"), 'attr' => 'AstPriority',
110 "Text" => _("The priority is a sequence number used to order the execution of commands. Commands are executed beginning with the lowest sequence number.")
111 ],
112 'AstApplication' => [
113 "Headline" => _("Application"), 'attr' => 'AstApplication',
114 "Text" => _("The name of a command to execute. The available commands may be listed at the Asterisk command line by executing \"core show applications\".")
115 ],
116 'member' => [
117 "Headline" => _("Extension owners"), 'attr' => 'member',
118 "Text" => _("DNs of the extension owners")
119 ],
120 'cn' => [
121 "Headline" => _("Common name"), 'attr' => 'cn',
122 "Text" => _("Common name of the Asterisk extension.")
123 ],
124 'ownerOptions' => [
125 "Headline" => _("Options"),
126 "Text" => _("These options change the list of potential extension owners below. You can select to show Asterisk accounts or all users.")
127 ],
128 ];
129
130 // profile options
131 $profileContainer = new htmlResponsiveRow();
132 $profileContainer->add(new htmlResponsiveInputField(_('Account context'), 'AsteriskExtension_AstContext', null, 'AstContext'));
133 $return['profile_options'] = $profileContainer;
134 $return['profile_mappings'] = [
135 'AsteriskExtension_AstContext' => 'AstContext',
136 ];
137 // available PDF fields
138 $return['PDF_fields'] = [
139 'AstContext' => _('Account context'),
140 'AstExtension' => _('Extension name'),
141 'owners' => _('Extension owners'),
142 'rules' => _('Rules'),
143 ];
144
145 $return['upload_columns'] = [
146 [
147 'name' => 'asteriskExtension_AstExtension',
148 'description' => _('Extension name'),
149 'help' => 'AstExtension',
150 'example' => '500',
151 'required' => true
152 ],
153 [
154 'name' => 'asteriskExtension_AstContext',
155 'description' => _('Account context'),
156 'help' => 'AstContext',
157 'example' => _('test'),
158 'required' => true,
159 ],
160 [
161 'name' => 'asteriskExtension_owner',
162 'description' => _('Extension owners'),
163 'help' => 'member',
164 'example' => 'uid=user1,o=test;uid=user2,o=test',
165 ],
166 [
167 'name' => 'asteriskExtension_AstApplication',
168 'description' => _('Application'),
169 'help' => 'AstApplication',
170 'example' => 'Playback',
171 'required' => true
172 ],
173 [
174 'name' => 'asteriskExtension_AstApplicationData',
175 'description' => _('Application data'),
176 'help' => 'AstApplicationData',
177 'example' => _('test-start'),
178 ],
179
180 ];
181 return $return;
182 }
183
184 /**
185 * {@inheritDoc}
186 */
187 protected function load_Messages(): void {
188 $this->messages['cn'][0] = ['ERROR', _('Please enter a common name.')];
189 $this->messages['AstApplication'][0] = ['ERROR', _('Please enter the application.')];
190 $this->messages['AstApplicationData'][0] = ['ERROR', _('Please enter the application data.')];
191 $this->messages['AstContext'][0] = ['ERROR', _('Please enter the account context.')];
192 $this->messages['AstExtension'][0] = ['ERROR', _('Please enter the extension name.')];
193 $this->messages['AstExtension'][1] = ['ERROR', _('Extension with this name already exists.')];
194 $this->messages['AstPriority'][0] = ['ERROR', _('Please enter the priority.')];
195 $this->messages['AstExtensionAstPriority'][0] = ['ERROR', _('This pair of extension name and priority already exists.')];
196 $this->messages['member'][0] = ['ERROR', _('Please add at least one extension owner.')];
197
198 }
199
200 /**
201 * {@inheritDoc}
202 */
203 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
204 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY));
205 }
206
207 /**
208 * {@inheritDoc}
209 */
210 public function display_html_attributes(): htmlElement|array {
211 $return = new htmlResponsiveRow();
212
213 $extName = '';
214 if (isset($this->attributes['AstExtension'][0])) {
215 $extName = $this->attributes['AstExtension'][0];
216 }
217 if (isset($this->extensionRows[0]['astextension'][0])) {
218 $extName = $this->extensionRows[0]['astextension'][0];
219 }
220 //This procedure LOAD all data from LDAP and then print to a page
221 $this->render_extensions_by_priority($extName, $return);
222
223 // owners
224 //Set default owner as logged in user if no other owner is set
225 if (!$this->isExtensionOwnerSet()) {
226 $this->setDefaultExtensionOwner();
227 }
228
229 $this->render_exten_owners_set_controls($return);
230
231 return $return;
232 }
233
234 /**
235 * This function prints management elements to manipulate owners of an extension.
236 *
237 * @param htmlResponsiveRow $renderContainer
238 */
239 private function render_exten_owners_set_controls($renderContainer): void {
240 $renderContainer->addVerticalSpacer('1rem');
241 $title = new htmlSubTitle(_("Extension owners"));
242 $title->setHelpId('member');
243 $renderContainer->add($title);
244 $ownerList = new htmlTable();
245 if ((count($this->extensionOwners) === 0) && isset($this->extensionRows[0]['member'])) {
246 $this->extensionOwners = $this->extensionRows[0]['member'];
247 }
248 for ($i = 0; $i < count($this->extensionOwners); $i++) {
249 $ownerList->addElement(new htmlOutputText(getAbstractDN($this->extensionOwners[$i])), true);
250 }
251 $renderContainer->add($ownerList);
252 $renderContainer->addVerticalSpacer('1rem');
253 $renderContainer->add(new htmlAccountPageButton(static::class, 'user', 'open', _('Change')));
254 }
255
256 /**
257 * Loads all related extension entries.
258 *
259 * @param string $extension extension name
260 * @return array<int, array<string, string[]|string>> extensions
261 */
262 private function load_extension_parts($extension): array {
263 if (!isset($this->extensionRows[0]['astcontext'][0])) {
264 $entries = searchLDAP($this->getAccountContainer()->dnSuffix, '(&(objectClass=AsteriskExtension)(AstExtension=' . $extension . '))', ['cn', 'AstContext', 'AstPriority',
265 'AstApplication', 'AstApplicationData', 'AstExtension', 'member', 'ObjectClass']);
266
267 $entries = $this->array_sort($entries, 'astpriority');
268 $this->extensionRowsOrig = $entries;
269 $this->extensionRows = $entries;
270 if (isset($this->extensionRows[0]['member'])) {
271 $this->extensionOwners = $this->extensionRows[0]['member'];
272 }
273 }
274 else {
275 $entries = $this->extensionRows;
276 }
277 return $entries;
278 }
279
280 /**
281 * Generates the meta HTML for the rules.
282 *
283 * @param string $extension extension name
284 * @param htmlResponsiveRow $renderContainer container
285 */
286 private function render_extensions_by_priority(string $extension, $renderContainer): void {
287 $entries = $this->load_extension_parts($extension);
288
289 if ($this->getAccountContainer()->isNewAccount) {
290 $suggestedExtName = $this->generateNextExtensionName();
291 $extNameInput = new htmlResponsiveInputField(_("Extension name"), 'AstExtension', $suggestedExtName, 'AstExtension');
292 }
293 else {
294 $extNameInput = new htmlResponsiveInputField(_("Extension name"), 'AstExtension', $extension, 'AstExtension');
295 }
296 $extNameInput->setRequired(true);
297 $renderContainer->add($extNameInput);
298
299 $accountContext = '';
300 if (isset($entries[0]['astcontext'][0])) {
301 //LOAD context from already entities that already exists
302 $accountContext = $entries[0]['astcontext'][0];
303 }
304 elseif (isset($this->attributes['AstContext'][0])) {
305 //LOAD context from attributes, this is to deal with profile
306 $accountContext = $this->attributes['AstContext'][0];
307 }
308 $accountContextInput = new htmlResponsiveInputField(_("Account context"), 'AstContext', $accountContext, 'AstContext');
309 $accountContextInput->setRequired(true);
310 $renderContainer->add($accountContextInput);
311
312
313 $renderContainer->add(new htmlSubTitle(_('Rules')));
314 $renderContainer->addVerticalSpacer('1rem');
315
316 for ($i = 0; $i < count($entries); $i++) {
317 $this->render_extension($entries[$i], $i, $renderContainer);
318 $renderContainer->addLabel(new htmlButton("delete_rule_" . $i, _('Delete rule')));
319
320 $upDownButtons = new htmlTable();
321 if ($i > 0) {
322 $upDownButtons->addElement(new htmlButton('rule_up_button_' . $i, 'up.svg', true));
323 }
324 if (($i < count($entries) - 1) &&
325 ((count($entries) > 1) || ($this->addRuleFlag))) {
326 $upDownButtons->addElement(new htmlButton('rule_down_button_' . $i, 'down.svg', true));
327 }
328 $renderContainer->addField($upDownButtons);
329
330 $renderContainer->addVerticalSpacer('2rem');
331 }
332
333 $displayEntrNum = count($entries);
334
335 if ($this->addRuleFlag || count($entries) === 0) {
336
337 $this->render_extension([], count($entries), $renderContainer);
338
339 if ($this->addRuleFlag) {
340 $upDownButtons = new htmlTable();
341 $renderContainer->addLabel(new htmlButton("delete_rule_" . $i, _('Delete rule')));
342 $upDownButtons->addElement(new htmlButton('rule_up_button_' . $i, 'up.svg', true));
343 $renderContainer->addField($upDownButtons);
344 }
345
346 $displayEntrNum++;
347 $this->addRuleFlag = false;
348 }
349 // the size of found rows plus 1 for the new one
350 $renderContainer->add(new htmlHiddenInput("extension_rows", (string) $displayEntrNum));
351
352 $renderContainer->add(new htmlButton("add_rule", _('Add another rule')));
353 }
354
355 /**
356 * Generates the meta HTML for a single rule.
357 *
358 * @param array<string, string[]|string> $extensLine attributes of rule
359 * @param int $placeInList rule position
360 * @param htmlResponsiveRow $renderContainer container
361 */
362 private function render_extension($extensLine, $placeInList, $renderContainer): void {
363 // application
364 $application = '';
365 if (isset($extensLine['astapplication'][0])) {
366 $application = $extensLine['astapplication'][0];
367 }
368 $applicationInput = new htmlResponsiveInputField(_("Application"), "AstApplication_" . $placeInList, $application, 'AstApplication');
369 $applicationInput->setRequired(true);
370 $renderContainer->add($applicationInput);
371 // application data
372 $applicationData = '';
373 if (isset($extensLine['astapplicationdata'][0])) {
374 $applicationData = $extensLine['astapplicationdata'][0];
375 }
376 $renderContainer->add(new htmlResponsiveInputField(_("Application data"), "AstApplicationData_" . $placeInList, $applicationData, 'AstApplicationData'));
377 //delimiter
378 $renderContainer->addVerticalSpacer('0.5rem');
379 }
380
381 /**
382 * Sorts an array of arrays by the given key.
383 *
384 * @param array<int, array<string, string[]|string>|string> $array array
385 * @param string $on key
386 * @param string $order order (SORT_ASC or SORT_DESC)
387 * @return array<int, array<string, string[]|string>|string> result
388 */
389 private function array_sort($array, $on, $order = 'SORT_ASC'): array {
390 $new_array = [];
391 $sortable_array = [];
392
393 if (count($array) > 0) {
394 foreach ($array as $k => $v) {
395 if (is_array($v)) {
396 foreach ($v as $k2 => $v2) {
397 if ($k2 == $on) {
398 $sortable_array[$k] = $v2;
399 }
400 }
401 }
402 else {
403 $sortable_array[$k] = $v;
404 }
405 }
406 if ($order === 'SORT_ASC') {
407 asort($sortable_array);
408 }
409 else {
410 arsort($sortable_array);
411 }
412 foreach (array_keys($sortable_array) as $k) {
413 $new_array[] = $array[$k];
414 }
415 }
416 return $new_array;
417 }
418
419 /**
420 * Displays a list of possible owners of this extension.
421 *
422 * @return htmlResponsiveRow HTML meta data
423 */
424 public function display_html_user(): htmlResponsiveRow {
425 $return = new htmlResponsiveRow();
426 // load list with all potential owners
427 $searchScope = 'user';
428 $searchClass = 'inetOrgPerson';
429 if ($this->filterOwnerForAsteriskAccounts) {
430 $searchClass = 'AsteriskSIPUser';
431 }
432 $entries = searchLDAPByAttribute(null, null, $searchClass, ['dn'], [$searchScope]);
433 $users_dn = [];
434 for ($i = 0; $i < count($entries); $i++) {
435 $dn = $entries[$i]['dn'];
436 if (!in_array($dn, $this->extensionOwners)) {
437 $users_dn[getAbstractDN($dn)] = $dn;
438 }
439 }
440 uasort($users_dn, compareDN(...));
441 $memberList = $this->extensionOwners;
442 usort($memberList, compareDN(...));
443 $members = [];
444 for ($i = 0; $i < count($memberList); $i++) {
445 $members[getAbstractDN($memberList[$i])] = $memberList[$i];
446 }
447 // options
448 $return->add(new htmlSubTitle(_("Filters")));
449 $return->add(new htmlResponsiveInputCheckbox('filterAsteriskUsers', $this->filterOwnerForAsteriskAccounts, _('Show only Asterisk accounts'), 'ownerOptions', false));
450 $refreshButton = new htmlButton('changeFilter', _('Refresh'));
451 $return->add($refreshButton);
452 $return->addVerticalSpacer('1rem');
453 // owners
454 $return->add(new htmlSubTitle(_("Extension owners")));
455 $this->addDoubleSelectionArea($return, _("Selected users"), _("Available users"), $members, [], $users_dn, [], 'owners', true);
456 // back button
457 $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Ok'));
458 $backButton->colspan = 3;
459 $return->add($backButton);
460 return $return;
461 }
462
463 /**
464 * Processes user input of the user selection page.
465 * It checks if all input values are correct and updates the associated LDAP attributes.
466 *
467 * @return array<string|string[]>[] list of info/error messages
468 */
469 public function process_user(): array {
470 if (isset($_POST['changeFilter'])) {
471 // update filter value
472 if (isset($_POST['filterAsteriskUsers'])) {
473 $this->filterOwnerForAsteriskAccounts = ($_POST['filterAsteriskUsers'] == 'on');
474 }
475 else {
476 $this->filterOwnerForAsteriskAccounts = false;
477 }
478 }
479 if (isset($_POST['owners_2']) && isset($_POST['owners_left'])) {
480 // Add new user
481 $this->extensionOwners = @array_merge($this->extensionOwners, $_POST['owners_2']);
482 }
483 elseif (isset($_POST['owners_1']) && isset($_POST['owners_right'])) {
484 $this->extensionOwners = array_delete($_POST['owners_1'], $this->extensionOwners);
485 }
486 $this->attributes['member'] = $this->extensionOwners;
487
488 return [];
489 }
490
491 /**
492 * Returns if the extension was moved to another OU.
493 *
494 * @return bool true if moved
495 */
496 private function isMoveToNewSuffix(): bool {
497 $orig_suffix = extractDNSuffix($this->getAccountContainer()->dn_orig);
498 return strcmp($orig_suffix, $this->getAccountContainer()->dnSuffix) !== 0
499 && !$this->getAccountContainer()->isNewAccount;
500 }
501
502
503 /**
504 * Returns true if at least one owner is set and false otherwise
505 *
506 * @return bool true if one or more owners
507 */
508 private function isExtensionOwnerSet(): bool {
509 return (count($this->extensionOwners) > 0);
510 }
511
512 /**
513 * {@inheritDoc}
514 */
515 public function process_attributes(): array {
516 $errors = [];
517 $extensionName = [];
518
519 if (!isset($_POST['generate_extension_name'])) {
520
521 //perform normal set of operations
522 if (isset($_POST['AstExtension']) && $_POST['AstExtension'] != '') {
523 $this->attributes['AstExtension'][0] = $_POST['AstExtension'];
524 $extensionName[0] = $_POST['AstExtension'];
525 }
526 else {
527 $errors[] = $this->messages['AstExtension'][0];
528 }
529 $extensionContext = [];
530 if (isset($_POST['AstContext'])) {
531 $this->attributes['AstContext'][0] = $_POST['AstContext'];
532 $extensionContext[0] = $_POST['AstContext'];
533 if ($extensionContext[0] == '') {
534 $errors[] = $this->messages['AstContext'][0];
535 }
536 }
537
538 if ($this->getAccountContainer()->isNewAccount && isset($extensionName[0])) {
539 $isPresented = $this->isThisExtensionPresented($extensionName[0]);
540 if ($isPresented) {
541 $errors[] = $this->messages['AstExtension'][1];
542 }
543 }
544
545 if (isset($_POST['add_rule'])) {
546 $this->addRuleFlag = true;
547 }
548 //process fields that are individual for each row
549 $extrow_errors = $this->processExtensionRows($extensionName, $extensionContext);
550
551 if (!empty($extrow_errors)) {
552 $errors = array_merge($errors, $extrow_errors);
553 }
554 }
555 else {
556 //find new free extension name
557 $this->extensionRows[0]['astextension'][0] = $this->generateNextExtensionName();
558 }
559
560 return $errors;
561 }
562
563 /**
564 * Processes the rule data.
565 *
566 * @param string[] $extensionName extension name
567 * @param string[] $extensionContext extension context
568 * @return array<string|string[]>[] error messages
569 */
570 private function processExtensionRows($extensionName, $extensionContext): array {
571 $errors = [];
572 if (isset($_POST['extension_rows']) && get_preg($_POST['extension_rows'], 'digit')) {
573
574 $extensionPriorityCntr = 1;
575 $this->extensionRows = [];
576 for ($entryCounter = 0; $entryCounter < $_POST['extension_rows']; $entryCounter++) {
577 $extRow = [];
578 if (!isset($_POST['delete_rule_' . $entryCounter])) {
579 $singleExtAddErrors = $this->processSingleExtension($extRow, $extensionName, $extensionContext, $entryCounter, $extensionPriorityCntr);
580 $errors += $singleExtAddErrors;
581
582 if ((isset($extRow['astapplication'][0]) && $extRow['astapplication'][0] != "") ||
583 (isset($extRow['astapplicationdata'][0]) && $extRow['astapplicationdata'][0] != "")
584 ) {
585 $this->extensionRows[$extensionPriorityCntr - 1] = $extRow;
586 $extensionPriorityCntr++;
587 }
588 }
589 }
590
591 //trow error banner if last row unporpertly filled (for now the only reason for that is unfilled AstApplication filed)
592 if (isset($_POST['AstApplicationData_' . ($_POST['extension_rows'] - 1)]) && $_POST['AstApplicationData_' . ($_POST['extension_rows'] - 1)] != "" &&
593 ($_POST['AstApplication_' . ($_POST['extension_rows'] - 1)] == "" || !isset($_POST['AstApplication_' . ($_POST['extension_rows'] - 1)]))) {
594 $errors[] = $this->messages['AstApplication'][0];
595 }
596
597 //process priority change on rule
598 $this->processPriorityChange();
599
600 //finally sort extensions by priority
601 $this->extensionRows = $this->array_sort($this->extensionRows, 'astpriority');
602 }
603 return $errors;
604 }
605
606 /**
607 * Set extension owner as current logged in user.
608 */
609 private function setDefaultExtensionOwner(): void {
610 $login = $this->getDefaultExtensionOwner();
611 $this->extensionOwners[0] = $login;
612 $this->attributes['member'] = [$login];
613 }
614
615 /**
616 * Returns the default extension owner.
617 *
618 * @return String owner
619 */
620 private function getDefaultExtensionOwner() {
621 return $_SESSION['ldap']->getUserName();
622 }
623
624 /**
625 * Fills the fields of a single extension row.
626 * In Asterisk it would only be an extension name,a priority,an application, but LDAP specific
627 * add to processing context field.
628 *
629 * @param array<string, array<int, string>|string> $extRow - hash array to store single extension properties;
630 * @param string[] $extensionName extension name
631 * @param string[] $extensionContext extension context
632 * @param int $entryCounter - counter to distinguish single extensuion properties from $_POST
633 * @param int $extensionPriorityCntr - it is the variable where actual number of extension rules wuld be aggregated
634 * @return array<string|string[]>[] errors
635 */
636 private function processSingleExtension(&$extRow, $extensionName, $extensionContext, $entryCounter, $extensionPriorityCntr): array {
637 $errors = [];
638 if (isset($extensionContext[0])) {
639 $extRow['astcontext'][0] = $extensionContext[0];
640 }
641 if (isset($extensionName[0])) {
642 $extRow['astextension'][0] = $extensionName[0];
643 }
644
645 $extRow["objectclass"][0] = "top";
646 $extRow["objectclass"][1] = "groupOfNames";
647 $extRow["objectclass"][2] = "AsteriskExtension";
648
649 $extRow['astapplication'][0] = (string) $_POST['AstApplication_' . $entryCounter];
650 if ((!isset($_POST['AstApplication_' . $entryCounter]) || $_POST['AstApplication_' . $entryCounter] == '')
651 && ($entryCounter < ($_POST['extension_rows'] - 1))) {
652 $errors[] = $this->messages['AstApplication'][0];
653 }
654
655 $extRow['astpriority'][0] = strval($extensionPriorityCntr);
656
657 $extRow['cn'][0] = $extRow['astextension'][0] . "-" . $extRow['astpriority'][0];
658
659 if (isset($_POST['AstApplicationData_' . $entryCounter]) && $_POST['AstApplicationData_' . $entryCounter] != "") {
660 $extRow['astapplicationdata'][0] = (string) $_POST['AstApplicationData_' . $entryCounter];
661 }
662
663 //Fill the member filed
664 $extRow['member'] = $this->extensionOwners;
665 if ((count($extRow['member']) === 0)
666 && !isset($_POST['form_subpage_' . static::class . '_user_open'])) {
667 $errors[] = $this->messages['member'][0];
668 }
669 return $errors;
670 }
671
672 /**
673 * Reorders the rules if the user clicked on a move button.
674 */
675 private function processPriorityChange(): void {
676 for ($entryCounter = 0; $entryCounter < count($this->extensionRows); $entryCounter++) {
677 if (isset($_POST["rule_up_button_" . $entryCounter])) {
678 $this->extensionRows[$entryCounter]['astpriority'][0] = (string) (intval($this->extensionRows[$entryCounter]['astpriority'][0]) - 1);
679 $this->extensionRows[$entryCounter - 1]['astpriority'][0] = (string) (intval($this->extensionRows[$entryCounter - 1]['astpriority'][0]) + 1);
680 }
681 elseif (isset($_POST["rule_down_button_" . $entryCounter])) {
682 $this->extensionRows[$entryCounter]['astpriority'][0] = (string) (intval($this->extensionRows[$entryCounter]['astpriority'][0]) + 1);
683 $this->extensionRows[$entryCounter + 1]['astpriority'][0] = (string) (intval($this->extensionRows[$entryCounter + 1]['astpriority'][0]) - 1);
684 }
685 }
686 }
687
688 /**
689 * Search by extension name and return true if fields with this extension name exists
690 * and false otherwise.
691 * Equal extension names are allowed in different OUs.
692 *
693 * @param string $extension extension name
694 * @return bool true if there are entries with this extension name.
695 */
696 private function isThisExtensionPresented($extension): bool {
697 $searchClass = "AsteriskExtension";
698 $searchScope = 'asteriskExt';
699
700 $entries = searchLDAPByAttribute("AstExtension", $extension, $searchClass, ['dn'], [$searchScope]);
701
702 $exists = false;
703 for ($i = 0; $i < count($entries); $i++) {
704 $dn = extractDNSuffix($entries[$i]['dn']);
705 if ($dn == $this->getAccountContainer()->dnSuffix) {
706 $exists = true;
707 break;
708 }
709 }
710 return $exists;
711 }
712
713 /**
714 * This function searches in the base subtree and finds all extensions names within.
715 * The generation algorithm is the naive one, so only work when extension is numbers.
716 * All extension name is sorted and new extension name will be greates on + 1.
717 *
718 * @return string suggested extension name
719 */
720 private function generateNextExtensionName() {
721 $searchClass = "AsteriskExtension";
722 $searchScope = 'asteriskExt';
723 if (isset($this->extensionRows[0]['astextension'][0])) {
724 $suggested_extension = $this->extensionRows[0]['astextension'][0];
725 }
726 else {
727 $entries = searchLDAPByAttribute(null, null, $searchClass, ['astextension'], [$searchScope]);
728 $entries = $this->array_sort($entries, 'astextension');
729
730 $greater_ext_name = $entries[count($entries) - 1]['astextension'][0] ?? 0;
731 if (is_numeric($greater_ext_name)) {
732 $suggested_extension = $greater_ext_name + 1;
733 }
734 else {
735 $ptn = "/(?P<name>[A-Za-z0-9]+)_(?P<digit>\\d+)/";
736 if (preg_match_all($ptn, $greater_ext_name, $matches)) {
737 $next_digit = ((int) $matches['digit'][0]) + 1;
738 $suggested_extension = $matches['name'][0] . '_' . $next_digit;
739 }
740 else {
741 $suggested_extension = $greater_ext_name . '_1';
742 }
743 }
744 }
745 return $suggested_extension;
746 }
747
748 /**
749 * {@inheritDoc}
750 */
751 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
752 $return = [];
753 $extName = '';
754 if (isset($this->attributes['AstExtension'][0])) {
755 $extName = $this->attributes['AstExtension'][0];
756 }
757 if (isset($this->extensionRows[0]['astextension'][0])) {
758 $extName = $this->extensionRows[0]['astextension'][0];
759 }
760 // global values
761 $this->addSimplePDFField($return, 'AstContext', _('Account context'));
762 $this->addSimplePDFField($return, 'AstExtension', _('Extension name'));
763 $this->addSimplePDFField($return, 'owners', _('Extension owners'), 'member', '; ');
764 // rules
765 $entries = $this->load_extension_parts($extName);
766 $pdfTable = new PDFTable();
767 $pdfRow = new PDFTableRow();
768 $pdfRow->cells[] = new PDFTableCell(_('Name'), '20%', null, true);
769 $pdfRow->cells[] = new PDFTableCell(_('Application'), '30%', null, true);
770 $pdfRow->cells[] = new PDFTableCell(_('Application data'), '30%', null, true);
771 $pdfRow->cells[] = new PDFTableCell(_('Priority'), '20%', null, true);
772 $pdfTable->rows[] = $pdfRow;
773 for ($i = 0; $i < count($entries); $i++) {
774 $appdata = ' ';
775 if (isset($entries[$i]['astapplicationdata'][0])) {
776 $appdata = $entries[$i]['astapplicationdata'][0];
777 }
778 $pdfRow = new PDFTableRow();
779 $pdfRow->cells[] = new PDFTableCell($entries[$i]['cn'][0], '20%');
780 $pdfRow->cells[] = new PDFTableCell($entries[$i]['astapplication'][0], '30%');
781 $pdfRow->cells[] = new PDFTableCell($appdata, '30%');
782 $pdfRow->cells[] = new PDFTableCell($entries[$i]['astpriority'][0], '20%');
783 $pdfTable->rows[] = $pdfRow;
784 }
785 $this->addPDFTable($return, 'rules', $pdfTable);
786 return $return;
787 }
788
789 /**
790 * {@inheritDoc}
791 */
792 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
793 $messages = [];
794 //hash to store extension_name => priority. For new extension priority will be 1
795 $extensionNamePriorityMap = [];
796 for ($i = 0; $i < count($rawAccounts); $i++) {
797 // add object class
798 if (!in_array("AsteriskExtension", $partialAccounts[$i]['objectClass'])) {
799 $partialAccounts[$i]['objectClass'][] = "AsteriskExtension";
800 }
801 if (!in_array("groupOfNames", $partialAccounts[$i]['objectClass'])) {
802 $partialAccounts[$i]['objectClass'][] = "groupOfNames";
803 }
804 // attributes
805 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'asteriskExtension_AstExtension', 'AstExtension');
806
807 $extensionName = $partialAccounts[$i]['AstExtension'];
808 if (isset($extensionNamePriorityMap[$extensionName])) {
809 $astPriorityTmp = $extensionNamePriorityMap[$extensionName] + 1;
810 $extensionNamePriorityMap[$extensionName] = $astPriorityTmp;
811 }
812 else {
813 $astPriorityTmp = 1;
814 $extensionNamePriorityMap[$extensionName] = $astPriorityTmp;
815 }
816 $partialAccounts[$i]['AstPriority'] = $astPriorityTmp;
817
818 $partialAccounts[$i]['cn'] = $extensionName . '-' . $astPriorityTmp;
819
820 if (isset($rawAccounts[$i][$ids['asteriskExtension_owner']]) && $rawAccounts[$i][$ids['asteriskExtension_owner']] != '') {
821 $partialAccounts[$i]['member'] = explode(';', $rawAccounts[$i][$ids['asteriskExtension_owner']]);
822 }
823 else {
824 $partialAccounts[$i]['member'] = $this->getDefaultExtensionOwner();
825 }
826
827 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'asteriskExtension_AstApplication', 'AstApplication');
828 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'asteriskExtension_AstApplicationData', 'AstApplicationData');
829 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'asteriskExtension_AstContext', 'AstContext');
830 }
831
832 return $messages;
833 }
834
835 /**
836 * Get list of all applications for given extension and move it into new suffix.
837 *
838 * @param array<string, string[]|string> $row attributes of original extension
839 * @return array<string|string[]>[] list of error messages
840 */
841 private function moveExtentionToNewSuffix($row): array {
842 $errors = [];
843 if ($this->isMoveToNewSuffix()) {
844 $oldDN = "cn=" . $row["cn"][0] . "," . extractDNSuffix($this->getAccountContainer()->dn_orig);
845 $newRDN = "cn=" . $row["cn"][0];
846 $is_rename_success = @ldap_rename($_SESSION['ldap']->server(), $oldDN, $newRDN, $this->getAccountContainer()->dnSuffix, true);
847 if (!$is_rename_success) {
848 $errors[] = ['ERROR', sprintf(_('Was unable to rename DN: %s.'), $this->getAccountContainer()->dn_orig), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
849 logNewMessage(LOG_ERR, 'Unable to rename ' . $oldDN . ' to ' . $newRDN . ',' . $this->getAccountContainer()->dnSuffix);
850 }
851 }
852 return $errors;
853 }
854
855 /**
856 * {@inheritDoc}
857 */
858 public function save_attributes(): array {
859 $this->extensionRows = $this->array_sort($this->extensionRows, 'astpriority');
860
861 // modify existent config rows if necessary
862 for ($rowCounter = 0; $rowCounter < count($this->extensionRowsOrig); $rowCounter++) {
863 $rowOrig = $this->extensionRowsOrig[$rowCounter];
864 unset($rowOrig['dn']);
865 if ($rowCounter < count($this->extensionRows)) {
866 $row = $this->extensionRows[$rowCounter];
867 $attributeNames = array_values(array_unique(array_merge(array_keys($row), array_keys($rowOrig))));
868 $ldapChanges = [];
869 foreach ($attributeNames as $attributeName) {
870 if (isset($rowOrig[$attributeName]) && !isset($row[$attributeName])) {
871 $ldapChanges[$attributeName] = [];
872 }
873 elseif (!isset($rowOrig[$attributeName]) && isset($row[$attributeName])) {
874 $ldapChanges[$attributeName] = $row[$attributeName];
875 }
876 elseif ($rowOrig[$attributeName][0] != $row[$attributeName][0]) {
877 $ldapChanges[$attributeName] = $row[$attributeName][0];
878 }
879 }
880 if (!empty($ldapChanges)) {
881 if (!isset($ldapChanges['cn'])) {
882 ldap_mod_replace($_SESSION['ldap']->server(), "cn=" . $row["cn"][0] . "," . $this->getAccountContainer()->dnSuffix, $ldapChanges);
883 }
884 else {
885 $origDN = "cn=" . $rowOrig["cn"][0] . "," . extractDNSuffix($this->getAccountContainer()->dn_orig);
886 $newRDN = "cn=" . $row["cn"][0];
887 ldap_rename($_SESSION['ldap']->server(), $origDN, $newRDN, extractDNSuffix($this->getAccountContainer()->dn_orig), true);
888 unset($ldapChanges['cn']);
889 if (!empty($ldapChanges)) {
890 ldap_mod_replace($_SESSION['ldap']->server(), $newRDN . "," . extractDNSuffix($this->getAccountContainer()->dn_orig), $ldapChanges);
891 }
892 }
893 }
894 // if new suffix just move old rows to the new suffix and go on
895 $this->moveExtentionToNewSuffix($row);
896 }
897 else {
898 ldap_delete($_SESSION['ldap']->server(), "cn=" . $rowOrig["cn"][0] . "," . extractDNSuffix($this->getAccountContainer()->dn_orig));
899 }
900 }
901 // add new config rows
902 for ($rowCounter = count($this->extensionRowsOrig); $rowCounter < count($this->extensionRows); $rowCounter++) {
903 $row = $this->extensionRows[$rowCounter];
904 ldap_add($_SESSION['ldap']->server(), "cn=" . $row["cn"][0] . "," . $this->getAccountContainer()->dnSuffix, $row);
905 }
906
907 //a trick for Edit again to work
908 $this->getAccountContainer()->dn_orig = "cn=" . $this->extensionRows[0]['cn'][0] . "," . $this->getAccountContainer()->dnSuffix;
909 $this->getAccountContainer()->finalDN = "cn=" . $this->extensionRows[0]['cn'][0] . "," . $this->getAccountContainer()->dnSuffix;
910
911 return $this->getAccountContainer()->save_module_attributes($this->orig, $this->orig);
912 }
913
914 /**
915 * {@inheritDoc}
916 */
917 public function postDeleteActions(): array {
918 $extension = $this->attributes['AstExtension'][0];
919 $searchClass = "AsteriskExtension";
920 $searchScope = 'asteriskExt';
921 $entries = searchLDAPByAttribute("AstExtension", $extension, $searchClass, ['cn', 'AstContext', 'AstPriority',
922 'AstApplication', 'AstApplicationData', 'AstExtension', 'member', 'ObjectClass', 'dn'], [$searchScope]);
923 $entries = $this->array_sort($entries, 'astpriority');
924
925 for ($rowCounter = 0; $rowCounter < count($entries); $rowCounter++) {
926 $rowOrig = $entries[$rowCounter];
927 if ($rowOrig["astpriority"][0] > 1) {
928 ldap_delete($_SESSION['ldap']->server(), $rowOrig['dn']);
929 }
930 }
931 return [];
932 }
933
934 /**
935 * @inheritDoc
936 */
937 public function getListAttributeDescriptions(ConfiguredType $type): array {
938 return [
939 'astcontext' => _('Account context'),
940 'astextension' => _('Extension name'),
941 "member" => _("Owner"),
942 ];
943 }
944
945 }