File: CalendarEvents.pm

package info (click to toggle)
znuny 6.5.18-1
  • links: PTS
  • area: non-free
  • in suites: forky, sid
  • size: 205,344 kB
  • sloc: perl: 1,038,694; xml: 74,551; javascript: 65,276; sql: 23,574; sh: 417; makefile: 63
file content (641 lines) | stat: -rw-r--r-- 18,106 bytes parent folder | download | duplicates (5)
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
# --
# Copyright (C) 2021 Znuny GmbH, https://znuny.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 http://www.gnu.org/licenses/agpl.txt.
# --
## nofilter(TidyAll::Plugin::Znuny::Perl::LayoutObject)

package Kernel::System::CalendarEvents;

use strict;
use warnings;

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

our @ObjectDependencies = (
    'Kernel::Output::HTML::Layout',
    'Kernel::System::Cache',
    'Kernel::System::Log',
    'Kernel::System::Main',
    'Kernel::System::Ticket::Article',
);

=head1 NAME

Kernel::System::CalendarEvents - to manage calendar events

=head1 DESCRIPTION

Global module for operations that bases on calendar events

=head1 PUBLIC INTERFACE

=head2 new()

Don't use the constructor directly, use the ObjectManager instead:

    my $CalendarEventsObject = $Kernel::OM->Get('Kernel::System::CalendarEvents');

=cut

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

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

    $Self->{SupportedExtensionsSearchParams} = {
        ICS => {
            SearchRegex => {
                Value => 'BEGIN:VCALENDAR.+?END:VCALENDAR',
            }
        },
    };

    $Self->{PossibleAttachments}->{ContentType} = {
        'text/calendar'                 => 1,
        'application/hbs-vcs'           => 1,
        'application/vnd.swiftview-ics' => 1,
        'text/x-vcalendar'              => 1,
    };

    return $Self;
}

=head2 Parse()

Parses calendar events of specified data.

    my $CalendarEventsData = $CalendarEventsObject->Parse(
        TicketID    => $Param{TicketID},
        ArticleID   => $Param{ArticleID},
        String      => $ArticleContent, # parse specified text content
        Attachments => { # parse attachments
            Data => {
                '4' => {
                    'Disposition' => 'attachment',
                    'ContentType' => 'text/calendar; charset=UTF-8; name="Some calendar name.ics"',
                    'Filename'    => 'calendar.ics',
                    'FilesizeRaw' => '949'
                },
                '1' => {
                    'Disposition' => 'attachment',
                    'ContentType' => 'text/calendar; charset=UTF-8; name="Some calendar name1.ics"',
                    'Filename'    => 'calendar1.ics',
                    'FilesizeRaw' => '2967'
                },
            },
            Type => "Article", # specify type of attachments
        },
        ToTimeZone => $UserTimeZone,
    );

