Skip to content
Snippets Groups Projects
planning.php 57.8 KiB
Newer Older
<?php

/**
 * planning.php - contains RoomManagement_PlanningController
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * @author      Moritz Strohm <strohm@data-quest.de>
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @copyright   2017
 * @category    Stud.IP
 * @since       4.1
 */


/**
 * RoomManagement_PlanningController contains room planning functionality.
 */
class RoomManagement_PlanningController extends AuthenticatedController
{
    public function index_action($selected_clipboard_id = null)
    {
        PageLayout::setTitle(
            _('Raumgruppen-Belegungsplan')
        );

        if (Navigation::hasItem('/resources/planning/index')) {
            Navigation::activateItem('/resources/planning/index');
        }
        $selected_clipboard_id = Request::get('clipboard_id', $selected_clipboard_id);
Moritz Strohm's avatar
Moritz Strohm committed

        $this->no_clipboard = false;
        $this->no_rooms = false;

        if ($selected_clipboard_id) {
            $_SESSION['selected_clipboard_id'] = $selected_clipboard_id;
        } else {
            $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        }

        $this->display_all_requests = Request::get('display_all_requests');

        //Build sidebar:
        $sidebar = Sidebar::get();

Moritz Strohm's avatar
Moritz Strohm committed
        $actions = new ActionsWidget();
        $actions->addLink(
            _('Drucken'),
            'javascript:void(window.print());',
            Icon::create('print')
        );
        $sidebar->addWidget($actions);

        $views = new ViewsWidget();
        if ($GLOBALS['user']->id && ($GLOBALS['user']->id !== 'nobody')) {
            $views->addLink(
                _('Standard Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/index',
                    [
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d'))
                    ]
                ),
                null,
                ['class' => 'booking-plan-std_view']
            )->setActive(!Request::get('allday'));

            $views->addLink(
                _('Ganztägiges Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/index',
                    [
                        'allday'      => true,
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d'))
                    ]
                ),
                null,
                ['class' => 'booking-plan-allday_view']
            )->setActive(Request::get('allday'));
        }
        $sidebar->addWidget($views);

        $dpicker = new SidebarWidget();
        $dpicker->setTitle('Datum');
        $picker_html = $this->get_template_factory()->render(
            'resources/room_planning/_sidebar_date_selection.php'
        );
        $dpicker->addElement(new WidgetElement($picker_html));
        $sidebar->addWidget($dpicker);

        $clipboards = Clipboard::getClipboardsForUser($GLOBALS['user']->id);
        if (!empty($clipboards)) {
            $clipboard_widget = new SelectWidget(
                _('Individuelle Raumgruppen'),
                $this->indexURL(),
                'clipboard_id',
                'get'
            );
            foreach ($clipboards as $clipboard) {
                $clipboard_widget->addElement(new SelectElement(
                    $clipboard->id,
                    $clipboard->name,
                    $clipboard->id === $selected_clipboard_id
                ), "clipboard_id-{$clipboard->id}");
            $sidebar->addWidget($clipboard_widget);
        }

        $rooms = [];
        if ($selected_clipboard_id) {
            $clipboard = Clipboard::find($selected_clipboard_id);
            $this->clipboard = $clipboard;
            if ($clipboard) {
                PageLayout::setTitle(
                    $clipboard->name . ': ' . _('Raumgruppen-Belegungsplan')
                );
                $room_ids = $clipboard->getAllRangeIds('Room');
                $rooms = Room::findMany($room_ids);
            } else {
                $this->no_clipboard = true;
                return;
            }
        }

        if (!$rooms) {
            //No rooms could be found.
            $this->no_rooms = true;
            return;
        }

        //Generate the resources array for the fullcalendar scheduler plugin:
        $this->scheduler_resources = [];
        foreach ($room_ids as $room_id) {
            $room = Room::find($room_id);
            $this->scheduler_resources[] = [
                'id'          => $room->id,
                'parent_name' => $room->building->name,
                'title'       => $room->name
            ];
        }

        $current_user = User::findCurrent();

        $room_c = count($rooms);
        $requestable_rooms_c = 0;
        $request_rights_c = 0;
        $booking_rights_c = 0;
        $admin_rights_c = 0;
Jan-Hendrik Willms's avatar
Jan-Hendrik Willms committed
        $this->booking_types = [
            ResourceBooking::TYPE_NORMAL,
            ResourceBooking::TYPE_RESERVATION,
            ResourceBooking::TYPE_LOCK,
        ];

        foreach ($rooms as $room) {
            if ($room->userHasRequestRights($current_user)) {
                $request_rights_c++;
            }
            if ($room->userHasBookingRights($current_user)) {
                $booking_rights_c++;
            }
            if ($room->userHasPermission($current_user, 'admin')) {
                $admin_rights_c++;
            }
            if ($room->requestable) {
                $requestable_rooms_c++;
            }

            //Check the permissions for the room:
            //The booking plan must be visible for the user.
            $sufficient_permissions =
                $room->bookingPlanVisibleForUser($current_user);
            if (!$sufficient_permissions) {
                throw new AccessDeniedException(
                    sprintf(
                        _('Der Belegungsplan des Raumes %s ist für Sie nicht zugänglich!'),
                        $room->name
                    )
                );
            }
        }

        $this->all_rooms_booking_rights = ($room_c == $booking_rights_c);
        $all_rooms_admin = ($room_c == $admin_rights_c);
        if ($all_rooms_admin) {
            //Display planned bookings, too:
Jan-Hendrik Willms's avatar
Jan-Hendrik Willms committed
            $this->booking_types[] = ResourceBooking::TYPE_PLANNED;
        }
        if (!$this->all_rooms_booking_rights && $this->display_all_requests) {
            throw new AccessDeniedException(
                _('Sie sind nicht dazu berechtigt, alle Anfragen im Belegungsplan zu sehen!')
            );
        }

        if (Config::get()->RESOURCES_ALLOW_ROOM_REQUESTS && $this->all_rooms_booking_rights) {
            $options = new OptionsWidget();
            $options->addCheckbox(
                _('Alle Anfragen anzeigen'),
                $this->display_all_requests ? 'checked' : '',
                $this->url_for(
                    'room_management/planning/index/' . $_SESSION['selected_clipboard_id'],
                    [
                        'display_all_requests' => '1'
                    ]
                ),
                $this->url_for(
                    'room_management/planning/index/' . $_SESSION['selected_clipboard_id']
                ),
                []
            );
            $sidebar->insertWidget($options, 'roomclipboard');
        }

        $this->fullcalendar_studip_urls = [];
        if ($this->all_rooms_booking_rights) {
            $this->fullcalendar_studip_urls['add'] = URLHelper::getURL(
                'dispatch.php/resources/booking/add'
            );
        }

        $booking_colour = ColourValue::find('Resources.BookingPlan.Booking.Bg');
        $course_booking_colour = ColourValue::find('Resources.BookingPlan.CourseBooking.Bg');
        $lock_colour = ColourValue::find('Resources.BookingPlan.Lock.Bg');
        $preparation_colour = ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
        $reservation_colour = ColourValue::find('Resources.BookingPlan.Reservation.Bg');
        $request_colour = ColourValue::find('Resources.BookingPlan.Request.Bg');
        $this->table_keys = [
            [
                'colour' => $booking_colour->__toString(),
                'text'   => _('Manuelle Buchung')
            ],
            [
                'colour' => $course_booking_colour->__toString(),
                'text'   => _('Veranstaltungsbezogene Buchung')
            ],
            [
                'colour' => $lock_colour->__toString(),
                'text'   => _('Sperrbuchung')
            ],
            [
                'colour' => $preparation_colour->__toString(),
                'text'   => _('Rüstzeit')
            ],
            [
                'colour' => $reservation_colour->__toString(),
                'text'   => _('Reservierung')
            ],
        ];
        if ($all_rooms_admin) {
            $planned_booking_colour = ColourValue::find('Resources.BookingPlan.PlannedBooking.Bg');
            $this->table_keys[] = [
                'colour' => $planned_booking_colour->__toString(),
                'text'   => _('Geplante Buchung')
            ];
        }
        if ($this->display_all_requests) {
            $this->table_keys[] = [
                'colour' => $request_colour->__toString(),
                'text'   => _('Anfrage')
            ];
        }
    }

    public function semester_plan_action($selected_clipboard_id = null)
    {
        PageLayout::setTitle(
            _('Raumgruppen-Semester-Belegungsplan')
        );

        if (Navigation::hasItem('/resources/planning/semestergroup_plan')) {
            Navigation::activateItem('/resources/planning/semestergroup_plan');
        }

        $selected_clipboard_id = Request::get('clipboard_id', $selected_clipboard_id);
Moritz Strohm's avatar
Moritz Strohm committed

        $this->no_clipboard = false;
        $this->no_rooms = false;

        if ($selected_clipboard_id) {
            $_SESSION['selected_clipboard_id'] = $selected_clipboard_id;
        } else {
            $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        }

        $this->display_all_requests = Request::get('display_all_requests');

        //Build sidebar:
        $sidebar = Sidebar::get();

        $this->semester = Semester::findCurrent();
        //For the semester selector:
        if (Request::submitted('semester_id')) {
            $this->semester = Semester::find(Request::get('semester_id'));
            if (!$this->semester) {
                PageLayout::postError(
                    _('Das ausgewählte Semester wurde nicht in der Datenbank gefunden!')
                );
                return;
            }
        }

        $actions = new ActionsWidget();
Moritz Strohm's avatar
Moritz Strohm committed
        $actions->addLink(
            _('Drucken'),
            'javascript:void(window.print());',
            Icon::create('print')
        );
        $actions->addLink(
            _('Buchungen kopieren'),
            $this->url_for('room_management/planning/copy_bookings'),
            ['data-dialog' => 'size=auto']
        );
        $sidebar->addWidget($actions);


        if ($GLOBALS['user']->id && ($GLOBALS['user']->id != 'nobody')) {
            $views = new ViewsWidget();
            $views->setTitle(_('Zeitfenster'));
            $views->addLink(
                _('Standard Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => Request::get('semester_timerange', 'vorles')
                    ]
                ),
                null,
                ['class' => 'booking-plan-std_view']
            )->setActive(!Request::get('allday'));

            $views->addLink(
                _('Ganztägiges Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'allday' => true,
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => Request::get('semester_timerange', 'vorles')
                    ]
                ),
                null,
                ['class' => 'booking-plan-allday_view']
            )->setActive(Request::get('allday'));
            $sidebar->addWidget($views);

            $views2 = new ViewsWidget();
            $views2->setTitle(_('Semesterzeitraum'));
            $views2->addLink(
                _('Vorlesungszeit'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'allday' => Request::get('allday'),
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => 'vorles'
                    ]
                ),
                null,
                ['class' => 'booking-plan-vorles_view']
            )->setActive(Request::get('semester_timerange') != 'fullsem');
            $views2->addLink(
                _('gesamtes Semester'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'allday' => Request::get('allday'),
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => 'fullsem'
                    ]
                ),
                null,
                ['class' => 'booking-plan-fullsem_view']
            )->setActive(Request::get('semester_timerange') == 'fullsem');
            $sidebar->addWidget($views2);
        }
        $semester_selector = new SemesterSelectorWidget(
            URLHelper::getURL(
Moritz Strohm's avatar
Moritz Strohm committed
                'dispatch.php/room_management/planning/semester_plan/' . (!empty($this->resource) ? $this->resource->id : ''),
                [
                    'allday' => Request::get('allday', false)
                ]
            )
        );
        $sidebar->addWidget($semester_selector);

        $clipboards = Clipboard::getClipboardsForUser($GLOBALS['user']->id);
        if (!empty($clipboards)) {
            $clipboard_widget = new SelectWidget(
                _('Individuelle Raumgruppen'),
                $this->semester_planURL(),
                'clipboard_id',
                'get'
            );
            foreach ($clipboards as $clipboard) {
                $clipboard_widget->addElement(new SelectElement(
                    $clipboard->id,
                    $clipboard->name,
                    $clipboard->id === $selected_clipboard_id
                ), "clipboard_id-{$clipboard->id}");
            }
            $sidebar->addWidget($clipboard_widget);
        }

        //Check if a clipboard is selected:
        $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        $rooms = [];
        if ($selected_clipboard_id) {
            $clipboard = Clipboard::find($selected_clipboard_id);
            $this->clipboard = $clipboard;
            if ($clipboard) {
                PageLayout::setTitle(
                    $clipboard->name . ': ' . _('Raumgruppen-Semester-Belegungsplan')
                );
                $room_ids = $clipboard->getAllRangeIds('Room');
                $rooms = Room::findMany($room_ids);
            } else {
                $this->no_clipboard = true;
                return;
            }
        }

        if (!$rooms) {
            //No rooms could be found.
            $this->no_rooms = true;
            return;
        }

        //Generate the resources array for the fullcalendar scheduler plugin:
        $this->scheduler_resources = [];
        foreach ($room_ids as $room_id) {
            $room = Room::find($room_id);
            $this->scheduler_resources[] = [
                'id' => $room->id,
                'parent_name' => $room->building->name,
                'title' => $room->name
            ];
        }

        $current_user = User::findCurrent();

        $room_c = count($rooms);
        $requestable_rooms_c = 0;
        $booking_rights_c = 0;
        $admin_rights_c = 0;
