Skip to content
Snippets Groups Projects
ResourceBooking.class.php 67.2 KiB
Newer Older
<?php

/**
 * ResourceBooking.class.php - model class for resource bookings
 *
 * 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>
 * @copyright   2017-2019
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
 * @package     resources
 * @since       4.5
 */


/**
 * The ResourceBooking class is responsible for storing
 * bookings of resources in a specified time range
 * or a time interval.
 *
 * @property string id database column
 * @property string resource_id database column
 * @property string range_id database column
 *     The user, course etc. where the booking (booking)
 *     is associated with.
 * @property string booking_user_id database column
 *     The user who created the booking (booking).
 * @property string description database column
 * @property string begin database column
 * @property string end database column
 * @property string booking_type database column: The booking type.
 *     The following types are defined:
 *     0 = normal booking
 *     1 = reservation
 *     2 = lock
 *     3 = planned booking (reservation from external tools)
 *
 * @property string repeat_end database column
 * @property string repeat_quantity database column
 * @property string repetition_interval database column
 *     The repetition_interval column contains a date interval string in a
 *     format that is accepted by the DateInterval class constructor.
 *     Examples for values of the repetition_interval column:
 *     - For an one month interval, the value is "P1M".
 *     - For an interval of two days, the value is "P2D".
 *     See the DateInterval documentation for more examples:
 *     https://secure.php.net/manual/en/class.dateinterval.php
 *
 * @property string internal_comment database column
 * @property string mkdate database column
 * @property string chdate database column
 * @property Resource resource belongs_to Resource
 * @property User assigned_user belongs_to User
 * @property CourseDate assigned_course_date belongs_to CourseDate
 */
class ResourceBooking extends SimpleORMap implements PrivacyObject, Studip\Calendar\EventSource
{
    private $assigned_user_type;

    protected static function configure($config = [])
    {
        $config['db_table'] = 'resource_bookings';

        $config['belongs_to']['resource'] = [
            'class_name' => 'Resource',
            'foreign_key' => 'resource_id',
            'assoc_func' => 'find'
        ];
        $config['belongs_to']['assigned_user'] = [
            'class_name' => 'User',
            'foreign_key' => 'range_id',
            'assoc_func' => 'find'
        ];
        $config['belongs_to']['assigned_course_date'] = [
            'class_name' => 'CourseDate',
            'foreign_key' => 'range_id',
            'assoc_func' => 'find'
        ];
        $config['has_many']['time_intervals'] = [
            'class_name' => 'ResourceBookingInterval',
            'assoc_foreign_key' => 'booking_id',
            'on_delete' => 'delete'
        ];
        $config['belongs_to']['booking_user'] = [
            'class_name' => 'User',
            'foreign_key' => 'booking_user_id',
            'assoc_func' => 'find'
        ];

        $config['additional_fields']['course_id'] = ['assigned_course_date', 'range_id'];
        $config['additional_fields']['room_name'] = ['resource', 'name'];

        $config['registered_callbacks']['after_store'][] = 'updateIntervals';
        $config['registered_callbacks']['after_store'][] = 'createStoreLogEntry';
        $config['registered_callbacks']['after_delete'][] = 'sendDeleteNotification';
        $config['registered_callbacks']['after_delete'][] = 'createDeleteLogEntry';

        //In regard to TIC 6460:
        //As long as TIC 6460 is not implemented, we must add the validate
        //method as a callback before storing the object.
        if (!method_exists('SimpleORMap', 'validate')) {
            $config['registered_callbacks']['before_store'][] = 'validate';
        }

        parent::configure($config);
    }


    public function createStoreLogEntry()
    {
        if ($this->isSimpleBooking()) {
            StudipLog::log(
                'RES_ASSIGN_SINGLE',
                $this->resource_id,
                null,
                $this->__toString(),
                null,
                $GLOBALS['user']->id
            );
        } else {
            StudipLog::log(
                'RES_ASSIGN_SEM',
                $this->resource_id,
André Noack's avatar
André Noack committed
                $this->course_id,
                $this->__toString(),
                null,
                $GLOBALS['user']->id
            );
        }
    }


