This file is indexed.

/usr/share/otrs/scripts/DBUpdateTo6/MigrateChatData.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
# --
# 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 scripts::DBUpdateTo6::MigrateChatData;    ## no critic

use strict;
use warnings;

use parent qw(scripts::DBUpdateTo6::Base);

our @ObjectDependencies = (
    'Kernel::System::DB',
    'Kernel::System::Log',
    'Kernel::System::JSON',
    'Kernel::System::YAML',
);

=head1 NAME

scripts::DBUpdateTo6::MigrateChatData -  Migrate Chat data.

=cut

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

    my $DBObject = $Kernel::OM->Get('Kernel::System::DB');
    my $Verbose = $Param{CommandlineOptions}->{Verbose} || 0;

    my $TableExists = $Self->TableExists(
        Table => 'article_data_otrs_chat',
    );

    return 1 if !$TableExists;

    return if !$DBObject->Prepare(
        SQL => 'SELECT id, name FROM communication_channel',
    );

    # Look for the chat channel id
    my $ChatChannelID;
    while ( my @Row = $DBObject->FetchrowArray() ) {
        if ( $Row[1] =~ /chat/i ) {
            $ChatChannelID = $Row[0];
        }
    }

    return 1 if !$ChatChannelID;

    # verify if chat articles exist.
    my $CheckChatArticles = $Self->_CheckChatArticles(
        ChatChannelID => $ChatChannelID,
    );

    return 1 if !$CheckChatArticles;

    my $ArticleChatCount = 0;
    my $ChatCount        = 0;

    # Get amount of article entries
    $DBObject->Prepare(
        SQL  => "SELECT COUNT(*) FROM article WHERE communication_channel_id = ? ",
        Bind => [ \$ChatChannelID ]
    );
    while ( my @Row = $DBObject->FetchrowArray() ) {
        $ArticleChatCount = $Row[0] || 0;
    }

    # Get amount of article entries
    $DBObject->Prepare(
        SQL => "SELECT COUNT(*) FROM article_data_otrs_chat",
    );
    while ( my @Row = $DBObject->FetchrowArray() ) {
        $ChatCount = $Row[0] || 0;
    }

    # Chat info should be present in chat channel table
    # not in article table
    if ( $ChatCount && !$ArticleChatCount ) {
        print "    Chat data migration already executed.\n" if $Verbose;
    }

    my $ArticleChatMin = 0;

    # Get amount of article entries
    $DBObject->Prepare(
        SQL  => "SELECT MIN(id) FROM article WHERE communication_channel_id = ? ",
        Bind => [ \$ChatChannelID ]
    );
    while ( my @Row = $DBObject->FetchrowArray() ) {
        $ArticleChatMin = $Row[0] || 0;
    }

    my $ArticleChatMax = 0;

    # Get amount of article entries
    $DBObject->Prepare(
        SQL  => "SELECT MAX(id) FROM article WHERE communication_channel_id = ? ",
        Bind => [ \$ChatChannelID ]
    );
    while ( my @Row = $DBObject->FetchrowArray() ) {
        $ArticleChatMax = $Row[0] || 0;
    }

    # TODO:OCBI: This number might be changed or even configurable
    my $RowsPerLoop = 1000;

    my $StartInEntry = $ArticleChatMin - 1 || 0;

    my $JSONObject = $Kernel::OM->Get('Kernel::System::JSON');

    ENTRIES:
    while ( $StartInEntry < $ArticleChatMax ) {

        # Get the complete set of Article entries.
        my $EndInEntry = $StartInEntry + 1 + $RowsPerLoop;

        return if !$DBObject->Prepare(
            SQL => '
                SELECT adm.id, adm.article_id, adm.a_body,
                    adm.create_by, adm.create_time, adm.change_by, adm.change_time
                FROM article art, article_data_mime adm
                WHERE
                    art.id = adm.article_id
                    AND art.communication_channel_id = ?
                    AND adm.id > ' . $StartInEntry . ' AND adm.id < ' . $EndInEntry . '
                ORDER BY id ASC',
            Bind => [ \$ChatChannelID ],
        );

        my @Data;
        while ( my @Row = $DBObject->FetchrowArray() ) {
            my $ArticleJSONData = $JSONObject->Decode(
                Data => $Row[2],
            );

            for my $ArticleJSON ( @{$ArticleJSONData} ) {

                my %CurrentRow = (
                    ID                  => $ArticleJSON->{ID},
                    ArticleID           => $Row[1],
                    ChatParticipantID   => $ArticleJSON->{ChatterID},
                    ChatParticipantName => $ArticleJSON->{ChatterName},
                    ChatParticipantType => $ArticleJSON->{ChatterType},
                    MessageText         => $ArticleJSON->{MessageText},
                    SystemGenerated     => $ArticleJSON->{SystemGenerated},
                    CreateTime          => $Row[4],
                );
                push @Data, \%CurrentRow;
            }
        }

        if (@Data) {
            my $MigrationResult = $Self->_MigrateData(
                Data              => \@Data,
                LastArticleDataID => $Data[-1]->{ID},
            );

            if ( !$MigrationResult ) {
                $Kernel::OM->Get('Kernel::System::Log')->Log(
                    Priority => 'error',
                    Message  => "An error occurs during chat data migration!",
                );
                print "\n    An error occurs during chat data migration!\n";
                return;
            }
        }

        $StartInEntry += $RowsPerLoop;
    }

    # Delete old chat articles.
    my $DeleteResult = $Self->_DeleteOldChatArticles(
        ChatChannelID => $ChatChannelID,
    );

    if ( !$DeleteResult ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "An error occurs during article chat data cleanup!",
        );
        print "\n    An error occurs during article chat data cleanup!\n";
        return;
    }

    return 1;
}

