This file is indexed.

/usr/share/otrs/Kernel/Modules/AgentCustomerUserAddressBook.pm is in otrs2 6.0.5-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
# --
# Copyright (C) 2001-2018 OTRS AG, http://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (AGPL). If you
# did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
# --

package Kernel::Modules::AgentCustomerUserAddressBook;

use strict;
use warnings;

use List::Util qw(first);

use Kernel::Language qw(Translatable);
use Kernel::System::VariableCheck qw(:all);

our $ObjectManagerDisabled = 1;

sub new {
    my ( $Type, %Param ) = @_;

    my $Self = {%Param};
    bless( $Self, $Type );

    # Define some customer company values, to use the values later for the output.
    $Self->{CustomerCompanySearchFieldPrefix} = 'CustomerCompany_';
    $Self->{CustomerCompanyLabelIdentifier}   = Translatable('Customer');

    return $Self;
}

sub Run {
    my ( $Self, %Param ) = @_;

    my $ConfigObject = $Kernel::OM->Get('Kernel::Config');
    my $ParamObject  = $Kernel::OM->Get('Kernel::System::Web::Request');
    my $LayoutObject = $Kernel::OM->Get('Kernel::Output::HTML::Layout');

    $Self->{RecipientType} = $ParamObject->GetParam( Param => 'RecipientType' ) || 'Email';

    $Self->{Config} = $ConfigObject->Get("CustomerUser::Frontend::$Self->{Action}");

    # Check if the config settings exsists for the given recipient type.
    for my $ConfigKey (qw(SearchParameters DefaultFields ShowColumns)) {
        if ( !grep { $_ eq $Self->{RecipientType} } sort keys %{ $Self->{Config}->{$ConfigKey} } ) {
            return $LayoutObject->ErrorScreen(
                Message => Translatable("No config setting '$ConfigKey' for the given RecipientType!"),
                Comment => Translatable('Please contact the administrator.'),
            );
        }
    }

    # Get the diffrent values from the params or the config to set the default values.
    $Self->{StartHit} = int( $ParamObject->GetParam( Param => 'StartHit' ) || 1 );
    $Self->{SearchLimit} = $Self->{Config}->{SearchParameters}->{ $Self->{RecipientType} }->{SearchLimit} || 500;
    $Self->{SortBy} = $ParamObject->GetParam( Param => 'SortBy' )
        || $Self->{Config}->{SearchParameters}->{ $Self->{RecipientType} }->{'SortBy::Default'}
        || 'UserLogin';
    $Self->{OrderBy} = $ParamObject->GetParam( Param => 'OrderBy' )
        || $Self->{Config}->{SearchParameters}->{ $Self->{RecipientType} }->{'Order::Default'}
        || 'Up';
    $Self->{Profile}             = $ParamObject->GetParam( Param => 'Profile' )             || '';
    $Self->{SaveProfile}         = $ParamObject->GetParam( Param => 'SaveProfile' )         || '';
    $Self->{TakeLastSearch}      = $ParamObject->GetParam( Param => 'TakeLastSearch' )      || '';
    $Self->{SelectTemplate}      = $ParamObject->GetParam( Param => 'SelectTemplate' )      || '';
    $Self->{EraseTemplate}       = $ParamObject->GetParam( Param => 'EraseTemplate' )       || '';
    $Self->{RecipientField}      = $ParamObject->GetParam( Param => 'RecipientField' );
    $Self->{RecipientFieldLabel} = $ParamObject->GetParam( Param => 'RecipientFieldLabel' ) || $Self->{RecipientField};

    if ( !$Self->{RecipientField} ) {
        return $LayoutObject->ErrorScreen(
            Message => Translatable('No RecipientField is given!'),
            Comment => Translatable('Please contact the administrator.'),
        );
    }

    if ( $ParamObject->GetParam( Param => 'SearchTemplate' ) && $Self->{Profile} ) {
        return $LayoutObject->Redirect(
            OP =>
                "Action=AgentCustomerUserAddressBook;Subaction=Search;TakeLastSearch=1;SaveProfile=1;Profile=$Self->{Profile}"
        );
    }

    my %GetParam;

    # Get the dynamic fields from the customer user and company search fields.
    my @CustomerUserDynamicFields = $Self->_GetCustomerUserSearchFields(
        Types => ['DynamicField'],
    );
    my @CustomerCompanyDynamicFields = $Self->_GetCustomerCompanySearchFields(
        Types         => ['DynamicField'],
        WithoutPrefix => 1,
    );

    my %LookupCustomerUserDynamicFields    = map { $_->{DatabaseField} => 1 } @CustomerUserDynamicFields;
    my %LookupCustomerCompanyDynamicFields = map { $_->{DatabaseField} => 1 } @CustomerCompanyDynamicFields;

    # Get the dynamic fields for this screen.
    $Self->{DynamicFieldCustomerUser} = $Kernel::OM->Get('Kernel::System::DynamicField')->DynamicFieldListGet(
        Valid       => 1,
        ObjectType  => [ 'CustomerUser', ],
        FieldFilter => \%LookupCustomerUserDynamicFields,
    );
    $Self->{DynamicFieldCustomerCompany} = $Kernel::OM->Get('Kernel::System::DynamicField')->DynamicFieldListGet(
        Valid       => 1,
        ObjectType  => [ 'CustomerCompany', ],
        FieldFilter => \%LookupCustomerCompanyDynamicFields,
    );

    my $DynamicFieldBackendObject = $Kernel::OM->Get('Kernel::System::DynamicField::Backend');
    my $SearchProfileObject       = $Kernel::OM->Get('Kernel::System::SearchProfile');

    # Get the diffrent search fields for the customer user search.
    my @CustomerUserInputSearchFields = $Self->_GetCustomerUserSearchFields(
        Types => ['Input'],
    );
    my @CustomerUserSelectionSearchFields = $Self->_GetCustomerUserSearchFields(
        Types => ['Selection'],
    );

    # Get the diffrent search fields for the customer company search.
    my @CustomerCompanyInputSearchFields = $Self->_GetCustomerCompanySearchFields(
        Types => ['Input'],
    );
    my @CustomerCompanySelectionSearchFields = $Self->_GetCustomerCompanySearchFields(
        Types => ['Selection'],
    );

    # Load parameters from search profile,
    # this happens when the next result page should be shown, or when the results are reordered.
    if ( ( $Self->{Subaction} eq 'LoadProfile' && $Self->{Profile} ) || $Self->{TakeLastSearch} ) {
        %GetParam = $SearchProfileObject->SearchProfileGet(
            Base      => 'CustomerUserAddressBook',
            Name      => $Self->{Profile},
            UserLogin => $Self->{UserLogin},
        );

        if ( $GetParam{ShownAttributes} && ref $GetParam{ShownAttributes} eq 'ARRAY' ) {
            $GetParam{ShownAttributes} = join ';', @{ $GetParam{ShownAttributes} };
        }

        # Use param ExcludeUserLogins only for the last-search profile (otherwise ignore the parameter).
        if ( $Self->{Profile} ne 'last-search' ) {
            delete $GetParam{ExcludeUserLogins};
        }
    }
    elsif ( $Self->{Subaction} eq 'DeleteProfile' ) {

        $SearchProfileObject->SearchProfileDelete(
            Base      => 'CustomerUserAddressBook',
            Name      => $Self->{Profile},
            UserLogin => $Self->{UserLogin},
        );
        $Self->{Profile} = '';
    }
    else {

        # Get some general search params.
        for my $ParamName (qw(ShownAttributes)) {
            $GetParam{$ParamName} = $ParamObject->GetParam( Param => $ParamName );
        }

        # Get the scalar search params for the customer user and customer company fields.
        for my $Field ( @CustomerUserInputSearchFields, @CustomerCompanyInputSearchFields ) {
            $GetParam{ $Field->{Name} } = $ParamObject->GetParam( Param => $Field->{Name} );

            # Remove the whitespace on the start and end of the given string.
            if ( $GetParam{ $Field->{Name} } ) {
                $GetParam{ $Field->{Name} } =~ s{ \A \s+ }{}xms;
                $GetParam{ $Field->{Name} } =~ s{ \s+ \z }{}xms;
            }
        }

        # Get the array search params for the customer user and customer company fields.
        for my $Field ( @CustomerUserSelectionSearchFields, @CustomerCompanySelectionSearchFields ) {
            my @Array = $ParamObject->GetArray( Param => $Field->{Name} );
            if (@Array) {
                $GetParam{ $Field->{Name} } = \@Array;
            }
        }

        # Get the excluded user logins, which were already selected in a recipient field.
        my $ExcludeUserLoginsJSONString = $ParamObject->GetParam( Param => 'ExcludeUserLoginsJSON' ) || '';

        if ($ExcludeUserLoginsJSONString) {
            $GetParam{ExcludeUserLogins} = $Kernel::OM->Get('Kernel::System::JSON')->Decode(
                Data => $ExcludeUserLoginsJSONString,
            );
        }

        # Get Dynamic fields from param object and cycle trough the activated Dynamic Fields for this screen.
        DYNAMICFIELD:
        for my $DynamicFieldConfig ( @{ $Self->{DynamicFieldCustomerUser} }, @{ $Self->{DynamicFieldCustomerCompany} } )
        {
            next DYNAMICFIELD if !IsHashRefWithData($DynamicFieldConfig);

            my $SearchFieldPreferences = $DynamicFieldBackendObject->SearchFieldPreferences(
                DynamicFieldConfig => $DynamicFieldConfig,
            );

            next DYNAMICFIELD if !IsArrayRefWithData($SearchFieldPreferences);

            PREFERENCE:
            for my $Preference ( @{$SearchFieldPreferences} ) {

                # Extract the dynamic field value from the web request.
                my $DynamicFieldValue = $DynamicFieldBackendObject->SearchFieldValueGet(
                    DynamicFieldConfig     => $DynamicFieldConfig,
                    ParamObject            => $ParamObject,
                    ReturnProfileStructure => 1,
                    LayoutObject           => $LayoutObject,
                    Type                   => $Preference->{Type},
                );

                # Set the complete value structure in GetParam to store it later in the search profile.
                if ( IsHashRefWithData($DynamicFieldValue) ) {
                    %GetParam = ( %GetParam, %{$DynamicFieldValue} );
                }
            }
        }
    }

    # Show result site or perform other actions.
    if ( $Self->{Subaction} eq 'Search' && !$Self->{EraseTemplate} ) {

        # Generate a lookup hash for the exluce user logins and delete the entry from the 'GetParam', because
        #   we disable the entries in the result.
        my %LookupExcludeUserLogins;
        if ( IsArrayRefWithData( $GetParam{ExcludeUserLogins} ) ) {
            %LookupExcludeUserLogins = map { $_ => 1 } @{ $GetParam{ExcludeUserLogins} };
            delete $GetParam{ExcludeUserLogins};
        }

        # Fill up profile name (e.g. with last-search).
        if ( !$Self->{Profile} || !$Self->{SaveProfile} ) {
            $Self->{Profile} = 'last-search';
        }

        # Save search profile (under last-search or real profile name).
        $Self->{SaveProfile} = 1;

        # Remember the last search values, e.g. for sorting.
        if ( $Self->{SaveProfile} && $Self->{Profile} ) {

            # Remove old profile stuff, before the new stuff will be saved.
            $SearchProfileObject->SearchProfileDelete(
                Base      => 'CustomerUserAddressBook',
                Name      => $Self->{Profile},
                UserLogin => $Self->{UserLogin},
            );

            if ( $GetParam{ShownAttributes} && ref $GetParam{ShownAttributes} eq '' ) {
                $GetParam{ShownAttributes} = [ split /;/, $GetParam{ShownAttributes} ];
            }

            KEY:
            for my $Key ( sort keys %GetParam ) {
                next KEY if !defined $GetParam{$Key};

                $SearchProfileObject->SearchProfileAdd(
                    Base      => 'CustomerUserAddressBook',
                    Name      => $Self->{Profile},
                    Key       => $Key,
                    Value     => $GetParam{$Key},
                    UserLogin => $Self->{UserLogin},
                );
            }
        }

        my %AttributeLookup;

        for my $Attribute ( @{ $GetParam{ShownAttributes} || [] } ) {
            $AttributeLookup{$Attribute} = 1;
        }

        my %DynamicFieldSearchParameters;

        DYNAMICFIELD:
        for my $DynamicFieldConfig ( @{ $Self->{DynamicFieldCustomerUser} }, @{ $Self->{DynamicFieldCustomerCompany} } )
        {
            next DYNAMICFIELD if !IsHashRefWithData($DynamicFieldConfig);

            my $SearchFieldPreferences = $DynamicFieldBackendObject->SearchFieldPreferences(
                DynamicFieldConfig => $DynamicFieldConfig,
            );

            next DYNAMICFIELD if !IsArrayRefWithData($SearchFieldPreferences);

            PREFERENCE:
            for my $Preference ( @{$SearchFieldPreferences} ) {

                if (
                    !$AttributeLookup{ 'LabelSearch_DynamicField_' . $DynamicFieldConfig->{Name} . $Preference->{Type} }
                    )
                {
                    next PREFERENCE;
                }

                # Extract the dynamic field value from the profile.
                my $SearchParameter = $DynamicFieldBackendObject->SearchFieldParameterBuild(
                    DynamicFieldConfig => $DynamicFieldConfig,
                    Profile            => \%GetParam,
                    LayoutObject       => $LayoutObject,
                    Type               => $Preference->{Type},
                );

                if ( defined $SearchParameter ) {
                    $DynamicFieldSearchParameters{ 'DynamicField_' . $DynamicFieldConfig->{Name} }
                        = $SearchParameter->{Parameter};
                }
            }
        }

        # Get only the customer company search params.
        my %CustomerCompanyGetParam;

        CUSTOMERCOMPANYFIELD:
        for my $CustomerCompanyField ( @CustomerCompanySelectionSearchFields, @CustomerCompanyInputSearchFields ) {

            next CUSTOMERCOMPANYFIELD if !$GetParam{ $CustomerCompanyField->{Name} };

            # Get the real field name.
            my $RealFieldName = $CustomerCompanyField->{Name};
            $RealFieldName =~ s{ \A $Self->{CustomerCompanySearchFieldPrefix} }{}xms;

            $CustomerCompanyGetParam{$RealFieldName} = $GetParam{ $CustomerCompanyField->{Name} };
        }

        # Check if a dynamic field search param exists.
        my $CustomerCompanyDynamicFieldExists;

        CUSTOMERCOMPANYDYNAMICFIELD:
        for my $CustomerCompanyDynamicField (@CustomerCompanyDynamicFields) {
            next CUSTOMERCOMPANYDYNAMICFIELD if !$DynamicFieldSearchParameters{ $CustomerCompanyDynamicField->{Name} };

            $CustomerCompanyDynamicFieldExists = 1;

            last CUSTOMERCOMPANYDYNAMICFIELD;
        }

        my $CustomerCompanyIDs;

        # Search first for customer companies, if some customer company search params exists.
        if ( %CustomerCompanyGetParam || $CustomerCompanyDynamicFieldExists ) {

            $CustomerCompanyIDs = $Kernel::OM->Get('Kernel::System::CustomerCompany')->CustomerCompanySearchDetail(
                Result => 'ARRAY',
                %CustomerCompanyGetParam,
                %DynamicFieldSearchParameters,
            ) || [];
        }

        my $CustomerUserObject = $Kernel::OM->Get('Kernel::System::CustomerUser');

        my $ViewableCustomerUserLogins = [];

        # Do the search only if no customer company get params are given or some customer company ids for the given
        # customer company search params were found.
        if (
            ( !%CustomerCompanyGetParam && !$CustomerCompanyDynamicFieldExists )
            || IsArrayRefWithData($CustomerCompanyIDs)
            )
        {

            $ViewableCustomerUserLogins = $CustomerUserObject->CustomerSearchDetail(
                Result                           => 'ARRAY',
                OrderBy                          => [ $Self->{SortBy} ],
                OrderByDirection                 => [ $Self->{OrderBy} ],
                Limit                            => $Self->{SearchLimit},
                CustomerCompanySearchCustomerIDs => $CustomerCompanyIDs,
                %GetParam,
                %DynamicFieldSearchParameters,
            ) || [];
        }

        if ( $Self->{RecipientSelectionAJAX} ) {

            my @CustomerUserLoginList;

            if ( IsArrayRefWithData($ViewableCustomerUserLogins) ) {

                CUSTOMERUSERLOGIN:
                for my $CustomerUserLogin ( @{$ViewableCustomerUserLogins} ) {

                    my %CustomerUser = $CustomerUserObject->CustomerUserDataGet(
                        User => $CustomerUserLogin,
                    );

                    push @CustomerUserLoginList, {
                        UserLogin      => $CustomerUser{UserLogin},
                        UserMailString => $CustomerUser{UserMailString},
                    };
                }
            }

            my $Output = $LayoutObject->JSONEncode(
                Data => \@CustomerUserLoginList,
            );
            return $LayoutObject->Attachment(
                NoCache     => 1,
                ContentType => 'text/html',
                Content     => $Output,
                Type        => 'inline'
            );
        }
        else {

            my $Output = $LayoutObject->Header(
                Type => 'Small',
            );
            $LayoutObject->Print( Output => \$Output );
            $Output = '';

            $Self->{Filter} = $ParamObject->GetParam( Param => 'Filter' ) || '';
            $Self->{View}   = $ParamObject->GetParam( Param => 'View' )   || '';

            my $LinkPage = 'RecipientField=' . $Self->{RecipientField}
                . ';RecipientFieldLabel=' . $Self->{RecipientFieldLabel}
                . ';RecipientType=' . $Self->{RecipientType}
                . ';Filter=' . $LayoutObject->Ascii2Html( Text => $Self->{Filter} )
                . ';View=' . $LayoutObject->Ascii2Html( Text => $Self->{View} )
                . ';SortBy=' . $LayoutObject->Ascii2Html( Text => $Self->{SortBy} )
                . ';OrderBy=' . $LayoutObject->Ascii2Html( Text => $Self->{OrderBy} )
                . ';Profile=' . $Self->{Profile}
                . ';TakeLastSearch=1;Subaction=Search'
                . ';';
            my $LinkSort = 'RecipientField=' . $Self->{RecipientField}
                . ';RecipientFieldLabel=' . $Self->{RecipientFieldLabel}
                . ';RecipientType=' . $Self->{RecipientType}
                . ';Filter=' . $LayoutObject->Ascii2Html( Text => $Self->{Filter} )
                . ';View=' . $LayoutObject->Ascii2Html( Text => $Self->{View} )
                . ';Profile=' . $Self->{Profile}
                . ';TakeLastSearch=1;Subaction=Search'
                . ';';
            my $LinkFilter = 'RecipientField=' . $Self->{RecipientField}
                . ';RecipientFieldLabel=' . $Self->{RecipientFieldLabel}
                . ';RecipientType=' . $Self->{RecipientType}
                . ';Profile=' . $LayoutObject->Ascii2Html( Text => $Self->{Profile} )
                . ';TakeLastSearch=1;Subaction=Search'
                . ';';
            my $LinkBack = 'RecipientField=' . $Self->{RecipientField}
                . ';RecipientFieldLabel=' . $Self->{RecipientFieldLabel}
                . ';RecipientType=' . $Self->{RecipientType}
                . ';Profile=' . $LayoutObject->Ascii2Html( Text => $Self->{Profile} )
                . ';TakeLastSearch=1;Subaction=LoadProfile'
                . ';';

            # Find out which columns should be shown.
            my @ShowColumns;
            if ( IsArrayRefWithData( $Self->{Config}->{ShowColumns}->{ $Self->{RecipientType} } ) ) {
                @ShowColumns = @{ $Self->{Config}->{ShowColumns}->{ $Self->{RecipientType} } };
            }

            # Get the already selected recipients, to remember the selected recipients for the diffrent pages.
            my $RecipientsJSONString = $ParamObject->GetParam( Param => 'RecipientsJSON' ) || '';

            my $Recipients;
            if ($RecipientsJSONString) {
                $Recipients = $Kernel::OM->Get('Kernel::System::JSON')->Decode(
                    Data => $RecipientsJSONString,
                );
            }

            $Output .= $LayoutObject->CustomerUserAddressBookListShow(
                CustomerUserIDs     => $ViewableCustomerUserLogins,
                Total               => scalar @{$ViewableCustomerUserLogins},
                View                => $Self->{View},
                Env                 => $Self,
                LinkPage            => $LinkPage,
                LinkSort            => $LinkSort,
                LinkFilter          => $LinkFilter,
                LinkBack            => $LinkBack,
                Profile             => $Self->{Profile},
                TitleName           => Translatable('Customer User Address Book'),
                ShowColumns         => \@ShowColumns,
                SortBy              => $LayoutObject->Ascii2Html( Text => $Self->{SortBy} ),
                OrderBy             => $LayoutObject->Ascii2Html( Text => $Self->{OrderBy} ),
                RequestedURL        => 'Action=' . $Self->{Action} . ';' . $LinkPage,
                Recipients          => $Recipients || {},
                RecipientType       => $Self->{RecipientType},
                RecipientField      => $Self->{RecipientField},
                RecipientFieldLabel => $Self->{RecipientFieldLabel},
                CustomerTicketTextField =>
                    $Self->{Config}->{SearchParameters}->{ $Self->{RecipientType} }->{CustomerTicketTextField}
                    || 'UserMailString',
                LookupExcludeUserLogins => \%LookupExcludeUserLogins,
            );

            $Output .= $LayoutObject->Footer(
                Type => 'Small',
            );

            return $Output;
        }
    }

    # There was no 'SubAction', or there were validation errors, or an user or customer was searched
    #   generate search mask.
    my $Output = $LayoutObject->Header(
        Type => 'Small',
    );

    $Output .= $Self->_MaskForm(
        RecipientType       => $Self->{RecipientType},
        RecipientField      => $Self->{RecipientField},
        RecipientFieldLabel => $Self->{RecipientFieldLabel},
        %GetParam,
    );

    $Output .= $LayoutObject->Footer(
        Type => 'Small',
    );

    return $Output;
}