    public function createDeleteLogEntry()
    {
        if ($this->isSimpleBooking()) {
            StudipLog::log(
                'RES_ASSIGN_DEL_SINGLE',
                $this->resource_id,
                null,
                $this->__toString(),
                null,
                $GLOBALS['user']->id
            );
        } else {
            StudipLog::log(
                'RES_ASSIGN_DEL_SEM',
                $this->resource_id,
André Noack's avatar
André Noack committed
                $this->course_id,
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
                $this->__toString(),
                null,
                $GLOBALS['user']->id
            );
        }
    }


    /**
     * Internal method that generated the SQL query used in
     * findByResourceAndTimeRanges and countByResourceAndTimeRanges.
     *
     * @see findByResourceAndTimeRanges
     * @inheritDoc
     */
    protected static function buildResourceAndTimeRangesSqlQuery(
        Resource $resource,
        $time_ranges = [],
        $booking_types = [],
        $excluded_booking_ids = []
    )
    {
        if (!is_array($time_ranges)) {
            throw new InvalidArgumentException(
                _('Es wurde keine Liste mit Zeiträumen angegeben!')
            );
        }

        //Check the array:
        foreach ($time_ranges as $time_range) {
            if ($time_range['begin'] > $time_range['end']) {
                throw new InvalidArgumentException(
                    _('Der Startzeitpunkt darf nicht hinter dem Endzeitpunkt liegen!')
                );
            }

            if ($time_range['begin'] == $time_range['end']) {
                throw new InvalidArgumentException(
                    _('Startzeitpunkt und Endzeitpunkt dürfen nicht identisch sein!')
                );
            }
        }

        $sql_params = [
            'resource_id' => $resource->id
        ];

        //First we build the SQL snippet for the case that the $booking_type
        //variable is set to something different than null.
        $booking_type_sql = '';
        if (is_array($booking_types) && count($booking_types)) {
            $booking_type_sql = ' AND booking_type IN ( :booking_types )';
            $sql_params['booking_types'] = $booking_types;
        }

        //Then we build the snippet for excluded booking IDs, if specified.
        $excluded_booking_ids_sql = '';
        if (is_array($excluded_booking_ids) && count($excluded_booking_ids)) {
            $excluded_booking_ids_sql = ' AND resource_booking_intervals.booking_id NOT IN ( :excluded_ids ) ';
            $sql_params['excluded_ids'] = $excluded_booking_ids;
        }

        //Now we build the SQL snippet for the time intervals.
        //These are repeated four times in the query below.
        //First we use one template ($time_sql_template) and
        //replace NUMBER with our counting variable $i.
        //BEGIN and END are replaced below since the columns for
        //BEGIN and END are different in the four cases where we
        //repeat the SQL snippet for the time intervals.
        $time_sql_template = '
            (resource_booking_intervals.begin < :endNUMBER AND :beginNUMBER < resource_booking_intervals.end)
            ';

        $time_sql = '';
        if ($time_ranges) {
            $time_sql = ' AND (';

            $i = 1;
            foreach ($time_ranges as $time_range) {
                if ($i > 1) {
                    $time_sql .= ' OR ';
                }
                $time_sql .= str_replace(
                    'NUMBER',
                    $i,
                    $time_sql_template
                );

                if ($time_range['begin'] instanceof DateTime) {
                    $sql_params[('begin' . $i)] = $time_range['begin']->getTimestamp();
                } else {
                    $sql_params[('begin' . $i)] = $time_range['begin'];
                }
                if ($time_range['end'] instanceof DateTime) {
                    $sql_params[('end' . $i)] = $time_range['end']->getTimestamp();
                } else {
                    $sql_params[('end' . $i)] = $time_range['end'];
                }

                $i++;
            }

            $time_sql .= ') ';
        }

        //Check if the booking has a start and end timestamp set
        //or if it has repetitions that have a matching timestamp.
        //This is done in the rest of the SQL query:

        $whole_sql = "resource_bookings.id IN (
                    SELECT resource_booking_intervals.booking_id FROM resource_booking_intervals WHERE
                    resource_booking_intervals.resource_id = :resource_id
                    AND resource_booking_intervals.takes_place = 1"
                    . $excluded_booking_ids_sql
                    . $time_sql
                    . " GROUP BY resource_booking_intervals.booking_id ORDER BY NULL)
                    $booking_type_sql
";

        return [
            'sql' => $whole_sql,
            'params' => $sql_params
        ];
    }