Jan-Hendrik Willms's avatar
Jan-Hendrik Willms committed
        $this->booking_types = [
            ResourceBooking::TYPE_NORMAL,
            ResourceBooking::TYPE_RESERVATION,
            ResourceBooking::TYPE_LOCK,
        ];

        foreach ($rooms as $room) {
            if ($room->userHasBookingRights($current_user)) {
                $booking_rights_c++;
            }
            if ($room->userHasPermission($current_user, 'admin')) {
                $admin_rights_c++;
            }
            if ($room->requestable) {
                $requestable_rooms_c++;
            }

            //Check the permissions for the room:
            if (!$room->bookingPlanVisibleForUser($current_user)) {
                throw new AccessDeniedException();
            }
        }

        $all_rooms_requestable = ($room_c == $requestable_rooms_c);
        $all_rooms_booking_rights = ($room_c == $booking_rights_c);
        $all_rooms_admin = ($room_c == $admin_rights_c);
        if ($all_rooms_admin) {
            //Display planned bookings, too:
Jan-Hendrik Willms's avatar
Jan-Hendrik Willms committed
            $this->booking_types[] = ResourceBooking::TYPE_PLANNED;
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
        }

        if (!$all_rooms_booking_rights && $this->display_all_requests) {
            throw new AccessDeniedException(
                _('Sie sind nicht dazu berechtigt, alle Anfragen im Belegungsplan zu sehen!')
            );
        }

        if ($all_rooms_booking_rights) {
            $options = new OptionsWidget();
            $options->addCheckbox(
                _('Alle Anfragen anzeigen'),
                $this->display_all_requests ? 'checked' : '',
                $this->url_for(
                    'room_management/planning/semester_plan/' . $_SESSION['selected_clipboard_id'],
                    [
                        'display_all_requests' => '1',
                        'semester_id' => Request::option('semester_id')
                    ]
                ),
                $this->url_for(
                    'room_management/planning/semester_plan/' . $_SESSION['selected_clipboard_id'],
                    [
                        'semester_id' => Request::option('semester_id')
                    ]
                ),
                []
            );
            $sidebar->insertWidget($options, 'roomclipboard');
        }

        $booking_colour = ColourValue::find('Resources.BookingPlan.Booking.Bg');
        $simple_booking_exception_colour = ColourValue::find('Resources.BookingPlan.SimpleBookingWithExceptions.Bg');
        $course_booking_colour = ColourValue::find('Resources.BookingPlan.CourseBooking.Bg');
        $course_booking_with_exceptions_colour = ColourValue::find('Resources.BookingPlan.CourseBookingWithExceptions.Bg');
        $lock_colour = ColourValue::find('Resources.BookingPlan.Lock.Bg');
        $preparation_colour = ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
        $reservation_colour = ColourValue::find('Resources.BookingPlan.Reservation.Bg');
        $request_colour = ColourValue::find('Resources.BookingPlan.Request.Bg');
        $this->table_keys = [
            [
                'colour' => $booking_colour->__toString(),
                'text'   => _('Manuelle Buchung')
            ],
            [
                'colour' => $course_booking_colour->__toString(),
                'text'   => _('Veranstaltungsbezogene Buchung')
            ],
            [
                'colour' => $lock_colour->__toString(),
                'text'   => _('Sperrbuchung')
            ],
            [
                'colour' => $preparation_colour->__toString(),
                'text'   => _('Rüstzeit')
            ],
            [
                'colour' => $reservation_colour->__toString(),
                'text'   => _('Reservierung')
            ],
        ];
        if ($all_rooms_admin) {
            $planned_booking_colour = ColourValue::find('Resources.BookingPlan.PlannedBooking.Bg');
            $this->table_keys[] = [
                'colour' => $planned_booking_colour->__toString(),
                'text'   => _('Geplante Buchung')
            ];
        }
        if ($this->display_all_requests) {
            $this->table_keys[] = [
                'colour' => $request_colour->__toString(),
                'text'   => _('Anfrage')
            ];
        }

    }

    public function copy_bookings_action($clipboard_id = null)
    {
        PageLayout::setTitle(
            _('Buchungen kopieren')
        );

        if (Navigation::hasItem('/resources/planning/copy_bookings')) {
            Navigation::activateItem('/resources/planning/copy_bookings');
        }

        //Check if the clipboard is selected:
        $selected_clipboard_id = $_SESSION['selected_clipboard_id'];

        $user = User::findCurrent();

        $this->clipboard = null;
        if ($selected_clipboard_id) {
            $this->clipboard = Clipboard::find($selected_clipboard_id);
        } else {
            $this->clipboard = Clipboard::find($clipboard_id);
            if (!$clipboard_id) {
                PageLayout::postError(
                    _('Es wurde keine Raumgruppe ausgewählt!')
                );
                return;
            }
        }
        if (!$this->clipboard) {
            PageLayout::postError(
                _('Die gewählte Raumgruppe wurde nicht gefunden!')
            );
            return;
        }
        if ($this->clipboard->user_id != $GLOBALS['user']->id) {
            throw new AccessDeniedException();
        }

        PageLayout::setTitle(
            $this->clipboard->name . ': ' . _('Buchungen kopieren')
        );

        //Step 1: Room selection
        $this->step = 1;

        //Get all Room items from the clipboard where the user has at least
        //user permissions:
        $all_room_ids = $this->clipboard->getAllRangeIds('Room');
        $unfiltered_rooms = Room::findMany($all_room_ids);
        $this->rooms = [];
        $this->available_room_ids = [];
        foreach ($unfiltered_rooms as $room) {
            if ($room->userHasPermission($user, 'autor')) {
                $this->rooms[] = $room;
                $this->available_room_ids[] = $room->id;
            }
        }

        $this->selected_room_ids = [];

        //Get all available semesters:
        $this->available_semesters = Semester::getAll();
        $this->sem_week_selected = false;
        $this->selected_sem_week = 1;

        if (Request::isPost()) {
            CSRFProtection::verifyUnsafeRequest();
            if (Request::submitted('select_rooms') || Request::submitted('step1')) {
                $this->step = 2;
            } elseif (Request::submitted('test_copy') || Request::submitted('step2')
                      || Request::submitted('download_booking_list')) {
                $this->step = 3;
            } elseif (Request::submitted('copy')) {
                $this->step = 4;
            }
        }

        if ($this->step >= 2) {
            //Step 2: Select and verify bookings and semester
            $this->source_semester_id = Request::get('source_semester_id');
            $this->sem_week_selected = Request::get('sem_week_selected');
            $this->selected_sem_week = Request::get('selected_sem_week');
            $this->selected_room_ids = Request::getArray('selected_room_ids');
            if (!$this->source_semester_id) {
                PageLayout::postError(
                    _('Es wurde kein Semester ausgewählt!')
                );
                $this->step = 1;
                return;
            }
            $this->source_semester = Semester::find($this->source_semester_id);
            if (!$this->source_semester) {
                PageLayout::postError(
                    _('Das gewählte Semester wurde nicht gefunden!')
                );
                $this->step = 1;
                return;
            }
            if ($this->sem_week_selected) {
                $last_sem_week_number = $this->source_semester->getSemWeekNumber(
                    $this->source_semester->vorles_ende
                );
                if (($this->selected_sem_week < 1) || ($this->selected_sem_week > $last_sem_week_number)) {
                    PageLayout::postError(
                        _('Die gewählte Semesterwoche liegt außerhalb des gewählten Semesters!')
                    );
                    $this->step = 1;
                    return;
                }
            }
            if (!$this->selected_room_ids) {
                PageLayout::postError(
                    _('Es wurden keine Räume ausgewählt!')
                );
                $this->step = 1;
                return;
            }

            foreach ($this->selected_room_ids as $room_id) {
                if (!in_array($room_id, $all_room_ids)) {
                    PageLayout::postError(
                        _('Es wurde ein Raum ausgewählt, der nicht Teil der Raumgruppe ist!')
                    );
                    $this->step = 1;
                    return;
                }
                if (!in_array($room_id, $this->available_room_ids)) {
                    PageLayout::postError(
                        _('Es wurde ein Raum ausgewählt, an dem die Berechtigungen zum Kopieren von Buchungen nicht ausreichend sind!')
                    );
                    $this->step = 1;
                    return;
                }
            }

            if (Request::submitted('step1')) {
                $this->step = 1;
                return;
            }

            $this->selected_rooms = Room::findMany($this->selected_room_ids);

            $this->available_target_semesters = Semester::findBySql(
                'beginn > :source_semester_end ORDER BY beginn ASC',
                ['source_semester_end' => $this->source_semester->ende]
            );
            if (!$this->available_target_semesters) {
                PageLayout::postError(
                    _('Es sind keine Semester vorhanden, die nach dem ausgewählten Semester starten!')
                );
                $this->step = 1;
                return;
            }

            $unfiltered_bookings = [];
            foreach ($this->selected_rooms as $room) {
                $room_bookings = [];
                if ($this->sem_week_selected) {
                    $selected_week_begin = $this->source_semester->vorles_beginn;
                    if ($this->selected_sem_week > 1) {
                        $selected_week_begin = strtotime(
                            sprintf('+%d weeks', $this->selected_sem_week),
                            $this->source_semester->vorles_beginn
                        );
                    }
                    $room_bookings = ResourceBooking::findByResourceAndTimeRanges(
                        $room,
                        [
                            [
                                'begin' => $selected_week_begin,
                                'end' => $this->source_semester->ende
                            ]
                        ]
                    );
                } else {
                    $room_bookings = ResourceBooking::findByResourceAndTimeRanges(
                        $room,
                        [
                            [
                                'begin' => $this->source_semester->beginn,
                                'end' => $this->source_semester->ende
                            ]
                        ]
                    );
                }
                if ($room_bookings) {
                    $unfiltered_bookings = array_merge(
                        $unfiltered_bookings,
                        $room_bookings
                    );
                }
            }
            $this->bookings = [];
            $this->available_booking_ids = [];
            $this->booking_time_ranges = [];
            foreach ($unfiltered_bookings as $booking) {
                if (!$booking->repetition_interval || !$booking->isSimpleBooking()) {
                    //We only regard simple bookings with repetitions here.
                    continue;
                }
                $this->bookings[] = $booking;
                $this->available_booking_ids[] = $booking->id;
                $this->booking_time_ranges[$booking->id] =
                    $booking->getTimeIntervalStrings();
            }

            if (!$this->available_booking_ids) {
                PageLayout::postError(
                    sprintf(
                        _('Die gewählten Räume haben im Semester %s keine einfachen Buchungen mit Wiederholungen!'),
                        htmlReady($this->source_semester->name)
                    )
                );
                $this->step = 1;
                return;
            }
        }
        if ($this->step >= 3) {
            //Step 3: Test copying into the target semester
            $this->show_copy_button = false;
            $this->target_semester_id = Request::get('target_semester_id');
            $this->selected_booking_ids = Request::getArray('selected_booking_ids');
            if (!$this->target_semester_id) {
                PageLayout::postError(
                    _('Es wurde kein Zielsemester ausgewählt!')
                );
                $this->step = 2;
                return;
            }
            $this->target_semester = Semester::find($this->target_semester_id);
            if (!$this->target_semester) {
                PageLayout::postError(
                    _('Das gewählte Zielsemester wurde nicht gefunden!')
                );
                $this->step = 2;
                return;
            }

            if (!$this->selected_booking_ids) {
                PageLayout::postError(
                    _('Es wurden keine Buchungen ausgewählt!')
                );
                $this->step = 2;
                return;
            }

            foreach ($this->selected_booking_ids as $booking_id) {
                if (!in_array($booking_id, $this->available_booking_ids)) {
                    PageLayout::postError(
                        _('Es wurde eine Buchung ausgewählt, die nicht Teil der Raumgruppe ist!')
                    );
                    $this->step = 2;
                    return;
                }
            }

            if (Request::submitted('step2')) {
                $this->step = 2;
                return;
            }

            //Retrieve booking objects:
            $this->selected_bookings = ResourceBooking::findMany($this->selected_booking_ids);

            if (!$this->selected_bookings) {
                PageLayout::postError(
                    _('Die gewählten Buchungen wurden nicht in der Datenbank gefunden!')
                );
                $this->step = 2;
                return;
            }

            //$booking_copy_data is an associative array where the items have
            //the following strucutre:
            //[
            //    'sem_week' => The week number of the target semester.
            //    'begin' => The timestamp of the begin of the copied booking.
            //    'end' => The timestamp of the end of the copied booking.
            //    'available' => Whether the resource is available
            //        on the specified time range (true) or not (false).
            //]
            $this->booking_copy_data = [];

            //Loop over each booking and do the following:
            //1. Calculate the week number and the week day of the booking
            //   in the semester, unless the week number has been explicitly
            //   specified in step 1.
            //2. Calculate the date for the copy of the booking and store it
            //   in an array.
            //3. Check if the resource of the booking is available on the
            //   calculcated date in the time range of the original booking.
            //4. Add the availability information to the array
            //   with the booking copies.
            //5. Count the number of bookings and how many of them can be
            //   copied in the target semester. If more that 50% of bookings
            //   cannot be copied, do not show the copy action and instead
            //   provide a download button to download the list of bookings.

            $available_booking_c = 0;
            foreach ($this->selected_bookings as $booking) {
                $begin_sem_week_number = 0;
                if ($this->sem_week_selected) {
                    $begin_sem_week_number = $this->selected_sem_week +
                                             $this->source_semester->getSemWeekNumber($booking->begin) - 1;
                } else {
                    $begin_sem_week_number = $this->source_semester->getSemWeekNumber($booking->begin);
                }
                if (!$begin_sem_week_number) {
                    PageLayout::postError(
                        sprintf(
                            _('Eine Buchung (%1$s) liegt außerhalb des Semesters %2$s!'),
                            htmlReady($booking->__toString()),
                            htmlReady($this->source_semester->name)
                        )
                    );
                    $this->step = 2;
                    return;
                }
                $begin_week_day = date('N', $booking->begin);
                $begin_time = explode(':', date('H:i:s', $booking->begin));
                $end_time = explode(':', date('H:i:s', $booking->end));

                //Calculate the duration (begin-end-difference):
                $booking_begin = new DateTime();
                $booking_begin->setTimestamp($booking->begin);
                $booking_end = new DateTime();
                $booking_end->setTimestamp($booking->end);

                $duration = $booking_begin->diff($booking_end);
                $booking_repeat_end = new DateTime();
                $booking_repeat_end->setTimestamp($booking->repeat_end);
                $repeat_duration = $booking_end->diff($booking_repeat_end);

                //Calculate the new begin date:
                $target_sem_week_begin = new DateTime();
                $target_sem_week_begin->setTimestamp($this->target_semester->beginn);
                $target_sem_week_begin = $target_sem_week_begin->add(
                    new DateInterval('P' . ($begin_sem_week_number - 1) . 'W')
                );
                $target_begin = clone $target_sem_week_begin;
                $begin_week_day_diff = $begin_week_day - $target_sem_week_begin->format('N');
                if ($begin_week_day_diff < 0) {
                    $target_begin = $target_begin->sub(
                        new DateInterval('P' . abs($begin_week_day_diff) . 'D')
                    );
                } elseif ($begin_week_day_diff > 0) {
                    $target_begin = $target_begin->add(
                        new DateInterval('P' . $begin_week_day_diff . 'D')
                    );
                }
                $target_begin->setTime(
                    intval($begin_time[0]),
                    intval($begin_time[1]),
                    intval($begin_time[2])
                );

                //Calculcate the new end date using the duration:
                $target_end = clone $target_begin;
                $target_end = $target_end->add($duration);

                //Calculcate the new repeat end using the repeat duration
                //or the end of the semester, if repeat_end of the original
                //booking is the same timestamp as the course end of the
                //source semester.
                $target_repeat_end = clone $target_end;
                if ($booking->repeat_end >= $this->source_semester->vorles_ende) {
                    $target_repeat_end->setTimestamp(
                        $this->target_semester->vorles_ende
                    );
                } else {
                    $target_repeat_end = $target_repeat_end->add(
                        $repeat_duration
                    );
                    if ($target_repeat_end >= $this->target_semester->vorles_ende) {
                        $target_repeat_end->setTimestamp(
                            $this->target_semester->vorles_ende
                        );
                    }
                }

                $copy_data = [
                    'sem_week_number' => $begin_sem_week_number,
                    'copy' => null,
                    'available' => null,
                    'original' => $booking,
                    'time_intervals' => []
                ];

                $copy = new ResourceBooking();
                $copy->resource_id = $booking->resource_id;
                $copy->range_id = $booking->range_id;
                $copy->booking_user_id = $GLOBALS['user']->id;
                $copy->description = $booking->description;
                $copy->begin = $target_begin->getTimestamp() +
                               $booking->preparation_time;
                $copy->end = $target_end->getTimestamp();
                $copy->preparation_time = $booking->preparation_time;
                $copy->booking_type = $booking->booking_type;
                $copy->repeat_end = $target_repeat_end->getTimestamp();
                $copy->repetition_interval = $booking->repetition_interval;
                $copy->internal_comment = $booking->internal_comment;
                if ($this->step == 3) {
                    //We only need to call validate when we are really
                    //trying to check if the booking can be made.
                    //After step 3, we don't need to call validate manually
                    //since it is automatically called before storing.
                    //Furthermore, the availability flag isn't important
                    //anymore after step 3.
                    $time_intervals = $copy->calculateTimeIntervals();
                    if (!$time_intervals) {
                        //The copied booking will have no time intervals.
                        //So we can skip to the next one.
                        continue;
                    }
                    $copy_data['time_intervals'] = $copy->calculateTimeIntervals();
                    try {
                        $copy->validate();
                        $copy_data['available'] = true;
                        $available_booking_c++;
                    } catch (Exception $e) {
                        $copy_data['available'] = false;
                    }
                }
                $copy_data['copy'] = $copy;
                $this->booking_copy_data[$booking->id] = $copy_data;
            }
            if (Request::submitted('download_booking_list')) {
                $csv_data = [
                    [
                        _('Buchungsnummer'),
                        _('Buchungszeitraum'),
                        _('Raum'),
                        _('Verfügbar')
                    ]
                ];
                $booking_c = 1;
                foreach ($this->booking_copy_data as $data) {
                    foreach ($data['time_intervals'] as $interval) {
                        $time_range = sprintf(
                            '%1$s - %2$s',
                            date('d.m.Y H:i', $interval['begin']),
                            date('d.m.Y H:i', $interval['end'])