sub _MaskForm {
    my ( $Self, %Param ) = @_;

    my $LayoutObject = $Kernel::OM->Get('Kernel::Output::HTML::Layout');
    my $ParamObject  = $Kernel::OM->Get('Kernel::System::Web::Request');

    my $EmptySearch = $ParamObject->GetParam( Param => 'EmptySearch' );
    if ( !$Self->{Profile} ) {
        $EmptySearch = 1;
    }

    my $SearchProfileObject = $Kernel::OM->Get('Kernel::System::SearchProfile');

    my %GetParam = $SearchProfileObject->SearchProfileGet(
        Base      => 'CustomerUserAddressBook',
        Name      => $Self->{Profile},
        UserLogin => $Self->{UserLogin},
    );

    # Allow profile overwrite the contents of %Param.
    %Param = (
        %Param,
        %GetParam,
    );

    # Get the search fields for the customer user search.
    my @CustomerUserSearchFields = $Self->_GetCustomerUserSearchFields(
        Types => [ 'Input', 'Selection' ],
    );

    # Get the search fields for the customer user search.
    my @CustomerCompanySearchFields = $Self->_GetCustomerCompanySearchFields(
        Types => [ 'Input', 'Selection' ],
    );

    # Translate the customer company label identifier to add this to the labels.
    my $TranslatedCustomerCompanyLabelIdentifier
        = $LayoutObject->{LanguageObject}->Translate( $Self->{CustomerCompanyLabelIdentifier} );

    my @Attributes;

    for my $Field (@CustomerUserSearchFields) {

        push @Attributes, {
            Key   => $Field->{Name},
            Value => $Field->{Label},
        };
    }

    my $DynamicFieldBackendObject = $Kernel::OM->Get('Kernel::System::DynamicField::Backend');

    if ( IsArrayRefWithData( $Self->{DynamicFieldCustomerUser} ) ) {

        # Create dynamic fields search options for attribute select
        #   cycle trough the activated Dynamic Fields for this screen.
        DYNAMICFIELD:
        for my $DynamicFieldConfig ( @{ $Self->{DynamicFieldCustomerUser} } ) {
            next DYNAMICFIELD if !IsHashRefWithData($DynamicFieldConfig);
            next DYNAMICFIELD if !$DynamicFieldConfig->{Name};
            next DYNAMICFIELD if $DynamicFieldConfig->{Name} eq '';

            my $SearchFieldPreferences = $DynamicFieldBackendObject->SearchFieldPreferences(
                DynamicFieldConfig => $DynamicFieldConfig,
            );

            next DYNAMICFIELD if !IsArrayRefWithData($SearchFieldPreferences);

            my $TranslatedDynamicFieldLabel = $LayoutObject->{LanguageObject}->Translate(
                $DynamicFieldConfig->{Label},
            );

            PREFERENCE:
            for my $Preference ( @{$SearchFieldPreferences} ) {

                my $TranslatedSuffix = $LayoutObject->{LanguageObject}->Translate(
                    $Preference->{LabelSuffix},
                ) || '';

                if ($TranslatedSuffix) {
                    $TranslatedSuffix = ' (' . $TranslatedSuffix . ')';
                }

                push @Attributes, (
                    {
                        Key   => 'Search_DynamicField_' . $DynamicFieldConfig->{Name} . $Preference->{Type},
                        Value => $TranslatedDynamicFieldLabel . $TranslatedSuffix,
                    },
                );
            }
        }
    }

    if (@CustomerCompanySearchFields) {

        push @Attributes, {
            Key      => '',
            Value    => '-',
            Disabled => 1,
        };

        for my $Field (@CustomerCompanySearchFields) {

            my $TranslatedFieldLabel = $LayoutObject->{LanguageObject}->Translate(
                $Field->{Label},
            );

            if (
                $TranslatedCustomerCompanyLabelIdentifier
                && $TranslatedFieldLabel ne $TranslatedCustomerCompanyLabelIdentifier
                )
            {
                $TranslatedFieldLabel .= " ($TranslatedCustomerCompanyLabelIdentifier)";
            }

            push @Attributes, {
                Key   => $Field->{Name},
                Value => $TranslatedFieldLabel,
            };
        }
    }

    if ( IsArrayRefWithData( $Self->{DynamicFieldCustomerCompany} ) ) {

        # Create dynamic fields search options for attribute select
        #   cycle trough the activated Dynamic Fields for this screen.
        DYNAMICFIELD:
        for my $DynamicFieldConfig ( @{ $Self->{DynamicFieldCustomerCompany} } ) {
            next DYNAMICFIELD if !IsHashRefWithData($DynamicFieldConfig);
            next DYNAMICFIELD if !$DynamicFieldConfig->{Name};
            next DYNAMICFIELD if $DynamicFieldConfig->{Name} eq '';

            my $SearchFieldPreferences = $DynamicFieldBackendObject->SearchFieldPreferences(
                DynamicFieldConfig => $DynamicFieldConfig,
            );

            next DYNAMICFIELD if !IsArrayRefWithData($SearchFieldPreferences);

            my $TranslatedDynamicFieldLabel = $LayoutObject->{LanguageObject}->Translate(
                $DynamicFieldConfig->{Label},
            );

            PREFERENCE:
            for my $Preference ( @{$SearchFieldPreferences} ) {

                my $TranslatedSuffix = $LayoutObject->{LanguageObject}->Translate(
                    $Preference->{LabelSuffix},
                ) || '';

                if ($TranslatedSuffix) {
                    $TranslatedSuffix = ' (' . $TranslatedSuffix . ')';
                }

                my $DynamicFieldLabel = $TranslatedDynamicFieldLabel . $TranslatedSuffix;

                if (
                    $TranslatedCustomerCompanyLabelIdentifier
                    && $TranslatedDynamicFieldLabel ne $TranslatedCustomerCompanyLabelIdentifier
                    )
                {
                    $DynamicFieldLabel
                        .= ( $TranslatedSuffix ? " - " : " " ) . "($TranslatedCustomerCompanyLabelIdentifier)";
                }

                push @Attributes, (
                    {
                        Key   => 'Search_DynamicField_' . $DynamicFieldConfig->{Name} . $Preference->{Type},
                        Value => $DynamicFieldLabel,
                    },
                );
            }
        }
    }

    # Create HTML strings for all dynamic fields.
    my %DynamicFieldHTML;

    # Cycle trough the activated Dynamic Fields for this screen.
    DYNAMICFIELD:
    for my $DynamicFieldConfig ( @{ $Self->{DynamicFieldCustomerUser} }, @{ $Self->{DynamicFieldCustomerCompany} } ) {
        next DYNAMICFIELD if !IsHashRefWithData($DynamicFieldConfig);

        my $SearchFieldPreferences = $DynamicFieldBackendObject->SearchFieldPreferences(
            DynamicFieldConfig => $DynamicFieldConfig,
        );

        next DYNAMICFIELD if !IsArrayRefWithData($SearchFieldPreferences);

        my $PossibleValues = $DynamicFieldBackendObject->PossibleValuesGet(
            DynamicFieldConfig   => $DynamicFieldConfig,
            OverridePossibleNone => 0,
        );

        PREFERENCE:
        for my $Preference ( @{$SearchFieldPreferences} ) {

            $DynamicFieldHTML{ $DynamicFieldConfig->{Name} . $Preference->{Type} }
                = $DynamicFieldBackendObject->SearchFieldRender(
                DynamicFieldConfig   => $DynamicFieldConfig,
                Profile              => \%GetParam,
                PossibleValuesFilter => $PossibleValues,
                LayoutObject         => $LayoutObject,
                Type                 => $Preference->{Type},
                );
        }
    }

    $Param{AttributesStrg} = $LayoutObject->BuildSelection(
        Data     => \@Attributes,
        Name     => 'Attribute',
        Multiple => 0,
        Class    => 'Modernize',
    );
    $Param{AttributesOrigStrg} = $LayoutObject->BuildSelection(
        Data     => \@Attributes,
        Name     => 'AttributeOrig',
        Multiple => 0,
        Class    => 'Modernize',
    );

    my @OutputSearchFields;

    # Build the output for the input search fields.
    for my $Field (@CustomerUserSearchFields) {

        my %FieldData = (
            CustomerUserField => 1,
            Name              => $Field->{Name},
            Label             => $Field->{Label},
        );

        if ( $Field->{Type} eq 'Selection' ) {

            my $SelectionString = $LayoutObject->BuildSelection(
                Data        => $Field->{SelectionsData},
                Name        => $Field->{Name},
                Translation => 1,
                Multiple    => 1,
                Size        => 5,
                SelectedID  => $Param{ $Field->{Name} },
                Class       => 'Modernize',
            );
            $FieldData{SelectionString} = $SelectionString;
        }
        else {
            $FieldData{Value} = $Param{ $Field->{Name} };
        }

        push @OutputSearchFields, \%FieldData;
    }

    # Build the output for the input search fields.
    for my $Field (@CustomerCompanySearchFields) {

        my $TranslatedFieldLabel = $LayoutObject->{LanguageObject}->Translate(
            $Field->{Label},
        );

        if (
            $TranslatedCustomerCompanyLabelIdentifier
            && $TranslatedFieldLabel ne $TranslatedCustomerCompanyLabelIdentifier
            )
        {
            $TranslatedFieldLabel .= " ($TranslatedCustomerCompanyLabelIdentifier)";
        }

        my %FieldData = (
            CustomerCompanyField => 1,
            Name                 => $Field->{Name},
            Label                => $TranslatedFieldLabel,
        );

        if ( $Field->{Type} eq 'Selection' ) {

            my $SelectionString = $LayoutObject->BuildSelection(
                Data        => $Field->{SelectionsData},
                Name        => $Field->{Name},
                Translation => 1,
                Multiple    => 1,
                Size        => 5,
                SelectedID  => $Param{ $Field->{Name} },
                Class       => 'Modernize',
            );
            $FieldData{SelectionString} = $SelectionString;
        }
        else {
            $FieldData{Value} = $Param{ $Field->{Name} };
        }

        push @OutputSearchFields, \%FieldData;
    }

    $Param{OutputSearchFields} = \@OutputSearchFields;

    my %Profiles = $SearchProfileObject->SearchProfileList(
        Base      => 'CustomerUserAddressBook',
        UserLogin => $Self->{UserLogin},
    );
    delete $Profiles{''};
    delete $Profiles{'last-search'};
    if ($EmptySearch) {
        $Profiles{''} = '-';
    }
    else {
        $Profiles{'last-search'} = '-';
    }
    $Param{ProfilesStrg} = $LayoutObject->BuildSelection(
        Data       => \%Profiles,
        Name       => 'Profile',
        ID         => 'SearchProfile',
        SelectedID => $Self->{Profile},
        Class      => 'Modernize',

        # Do not modernize this field as this causes problems with the automatic focussing of the first element.
    );

    # Output the dynamic fields blocks, cycle trough the activated Dynamic Fields for this screen.
    DYNAMICFIELD:
    for my $DynamicFieldConfig ( @{ $Self->{DynamicFieldCustomerUser} }, @{ $Self->{DynamicFieldCustomerCompany} } ) {
        next DYNAMICFIELD if !IsHashRefWithData($DynamicFieldConfig);

        my $SearchFieldPreferences = $DynamicFieldBackendObject->SearchFieldPreferences(
            DynamicFieldConfig => $DynamicFieldConfig,
        );

        next DYNAMICFIELD if !IsArrayRefWithData($SearchFieldPreferences);

        PREFERENCE:
        for my $Preference ( @{$SearchFieldPreferences} ) {

            # Skip fields that HTML could not be retrieved.
            next PREFERENCE if !IsHashRefWithData(
                $DynamicFieldHTML{ $DynamicFieldConfig->{Name} . $Preference->{Type} }
            );

            my $DynamicFieldLabel = $DynamicFieldHTML{ $DynamicFieldConfig->{Name} . $Preference->{Type} }->{Label};

            # Add a identifier for the object type 'CustomerCompany' and if a identifier exists.
            if ( $DynamicFieldConfig->{ObjectType} eq 'CustomerCompany' && $TranslatedCustomerCompanyLabelIdentifier ) {
                my $LabelCustomerCompanyLabelIdentifier
                    = ( $Preference->{LabelSuffix} ? " - " : " " ) . "($TranslatedCustomerCompanyLabelIdentifier)";
                $DynamicFieldLabel =~ s{(<label.*>)(.*)(</label>)}{$1$2$LabelCustomerCompanyLabelIdentifier$3}xmsg;
            }

            $LayoutObject->Block(
                Name => 'DynamicField',
                Data => {
                    Label => $DynamicFieldLabel,
                    Field => $DynamicFieldHTML{ $DynamicFieldConfig->{Name} . $Preference->{Type} }->{Field},
                },
            );
        }
    }

    my @SearchAttributes;

    if ( $Self->{Profile} ) {

        my %AlreadyShown;

        ITEM:
        for my $Item (@Attributes) {
            my $Key = $Item->{Key};
            next ITEM if !$Key;
            next ITEM if !defined $Param{$Key};
            next ITEM if $AlreadyShown{$Key};

            if ( ref $Param{$Key} eq 'ARRAY' && !@{ $Param{$Key} } ) {
                next ITEM;
            }

            $AlreadyShown{$Key} = 1;

            push @SearchAttributes, $Key;
        }
    }

    # No profile, then show default screen.
    else {

        my %LookupDefaultFields = map { $_ => 1 } @{ $Self->{Config}->{DefaultFields}->{ $Self->{RecipientType} } };

        ITEM:
        for my $Item (@Attributes) {
            my $Key = $Item->{Key};

            next ITEM if !$LookupDefaultFields{$Key};

            push @SearchAttributes, $Key;
        }
    }

    $LayoutObject->AddJSData(
        Key   => 'ShowSearchDialog',
        Value => 1,
    );

    $LayoutObject->AddJSData(
        Key   => 'SearchAttributes',
        Value => \@SearchAttributes,
    );

    # build output
    my $Output = $LayoutObject->Output(
        TemplateFile => 'AgentCustomerUserAddressBook',
        Data         => {
            %Param,
            ShowSearchDialog => 1,
        },
    );

    return $Output;
}