=head2 _MigrateData()

Adds multiple article entries to the article table. Returns 1 on success

    my $Result = $DBUpdateTo6Object->_MigrateData(
        Data => \@OldArticleData, # Old structure content
    );

=cut

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

    # Check needed stuff.
    if ( !$Param{Data} ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "Need Data!",
        );
        return;
    }

    # Check needed stuff.
    if ( ref $Param{Data} ne 'ARRAY' ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "Data must be an array reference!",
        );
        return;
    }

    # Check needed stuff.
    if ( !@{ $Param{Data} } ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "Data array must not be empty!",
        );
        return;
    }

    # Check needed stuff.
    if ( !defined $Param{LastArticleDataID} ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "Need LastArticleDataID!",
        );
        return;
    }

    my $DBObject = $Kernel::OM->Get('Kernel::System::DB');

    # Get the database type.
    my $DBType = $DBObject->GetDatabaseFunction('Type');

    # Decide data migration type.
    my $AllowMultiple          = 1;
    my @SupportMultipleInserts = qw(mysql oracle postgresql);

    if ( !grep {m/$DBType/} @SupportMultipleInserts ) {
        $AllowMultiple = 0;
    }

    # Define database specific SQL for the multi-line inserts.
    my %DatabaseSQL;

    if ( $DBType eq 'oracle' && $AllowMultiple ) {

        %DatabaseSQL = (
            Start     => 'INSERT ALL ',
            FirstLine => '
                INTO article_data_otrs_chat (
                    article_id,chat_participant_id,chat_participant_name,
                    chat_participant_type,message_text,system_generated,create_time
                )
                VALUES ( ?, ?, ?, ?, ?, ?, ? ) ',
            NextLine => '
                INTO article_data_otrs_chat (
                    article_id,chat_participant_id,chat_participant_name,
                    chat_participant_type,message_text,system_generated,create_time
                )
                VALUES ( ?, ?, ?, ?, ?, ?, ? ) ',
            End => 'SELECT * FROM DUAL',
        );
    }
    else {
        %DatabaseSQL = (
            Start => '
                INSERT INTO article_data_otrs_chat (
                    article_id,chat_participant_id,chat_participant_name,
                    chat_participant_type,message_text,system_generated,create_time
                )',
            FirstLine => 'VALUES ( ?, ?, ?, ?, ?, ?, ? )',
            NextLine  => ', ( ?, ?, ?, ?, ?, ?, ? ) ',
            End       => '',
        );

    }

    my $SQL = '';
    my @Bind;

    ARTICLEENTRY:
    for my $ArticleEntry ( @{ $Param{Data} } ) {

        # Now the article entry is validated and can be added to sql.
        if ( !$SQL ) {
            $SQL = $DatabaseSQL{Start} . $DatabaseSQL{FirstLine};
        }
        else {
            $SQL .= $DatabaseSQL{NextLine};
        }

        push @Bind, (
            \$ArticleEntry->{ArticleID},
            \$ArticleEntry->{ChatParticipantID},
            \$ArticleEntry->{ChatParticipantName},
            \$ArticleEntry->{ChatParticipantType},
            \$ArticleEntry->{MessageText},
            \$ArticleEntry->{SystemGenerated},
            \$ArticleEntry->{CreateTime},
        );

        # Check the length of the SQL string
        # (some databases only accept SQL strings up to 4k,
        # so we want to stay safe here with just 3500 bytes).
        if ( length $SQL > 3500 || !$AllowMultiple || $ArticleEntry->{ID} == $Param{LastArticleDataID} ) {

            # Add the end line to sql string.
            $SQL .= $DatabaseSQL{End};

            # Insert multiple history entries.
            return if !$DBObject->Do(
                SQL  => $SQL,
                Bind => \@Bind,
            );

            # Reset the SQL string and the Bind array.
            $SQL  = '';
            @Bind = ();
        }
    }

    return 1;
}