    /**
     * Retrieves all resource booking for the given resource and
     * time range. By default, all booking are returned.
     * To get only bookings of a certain type
     * set the $booking_type parameter.
     *
     * @param Resource $resource The resource whose requests shall be retrieved.
     * @param array $time_ranges An array with time ranges as DateTime objects.
     *     The array has the following structure:
     *     [
     *         [
     *             'begin' => begin timestamp,
     *             'end' => end timestamp
     *         ],
     *         ...
     *     ]
     * @param array $booking_types An optional specification for the
     *     booking_type column in the database. More than one booking
     *     type can be specified.
     *     By default this is set to an empty array which means
     *     that resource booking are not filtered by the type column.
     *     The allowed resource booking types are specified in the
     *     class documentation.
     *
     * @param array $excluded_booking_ids An array of strings representing
     *     resource booking IDs. IDs specified in this array are excluded
     *     from the search.
     * @return ResourceBooking[] An array of ResourceRequest objects.
     *     If no requests can be found, the array is empty.
     *
     * @throws InvalidArgumentException, if the time ranges are either not in an
     *     array matching the format description from above or if one of the
     *     following conditions is met in one of the time ranges:
     *     - begin > end
     *     - begin == end
     */
    public static function findByResourceAndTimeRanges(
        Resource $resource,
        $time_ranges = [],
        $booking_types = [],
        $excluded_booking_ids = []
    )
    {
        //Build the SQL query and the parameter array.

        $sql_data = self::buildResourceAndTimeRangesSqlQuery(
            $resource,
            $time_ranges,
            $booking_types,
            $excluded_booking_ids
        );

        //Call findBySql:
        return self::findBySql($sql_data['sql'], $sql_data['params']);
    }


    /**
     * Counts all resource bookings for the specified resource and
     * time range. By default, all bookings are counted.
     * To count only bookings of a certain type
     * set the $booking_type parameter.
     *
     * @see findByResourceAndTimeRanges
     * @inheritDoc
     */
    public static function countByResourceAndTimeRanges(
        Resource $resource,
        $time_ranges = [],
        $booking_types = [],
        $excluded_booking_ids = []
    )
    {
        //Build the SQL query and the parameter array.

        $sql_data = self::buildResourceAndTimeRangesSqlQuery(
            $resource,
            $time_ranges,
            $booking_types,
            $excluded_booking_ids
        );

        //Call countBySql:
        return self::countBySql($sql_data['sql'], $sql_data['params']);
    }


    /**
     * Deletes all resource bookings for the specified resource and
     * time range. By default, all bookings are counted.
     * To count only bookings of a certain type
     * set the $booking_type parameter.
     *
     * @see findByResourceAndTimeRanges
     * @inheritDoc
     */
    public static function deleteByResourceAndTimeRanges(
        Resource $resource,
        $time_ranges = [],
        $booking_types = [],
        $excluded_booking_ids = []
    )
    {
        //Build the SQL query and the parameter array.
        $sql_data = self::buildResourceAndTimeRangesSqlQuery(
            $resource,
            $time_ranges,
            $booking_types,
            $excluded_booking_ids
        );

        //Call deleteBySql:
        return self::deleteBySql($sql_data['sql'], $sql_data['params']);
    }


    /**
     * The SimpleORMap::store method is overloaded to allow forced booking
     * of resource bookings, meaning that all other bookings of the
     * resource of a booking are deleted when they overlap with this booking.
     *
     * @param bool $force_booking Whether booking shall be forced (true)
     *     or not (false). Defaults to false.
     * @return bool
     */
    public function store($force_booking = false)
    {
        if ($force_booking == true) {
            $this->deleteOverlappingBookings();
        }
        $this->deleteOverlappingReservations();

        if (parent::store()) {
            //Check if the booking is bound to a course date.
            //If this is the case, check for existing bookings
            //and delete them, so that there is only one booking
            //for a course date:
            $course_date_exists = CourseDate::exists($this->range_id);
            if ($course_date_exists) {
                self::deleteBySql(
                    'range_id = :range_id AND id <> :this_id',
                    [
                        'this_id' => $this->id,
                        'range_id' => $this->range_id
                    ]
                );
            }
            return true;
        }
        return false;
    }