=cut

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

    my $LogObject     = $Kernel::OM->Get('Kernel::System::Log');
    my $LayoutObject  = $Kernel::OM->Get('Kernel::Output::HTML::Layout');
    my $ArticleObject = $Kernel::OM->Get('Kernel::System::Ticket::Article');
    my $CacheObject   = $Kernel::OM->Get('Kernel::System::Cache');
    my $MainObject    = $Kernel::OM->Get('Kernel::System::Main');

    my %DataToParse;
    my %ParsedData;

    my $ToTimeZoneCacheKey = $Param{ToTimeZone} || 'Default';

    if (
        IsHashRefWithData( $Param{Attachments} )
        && $Param{Attachments}->{Type}
        && $Param{Attachments}->{Type} eq 'Article'
        )
    {
        NEEDED:
        for my $Needed (qw(TicketID ArticleID)) {
            next NEEDED if defined $Param{$Needed};

            $LogObject->Log(
                Priority => 'error',
                Message  => "Need $Needed!",
            );
            return;
        }

        my $ArticleBackendObject = $ArticleObject->BackendForArticle(
            TicketID  => $Param{TicketID},
            ArticleID => $Param{ArticleID}
        );
        my $AttachmentsData = $Param{Attachments}->{Data};

        # parse attachments
        if ( IsHashRefWithData $AttachmentsData) {

            ATTACHMENTINDEX:
            for my $AttachmentIndex ( sort keys %{$AttachmentsData} ) {
                my %Data = $ArticleBackendObject->ArticleAttachment(
                    ArticleID => $Param{ArticleID},
                    TicketID  => $Param{TicketID},
                    FileID    => $AttachmentIndex,
                );

                $Data{Index} = $AttachmentIndex;

                next ATTACHMENTINDEX if !$Data{Content};
                next ATTACHMENTINDEX if !$Data{ContentType};

                next ATTACHMENTINDEX if $Data{ContentType} !~ m{^(.+?);.*};
                next ATTACHMENTINDEX if !$Self->{PossibleAttachments}->{ContentType}->{$1};

                my $CalendarEventsAttachment = $CacheObject->Get(
                    Type => 'CalendarEventsArticle',
                    Key => "Attachment::$Param{TicketID}::$Param{ArticleID}::${AttachmentIndex}::${ToTimeZoneCacheKey}",

                );

                if ( IsHashRefWithData($CalendarEventsAttachment) ) {
                    push @{ $ParsedData{Attachments} }, {
                        Data  => $CalendarEventsAttachment,
                        Index => $AttachmentIndex,
                    };
                }
                else {
                    push @{ $DataToParse{Attachments} }, \%Data;
                }
            }
        }
    }

    if ( $Param{String} ) {
        push @{ $DataToParse{String} }, {
            Content => $Param{String}
        };
    }

    return if !keys %DataToParse && !IsArrayRefWithData( $ParsedData{Attachments} );

    # support for specified calendar extensions
    # select each occurances content
    my $CalendarEvents;
    if ( keys %DataToParse ) {
        $CalendarEvents = $Self->FindEvents(
            %DataToParse,
        );
    }

    return \%ParsedData if !IsHashRefWithData($CalendarEvents);

    EXTENSION:
    for my $Extension ( sort keys %{$CalendarEvents} ) {
        next EXTENSION if !IsArrayRefWithData( $CalendarEvents->{$Extension} );
        my $BackendModule = "Kernel::System::CalendarEvents::$Extension";

        # check module validity
        if ( !$MainObject->Require($BackendModule) ) {
            $LogObject->Log(
                Priority => 'error',
                Message  => "Can't load $BackendModule.",
            );
            next EXTENSION;
        }

        if ( !$BackendModule->can('Parse') ) {
            $LogObject->Log(
                Priority => 'error',
                Message  => "Module $BackendModule is missing method 'Parse'.",
            );
            next EXTENSION;
        }

        $BackendModule = $BackendModule->new();

        my $Counter = 0;

        # parse actual content of each data type
        DATA:
        for my $Data ( $CalendarEvents->{$Extension} ) {

            next DATA if !IsArrayRefWithData($Data);

            EVENTSDATA:
            for my $EventsData ( @{$Data} ) {
                next EVENTSDATA if !IsArrayRefWithData( $EventsData->{CalendarEvents} );
                next EVENTSDATA if !$EventsData->{Type};

                CONTENT:
                for my $Content ( @{ $EventsData->{CalendarEvents} } ) {
                    my $Result = $BackendModule->Parse(
                        String     => $Content,
                        ToTimeZone => $Param{ToTimeZone},
                    );

                    next CONTENT if !$Result;

                    my $Index;
                    if (
                        $EventsData->{Type} eq 'Attachments'
                        && $EventsData->{Data}->{Index}
                        )
                    {
                        $Index = $EventsData->{Data}->{Index};
                        $CacheObject->Set(
                            Type  => 'CalendarEventsArticle',
                            Key   => "Attachment::$Param{TicketID}::$Param{ArticleID}::${Index}::${ToTimeZoneCacheKey}",
                            Value => $Result,
                            TTL   => 60 * 60,
                        );
                    }
                    else {
                        $Index = $Counter;
                        $Counter++;
                    }

                    push @{ $ParsedData{ $EventsData->{Type} } }, {
                        Data  => $Result,
                        Index => $Index,
                    };
                }
            }
        }
    }

    return \%ParsedData;
}

=head2 FindEvents()

Finds supported calendar event from the string.

    my $Result = $CalendarEventsObject->FindEvents(
        String => [
            {
                Content =>
                    "Hello! You've got an invitation for a meeting:
                    BEGIN:VCALENDAR
                    ..
                    END:VCALENDAR"
            }
        ],
        Attachments => [
            {
                Content =>
                    "Hello! You've got an invitation for a meeting:
                    BEGIN:VCALENDAR
                    ..
                    END:VCALENDAR"
            },
            {
                Content =>
                    "Hello! You've got an invitation for a meeting:
                    BEGIN:VCALENDAR
                    ..
                    END:VCALENDAR"
            },
            ..
        ],
    );