=head2 _GetCustomerUserSearchFields()

Get the search fields from the customer user map config for the given types (otherwise all search fields).

    my @SearchFields = $AgentCustomerUserAddressBookObject->_GetCustomerUserSearchFields(
        Types => ['Input', 'Selection', 'DynamicField'], # optional
    );

=cut

sub _GetCustomerUserSearchFields {
    my ( $Self, %Param ) = @_;

    my @AllSearchFields = $Kernel::OM->Get('Kernel::System::CustomerUser')->CustomerUserSearchFields();

    return @AllSearchFields if !IsArrayRefWithData( $Param{Types} ) || !@AllSearchFields;

    my @SearchFields;

    TYPE:
    for my $Type ( @{ $Param{Types} } ) {

        my @TypeSearchFields = grep { $Type eq $_->{Type} } @AllSearchFields;

        next TYPE if !@TypeSearchFields;

        @SearchFields = ( @SearchFields, @TypeSearchFields );
    }
    return @SearchFields;
}

=head2 _GetCustomerCompanySearchFields()

Get the search fields from the customer user map config for the given type (otherwise all search fields)
with a special prefix.

    my @SearchFields = $AgentCustomerUserAddressBookObject->_GetCustomerCompanySearchFields(
        Types         => ['Input', 'Selection', 'DynamicField'], # optional
        WithoutPrefix => 1, # optional
    );

=cut

sub _GetCustomerCompanySearchFields {
    my ( $Self, %Param ) = @_;

    my @AllSearchFields = $Kernel::OM->Get('Kernel::System::CustomerCompany')->CustomerCompanySearchFields();

    # add a prefix for the customer company fields
    if ( !$Param{WithoutPrefix} ) {
        for my $Field (@AllSearchFields) {
            $Field->{Name} = $Self->{CustomerCompanySearchFieldPrefix} . $Field->{Name};
        }
    }

    return @AllSearchFields if !IsArrayRefWithData( $Param{Types} ) || !@AllSearchFields;

    my @SearchFields;

    TYPE:
    for my $Type ( @{ $Param{Types} } ) {

        my @TypeSearchFields = grep { $Type eq $_->{Type} } @AllSearchFields;

        next TYPE if !@TypeSearchFields;

        @SearchFields = ( @SearchFields, @TypeSearchFields );
    }
    return @SearchFields;
}

1;