    /**
     * This validation method is called before storing an object.
     */
    public function validate()
    {
        if ((!$this->resource_id) || !($this->resource instanceof Resource)) {
            throw new InvalidArgumentException(
                _('Es wurde keine Ressource zur Buchung angegeben!')
            );
        }

        if (!$this->range_id && !$this->description) {
            throw new ResourceBookingRangeException(
                _('Es muss eine Person oder ein Text zur Buchung eingegeben werden!')
            );
        }

        if ((!$this->booking_user_id) || !($this->booking_user instanceof User)) {
            /*throw new InvalidArgumentException(
                _('Die buchende Person wurde nicht gesetzt!')
            );*/
            $this->booking_user = User::findCurrent();
        }

        if ($this->begin >= $this->end) {
            throw new InvalidArgumentException(
                _('Der Startzeitpunkt darf nicht hinter dem Endzeitpunkt liegen!')
            );
        }

        if ($this->repetition_interval) {
            if (!($this->repeat_quantity || $this->repeat_end)) {
                throw new InvalidArgumentException(
                    _('Es wurde ein Wiederholungsintervall ohne Begrenzung angegeben!')
                );
            }
            if ((!$this->repeat_quantity) && ($real_begin > $this->repeat_end)) {
                throw new InvalidArgumentException(
                    _('Der Startzeitpunkt darf nicht hinter dem Ende der Wiederholungen liegen!')
                );
            }
        }

        //Check if the user has booking rights on the resource.
        //The user must have either permanent permissions or they have to
        //have booking rights by a temporary permission in this moment
        //(the moment this booking is saved).
        $derived_resource = $this->resource->getDerivedClassInstance();
        $user_has_booking_rights = $derived_resource->userHasBookingRights(
            $this->booking_user
        );
        if (!$user_has_booking_rights) {
            throw new ResourcePermissionException(
                sprintf(
                    _('Unzureichende Berechtigungen zum Buchen der Ressource %s!'),
                    $this->resource->name
                )
            );
        }

        $time_intervals = $this->calculateTimeIntervals(true);
        $time_interval_overlaps = [];
        foreach ($time_intervals as $time_interval) {
            $is_locked = $derived_resource->isLocked(
                $time_interval['begin'],
                $time_interval['end'],
                ($this->isNew() ? [] : [$this->id])
            );
            if ($is_locked) {
                if ($time_interval['begin']->format('Ymd') == $time_interval['end']->format('Ymd')) {
                    $time_interval_overlaps[] = sprintf(
                        _('Gesperrt im Bereich vom %1$s bis %2$s'),
                        $time_interval['begin']->format('d.m.Y H:i'),
                        $time_interval['end']->format('H:i')
                    );
                } else {
                    $time_interval_overlaps[] = sprintf(
                        _('Gesperrt im Bereich vom %1$s bis zum %2$s'),
                        $time_interval['begin']->format('d.m.Y H:i'),
                        $time_interval['end']->format('d.m.Y H:i')
                    );
                }
            } else {
                $is_assigned = $derived_resource->isAssigned(
                    $time_interval['begin'],
                    $time_interval['end'],
                    ($this->isNew() ? [] : [$this->id])
                );
                if ($is_assigned) {
                    if ($time_interval['begin']->format('Ymd') == $time_interval['end']->format('Ymd')) {
                        $time_interval_overlaps[] = sprintf(
                            _('Gebucht im Bereich vom %1$s bis %2$s'),
                            $time_interval['begin']->format('d.m.Y H:i'),
                            $time_interval['end']->format('H:i')
                        );
                    } else {
                        $time_interval_overlaps[] = sprintf(
                            _('Gebucht im Bereich vom %1$s bis zum %2$s'),
                            $time_interval['begin']->format('d.m.Y H:i'),
                            $time_interval['end']->format('d.m.Y H:i')
                        );
                    }
                }
            }
        }
        if ($time_interval_overlaps) {
            throw new ResourceBookingOverlapException(
                implode(', ', $time_interval_overlaps)
            );
        }

        NotificationCenter::postNotification('ResourceBookingWillValidate', $this);
    }