=cut

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

    my $LogObject = $Kernel::OM->Get('Kernel::System::Log');

    if (
        !$Param{String}
        && !$Param{Attachments}
        )
    {
        $LogObject->Log(
            Priority => 'error',
            Message  => 'Need either parameter String or Attachments.',
        );
        return;
    }

    my $SupportedExtensionsSearch = $Self->{SupportedExtensionsSearchParams};
    my %Result;

    DATATYPE:
    for my $DataType (qw(String Attachments)) {
        next DATATYPE if !IsArrayRefWithData( $Param{$DataType} );

        DATA:
        for my $Data ( @{ $Param{$DataType} } ) {
            next DATA if !IsHashRefWithData($Data);
            next DATA if !$Data->{Content};
            my $Content = $Data->{Content};

            # search for each supported extension
            my @EventsFound;
            for my $Extension ( sort keys %{$SupportedExtensionsSearch} ) {
                my $SearchRegex = $SupportedExtensionsSearch->{$Extension}->{SearchRegex};
                @EventsFound = $Content =~ m{$SearchRegex->{Value}}smg;
                if (@EventsFound) {
                    push @{ $Result{$Extension} }, {
                        CalendarEvents => \@EventsFound,
                        Type           => $DataType,
                        Data           => $Data,
                    };
                }
            }
        }
    }

    return \%Result;
}

=head2 BuildString()

Builds string for data output.

    my $OutputString = $CalendarEventsObject->BuildString(
        Data => {
          'Type'      => 'Recurrent', # required
          'Interval'  => '5',
          'ByDay'     => 'SU,TU,WE,TH,FR,SA',
          'AllDay'    => 1,
          'Frequency' => 'Weekly'
        },
        Type => 'Frequency',
    );

=cut

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

    my $LogObject      = $Kernel::OM->Get('Kernel::System::Log');
    my $LayoutObject   = $Kernel::OM->Get('Kernel::Output::HTML::Layout');
    my $LanguageObject = $LayoutObject->{LanguageObject};

    # check needed stuff
    NEEDED:
    for my $Needed (qw(Data Type)) {
        next NEEDED if defined $Param{$Needed};

        $LogObject->Log(
            Priority => 'error',
            Message  => "Parameter '$Needed' is needed!",
        );
        return;
    }

    my %Data = %{ $Param{Data} };

    return if $Param{Type} ne 'Frequency';
    return if !$Data{Frequency};

    my $Interval = $Data{Interval} || 1;

    my $FrequencyMapping = $Self->_FrequencyStringMappingGet();
    my $MonthsMapping    = $Self->_MonthsMappingGet();
    my $DaysMapping      = $Self->_DaysMappingGet();
    my $DaysOrderMapping = $Self->_DaysOrderMappingGet();
    my $EveryType        = $Interval > 1 ? "Multiple" : "Single";
    my $EveryWhat        = $FrequencyMapping->{ $Data{Frequency} }->{$EveryType};

    my %Details = (
        BySecond   => '',
        ByMinute   => '',
        ByHour     => '',
        ByDay      => '',
        ByMonthDay => '',
        ByYearDay  => '',
        ByWeek     => '',
        ByMonth    => '',

        #               BySetPos   => '',
    );

    my $On;

    PROPERTY:
    for my $Property (qw(BySecond ByMinute ByHour ByMonthDay ByYearDay)) {
        next PROPERTY if !$Data{$Property};

        my @ByProperty = split /,/, $Data{$Property};
        next PROPERTY if !@ByProperty;

        $On = 1;
        $Details{$Property} .= join ', ', @ByProperty;
    }

    my $In;

    if ( $Data{ByMonth} ) {
        my @ByMonth = split /,/, $Data{ByMonth};
        if (@ByMonth) {
            $In = 1;

            my @MonthValues = map { $MonthsMapping->{$_} } @ByMonth;
            $Details{ByMonth} .= join ', ', @MonthValues;
        }
    }

    if ( $Data{ByDay} ) {
        my @ByDay = split /,/, $Data{ByDay};

        my @DayValues;

        BYDAY:
        for my $ByDay (@ByDay) {
            next BYDAY if $ByDay !~ m{(-*)(\d*)(\w{2})};

            if ( $1 && $2 ) {
                push @DayValues, $DaysOrderMapping->{ $1 . $2 } . ' ' . $DaysMapping->{$3};
            }
            elsif ($2) {
                push @DayValues, $DaysOrderMapping->{$2} . ' ' . $DaysMapping->{$3};
            }
            elsif ( !$1 && !$2 ) {
                push @DayValues, $DaysMapping->{$3};
            }
        }

        if (@DayValues) {
            $On = 1;
            $Details{ByDay} .= join ', ', @DayValues;
        }
    }

    my $FrequencyString =
        $LanguageObject->Translate("every") . " $Interval" . " " .
        $LanguageObject->Translate($EveryWhat);

    if ($In) {
        $FrequencyString .= " " . $LanguageObject->Translate("in") . " ";
        if ( $Details{ByMonth} ) {
            $FrequencyString .= $LanguageObject->Translate( $Details{ByMonth} );
        }
    }

    if ($On) {
        $FrequencyString .= " " . $LanguageObject->Translate("on") . " ";
        if ( $Details{ByYearDay} ) {
            $FrequencyString .= $LanguageObject->Translate("day") . " $Details{ByYearDay}"
                . $LanguageObject->Translate("of year")
                . ', ';
        }
        if ( $Details{ByMonthDay} ) {
            $FrequencyString .= $LanguageObject->Translate("day") . " $Details{ByMonthDay}"
                . $LanguageObject->Translate("of month")
                . ', ';
        }
        if ( $Details{ByHour} ) {
            $FrequencyString .= $LanguageObject->Translate("hour") . " $Details{ByHour}"
                . ', ';
        }
        if ( $Details{ByMinute} ) {
            $FrequencyString .= $LanguageObject->Translate("minute") . " $Details{ByMinute}"
                . ', ';
        }
        if ( $Details{BySecond} ) {
            $FrequencyString .= $LanguageObject->Translate("second") . " $Details{BySecond}"
                . ', ';
        }
        if ( $Details{ByDay} ) {
            if ( $Details{ByDay} =~ m{(\w+?) {1}(\w+)} ) {
                $FrequencyString .= $LanguageObject->Translate("$1") . " " .
                    $LanguageObject->Translate("$2")
                    . ', ';
            }
            else {
                $FrequencyString .= $LanguageObject->Translate("$Details{ByDay}")
                    . ', ';
            }
        }
        if ( $Data{AllDay} && $Param{OriginalTimeZone} ) {
            $FrequencyString .= $LanguageObject->Translate("all-day")
                . "(" . $LanguageObject->Translate( $Param{OriginalTimeZone} ) . ")"
                . ', ';
        }
        $FrequencyString = substr $FrequencyString, 0, -2;
    }
    else {
        if ( $Data{AllDay} && $Param{OriginalTimeZone} ) {
            $FrequencyString .= ', ' . $LanguageObject->Translate("all-day")
                . " (" . $LanguageObject->Translate( $Param{OriginalTimeZone} ) . ")";
        }
    }

    return $FrequencyString;
}