=head2 _DeleteOldChatArticles()

Delete chat data from the article table. Returns 1 on success

    my $Result = $DBUpdateTo6Object->_DeleteOldChatArticles(
        ChatChannelID => $ChatChannelID, # ID of chat channel
    );

=cut

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

    # Check needed stuff.
    if ( !$Param{ChatChannelID} ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "Need ChatChannelID!",
        );
        return;
    }

    my $DBObject = $Kernel::OM->Get('Kernel::System::DB');

    # Check chat article data.
    return if !$DBObject->Prepare(
        SQL => '
            SELECT adm.id
            FROM article_data_mime adm
                JOIN article at ON adm.article_id = at.id
            WHERE at.communication_channel_id = ?
        ',
        Bind => [ \$Param{ChatChannelID} ],
    );

    my @ChatIDs;
    while ( my @Row = $DBObject->FetchrowArray() ) {
        push @ChatIDs, $Row[0];
    }

    my $RowsPerLoop = 1;
    my $IndexStart  = 0;
    my $IndexEnd;
    my $LastChatIDIndex = scalar @ChatIDs - 1;

    ENTRIES:
    while ( $IndexStart < scalar @ChatIDs ) {

        # Set the upper limit.
        my $IndexEnd = $IndexStart + $RowsPerLoop - 1;

        if ( $IndexEnd > $LastChatIDIndex ) {
            $IndexEnd = $LastChatIDIndex;
        }

        # Delete chat article data.
        return if !$DBObject->Do(
            SQL => '
                DELETE
                FROM article_data_mime
                WHERE id IN (' . join( ', ', @ChatIDs[ $IndexStart .. $IndexEnd ] ) . ' )
            ',
        );

        $IndexStart += $RowsPerLoop;
    }

    return 1;
}

=head2 _CheckChatArticles()

Verify if chat articles exists. Returns 1 on success

    my $Result = $DBUpdateTo6Object->_CheckChatArticles(
        ChatChannelID => $ChatChannelID, # ID of chat channel
    );

=cut

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

    # Check needed stuff.
    if ( !$Param{ChatChannelID} ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            Priority => 'error',
            Message  => "Need ChatChannelID!",
        );
        return;
    }

    my $DBObject = $Kernel::OM->Get('Kernel::System::DB');

    # Check chat article data.
    return if !$DBObject->Prepare(
        SQL => '
            SELECT COUNT(at.id)
            FROM article_data_mime adm
                JOIN article at ON adm.article_id = at.id
            WHERE at.communication_channel_id = ?
        ',
        Bind => [ \$Param{ChatChannelID} ],
    );

    my $ChatCount = 0;
    while ( my @Row = $DBObject->FetchrowArray() ) {
        $ChatCount = $Row[0] || 0;
    }

    return $ChatCount;
}

1;

=head1 TERMS AND CONDITIONS

This software is part of the OTRS project (L<http://otrs.org/>).

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 L<http://www.gnu.org/licenses/agpl.txt>.

=cut