    /**
     * This method updates the intervals of this resource booking
     * which are stored in the resource_booking_intervals table.
     */
    public function updateIntervals($keep_exceptions = true)
    {
        if ($keep_exceptions) {
            //Delete all intervals with takes_place > 0
            //and update the time intervals of the exceptions:
            ResourceBookingInterval::deleteBySql(
                "booking_id = :booking_id
                AND
                takes_place > '0'",
                [
                    'booking_id' => $this->id
                ]
            );

            //Get all interval exceptions:
            $exceptions = ResourceBookingInterval::findBySql(
                "booking_id = :booking_id
                AND
                takes_place < '1'",
                [
                    'booking_id' => $this->id
                ]
            );

            if ($exceptions) {
                //Now we must compare the time intervals of the booking
                //with the time intervals of the exceptions.
                //If there is only a difference in hours we update
                //the exceptions. Otherwise we delete the exceptions.

                $repetition_interval = $this->getRepetitionInterval();
                if (!$repetition_interval) {
                    //No repetition interval also means nothing left to do.
                    return;
                }

                $repetition_begin = new DateTime();
                $repetition_begin->setTimestamp($this->begin - $this->preparation_time);
                $date_end = new DateTime();
                $date_end->setTimestamp($this->end);
                $repetition_end = new DateTime();
                $repetition_end->setTimestamp($this->repeat_end);
                $repetition_interval = $this->getRepetitionInterval();

                $duration = $repetition_begin->diff($date_end);

                //Loop over all exceptions and check if they belong to
                //one of the repetions:

                $obsolete_exception_ids = [];
                foreach ($exceptions as $exception) {
                    $exception_begin = new DateTime();
                    $exception_begin->setTimestamp($exception->begin);
                    $exception_end = new DateTime();
                    $exception_end->setTimestamp($exception->end);
                    $exc_begin_str = $exception_begin->format('Y-m-d');
                    $exc_end_str = $exception_end->format('Y-m-d');

                    $exception_obsolete = true;

                    $current_repetition = clone $repetition_begin;
                    while ($current_repetition < $repetition_end) {
                        $current_end = clone $current_repetition;
                        $current_end->add($duration);

                        $current_begin_str = $current_repetition->format('Y-m-d');
                        $current_end_str = $current_end->format('Y-m-d');

                        if ($current_begin_str == $exc_begin_str && $current_end_str == $exc_end_str) {
                            //We found one exception which needs to be updated.
                            $exception_obsolete = false;
                            $exception->begin = $current_repetition->getTimestamp();
                            $exception->end = $current_end->getTimestamp();
                            if ($exception->isDirty()) {
                                $exception->store();
                            }
                            //No need to loop the rest of the repetitions:
                            break;
                        }

                        $current_repetition->add($repetition_interval);
                    }

                    if ($exception_obsolete) {
                        $obsolete_exception_ids[] = $exception->id;
                    }
                }

                if ($obsolete_exception_ids) {
                    ResourceBookingInterval::deleteBySql(
                        'interval_id IN ( :ids )',
                        [
                            'ids' => $obsolete_exception_ids
                        ]
                    );
                }
            }
        } else {
            //We delete all existing intervals for this booking
            //and re-create them.
            ResourceBookingInterval::deleteBySql(
                'booking_id = :booking_id',
                [
                    'booking_id' => $this->id
                ]
            );
        }

        ResourceBookingInterval::createFromBooking($this);
    }


    /**
     * Deletes the ResourceBooking object if there are no
     * ResourceBookingInterval objects attachted to it.
     *
     * @return null|bool If the ResourceBooking object still has
     *     ResourceBookingInterval objects attachted to it,
     *     null is returned. Otherwise the return value of the
     *     SimpleORMap::delete method for the ResourceBooking object
     *     is returned.
     */
    public function deleteIfNoInterval()
    {
        $intervals = ResourceBookingInterval::countBySql(
            'booking_id = :id',
            [
                'id' => $this->id
            ]
        );
        if ($intervals == 0) {
            return $this->delete();
        }

        return null;
    }