=head2 _FrequencyStringMappingGet()

Get frequency string mapping.

    my $FrequencyStringMapping = $CalendarEventsObject->_FrequencyStringMappingGet();

=cut

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

    return {
        Yearly => {
            Single   => 'year',
            Multiple => 'years'
        },
        Monthly => {
            Single   => 'month',
            Multiple => 'months'
        },
        Weekly => {
            Single   => 'week',
            Multiple => 'weeks'
        },
        Daily => {
            Single   => 'day',
            Multiple => 'days'
        },
        Hourly => {
            Single   => 'hour',
            Multiple => 'hours'
        },
        Minutely => {
            Single   => 'minute',
            Multiple => 'minutes'
        },
        Secondely => {
            Single   => 'second',
            Multiple => 'seconds'
        }
    };
}

=head2 _MonthsMappingGet()

Get months mapping.

    my $MonthsMapping = $CalendarEventsObject->_MonthsMappingGet();

=cut

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

    return {
        1  => 'January',
        2  => 'February',
        3  => 'March',
        4  => 'April',
        5  => 'May',
        6  => 'June',
        7  => 'July',
        8  => 'August',
        9  => 'September',
        10 => 'October',
        11 => 'November',
        12 => 'December',
    };
}

=head2 _DaysMappingGet()

Get days mapping

    my $DaysMapping = $CalendarEventsObject->_DaysMappingGet();

=cut

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

    return {
        MO => 'Monday',
        TU => 'Tuesday',
        WE => 'Wednesday',
        TH => 'Thursday',
        FR => 'Friday',
        SA => 'Saturday',
        SU => 'Sunday',
    };
}

=head2 _DaysOrderMappingGet()

Get days order mapping

    my $DaysOrderMapping = $CalendarEventsObject->_DaysOrderMappingGet();

=cut

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

    return {
        -1 => 'last',
        1  => 'first',
        2  => 'second',
        3  => 'third',
        4  => 'fourth',
    };
}

1;