    /**
     * Deletes all bookings in the time ranges of this resource booking.
     * Such bookings would prevent saving this booking.
     *
     * @return int The amount of deleted bookings.
     */
    public function deleteOverlappingBookings()
    {
        $real_begin = new DateTime();
        $real_begin->setTimestamp($this->begin - $this->preparation_time);
        $end = new DateTime();
        $end->setTimestamp($this->end);
        $repetition_end = new DateTime();
        $repetition_end->setTimestamp($this->repeat_end);

        $deleted_c = 0;
        if ($this->repetition_interval) {
            $repetition_interval = $this->getRepetitionInterval();

            if (!($this->repeat_quantity || $this->repeat_end)) {
                throw new InvalidArgumentException(
                    _('Es wurde ein Wiederholungsintervall ohne Begrenzung angegeben!')
                );
            }
            if ((!$this->repeat_quantity) && ($real_begin > $this->repeat_end)) {
                throw new InvalidArgumentException(
                    _('Der Startzeitpunkt darf nicht hinter dem Ende der Wiederholungen liegen!')
                );
            }

            //Look in each repetition for overlapping bookings and delete them.
            $current_date = clone $real_begin;
            while ($current_date <= $repetition_end) {
                $current_begin = clone $current_date;
                $current_end = clone $current_date;
                $current_end->setTime(
                    intval($end->format('H')),
                    intval($end->format('i')),
                    intval($end->format('s'))
                );
                $derived_resource = $this->resource->getDerivedClassInstance();
                if ($derived_resource->userHasPermission($this->booking_user, 'tutor', [$current_begin, $current_end])) {
                    //Sufficient permissions to delete bookings
                    //in the time frame.
                    $delete_sql = '(begin BETWEEN :begin AND :end
                        OR
                        end BETWEEN :begin AND :end)
                        AND
                        resource_id = :resource_id ';
                    $sql_params = [
                        'begin' => $current_begin->getTimestamp(),
                        'end' => $current_end->getTimestamp(),
                        'resource_id' => $this->resource->id
                    ];
                    if (!$this->isNew()) {
                        $delete_sql .= 'booking_id <> :booking_id';
                        $sql_params['booking_id'] = $this->id;
                    }
                    $intervals = ResourceBookingInterval::findBySQL(
                        $delete_sql,
                        $sql_params
                    );

                    $affected_bookings = [];
                    foreach ($intervals as $interval) {
                        if ($interval->booking instanceof ResourceBooking) {
                            $affected_bookings[$interval->booking_id] = $interval->booking;
                        }
                        $deleted_c += $interval->delete();
                    }

                    foreach ($affected_bookings as $booking) {
                        $booking->deleteIfNoInterval();
                    }
                }
                $current_date = $current_date->add($repetition_interval);
            }
        } else {
            $derived_resource = $this->resource->getDerivedClassInstance();
            if ($derived_resource->userHasPermission($this->booking_user, 'autor', [$real_begin, $end])) {
                $delete_sql = '(begin BETWEEN :begin AND :end
                    OR
                    end BETWEEN :begin AND :end)
                    AND
                    resource_id = :resource_id ';
                $sql_params = [
                    'begin' => $real_begin->getTimestamp(),
                    'end' => $end->getTimestamp(),
                    'resource_id' => $this->resource->id
                ];
                if (!$this->isNew()) {
                    $delete_sql .= 'booking_id <> :booking_id';
                    $sql_params['booking_id'] = $this->id;
                }
                $intervals = ResourceBookingInterval::findBySQL(
                    $delete_sql,
                    $sql_params
                );
                $affected_bookings = [];
                foreach ($intervals as $interval) {
                    if ($interval->booking instanceof ResourceBooking) {
                        $affected_bookings[$interval->booking_id] = $interval->booking;
                    }
                    $deleted_c += $interval->delete();
                }

                foreach ($affected_bookings as $booking) {
                    $booking->deleteIfNoInterval();
                }
            }
        }

        return $deleted_c;
    }


    /**
     * Deletes all reservations in the time ranges of this resource booking.
     *
     * @return int The amount of deleted reservations.
     */
    public function deleteOverlappingReservations()
    {
        //Notify all persons who made reservations or who are assigned
        //to the reservation about the new booking which overwrites
        //their reservation:
        $booking_resource = Resource::find($this->resource_id);
        $booking_user = User::find($this->booking_user_id);

        $real_begin = new DateTime();
        $real_begin->setTimestamp($this->begin - $this->preparation_time);
        $end = new DateTime();
        $end->setTimestamp($this->end);

        $deleted_c = 0;

        $template_factory = new Flexi_TemplateFactory(
            $GLOBALS['STUDIP_BASE_PATH'] . '/locale/'
        );

        $affected_reservations =  ResourceBooking::findByResourceAndTimeRanges(
            $booking_resource,
            [
                [
                    'begin' => $real_begin->getTimestamp(),
                    'end' => $end->getTimestamp(),
                ]
            ],
            [1, 3],
            [$this->id]
        );
        foreach ($affected_reservations as $reservation) {
            if ($reservation->id == $this->id) {
                continue;
            }
            if ($reservation->assigned_user && (
                $reservation->range_id != $reservation->booking_user_id
            )) {
                //Inform the person who is assigned to the reservation:
                setTempLanguage($reservation->assigned_user->id);
                $lang_path = getUserLanguagePath($reservation->assigned_user->id);

                $template = $template_factory->open(
                    $lang_path . '/LC_MAILS/overbooked_reservation.php'
                );
                $template->set_attribute('resource', $booking_resource);
                $template->set_attribute('reservation', $reservation);
                $template->set_attribute('booking_user', $booking_user);
                $mail_text = $template->render();

                Message::send(
                    '____%system%____',
                    [$reservation->assigned_user->username],
                    _('Reservierung überbucht'),
                    $mail_text
                );

                restoreLanguage();
            }
            if ($reservation->booking_user) {
                //Inform the person who made the reservation:
                setTempLanguage($reservation->booking_user->id);
                $lang_path = getUserLanguagePath($reservation->booking_user->id);

                $template = $template_factory->open(
                    $lang_path . '/LC_MAILS/overbooked_reservation.php'
                );
                $template->set_attribute('resource', $booking_resource);
                $template->set_attribute('reservation', $reservation);
                $template->set_attribute('booking_user', $booking_user);
                $mail_text = $template->render();

                Message::send(
                    '____%system%____',
                    [$reservation->booking_user->username],
                    _('Reservierung überbucht'),
                    $mail_text
                );

                restoreLanguage();
            }

            //Delete the reservation:
            $deleted_c += $reservation->delete();
        }
        return $deleted_c;
    }


    /**
     * Determines whether the resource booking ends on the same timestamp
     * like the lecture time of one of the defined semesters.
     *
     * @return True, if the resource booking ends with a semester,
     *     false otherwise.
     */
    public function endsWithSemester()
    {
        return Semester::countBySql(
            '(beginn <= :begin) AND (ende >= :begin)
             AND vorles_ende = :repeat_end',
            [
                'begin' => $this->begin,
                'repeat_end' => $this->repeat_end
            ]
        ) > 0;
    }


    /**
     * Check if the specified user is the owner of the booking.
     *
     * @param User $user The user whose ownership shall be tested.
     *
     * @return bool True, if the specified user is the owner of the booking,
     *     false otherwise.
     */
    public function userIsOwner(User $user)
    {
        return $this->booking_user_id == $user->id;
    }


    /**
     * Determines wheter the booking is read only for a specified user.
     *
     * @param User $user The user whose permissions shall be checked.
     *
     * @return bool True, if the specified user may only perform reading
     *     actions on the booking, false otherwise.
     */
    public function isReadOnlyForUser(User $user)
    {
        if ($this->isSimpleBooking()) {
            //In case it is a simple booking, one has to be
            //either resource tutor or the owner of the request.
            if ($this->userIsOwner($user)) {
                return false;
            }
            //Still no answer? Check, if the user is resource tutor.
            $derived_resource = $this->resource->getDerivedClassInstance();
            return !$derived_resource->userHasPermission($user, 'tutor');
        }
        //Non-simple bookings (course bookings etc.) are always read-only.
        return true;
    }


    /**
     * Determines whether this resource booking has a repetition in the
     * specified time range.
     * @param DateTime $begin
     * @param DateTime $end
     * @return bool True, if the booking has repetitions in the timeframe
     * specified by $begin and $end, false otherwise.
     */
    public function isRepetitionInTimeframe(DateTime $begin, DateTime $end)
    {
        return ResourceBookingInterval::countBySql(
            "booking_id = :booking_id
            AND (
                (begin BETWEEN :begin AND :end)
                OR
                (end BETWEEN :begin AND :end)
                OR
                (begin < :begin AND end > :end)
            )
            AND NOT (
                (begin BETWEEN :booking_begin AND :booking_end)
                OR
                (end BETWEEN :booking_begin AND :booking_end)
                OR
                (begin < :booking_begin AND end > :booking_end)
            )",
            [
                'booking_id' => $this->id,
                'begin' => $begin->getTimestamp(),
                'end' => $end->getTimestamp(),
                'booking_begin' => $this->begin,
                'booking_end' => $this->end
            ]
        ) > 0;
    }


    /**
     * Returns the DateInterval object according to the set repetition
     * interval of this resource booking object.
     *
     * @return DateInterval|null A DateInterval object or null,