Skip to content
Snippets Groups Projects
Seminar.class.php 89.2 KiB
Newer Older
<?
# Lifter002: TODO
# Lifter003: TEST
# Lifter007: TODO
# Lifter010: TODO
/**
 * Seminar.class.php - This class represents a Seminar in Stud.IP
 *
 * This class provides functions for seminar-members, seminar-dates, and seminar-modules
 *
 * 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      Till Glöggler <tgloeggl@uni-osnabrueck.de>
 * @author      Stefan Suchi <suchi@data-quest>
 * @author      Suchi & Berg GmbH <info@data-quest.de>
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
 */

require_once 'lib/dates.inc.php';

class Seminar
{
    var $issues = null;                 // Array of Issue
    var $irregularSingleDates = null;   // Array of SingleDates
    var $messages = [];            // occured errors, infos, and warnings
    var $semester = null;
    var $filterStart = 0;
    var $filterEnd = 0;
    var $hasDatesOutOfDuration = -1;
    var $message_stack = [];

    var $user_number = 0;//?
    var $commands; //?
    var $BookedRoomsStatTemp; //???

    var $request_id;//TODO
    var $requestData;
    var $room_request;

    private $_metadate = null;               // MetaDate

    private $alias = [
        'seminar_number' => 'VeranstaltungsNummer',
        'subtitle' => 'Untertitel',
        'description' => 'Beschreibung',
        'location' => 'Ort',
        'misc' => 'Sonstiges',
        'read_level' => 'Lesezugriff',
        'write_level' => 'Schreibzugriff',
        'semester_start_time' => 'start_time',
        'semester_duration_time' => 'duration_time',
        'form' => 'art',
        'participants' => 'teilnehmer',
        'requirements' => 'vorrausetzungen',
        'orga' => 'lernorga',
    ];

    private $course = null;

    private $course_set = null;

    private static $seminar_object_pool;

    public static function GetInstance($id = false, $refresh_cache = false)
    {
        if ($id) {
            if ($refresh_cache) {
                self::$seminar_object_pool[$id] = null;
            }
Moritz Strohm's avatar
Moritz Strohm committed
            if (!empty(self::$seminar_object_pool[$id]) && is_object(self::$seminar_object_pool[$id]) && self::$seminar_object_pool[$id]->getId() == $id) {
                return self::$seminar_object_pool[$id];
            } else {
                self::$seminar_object_pool[$id] = new Seminar($id);
                return self::$seminar_object_pool[$id];
            }
        } else {
            return new Seminar(false);
        }
    }

    public static function setInstance(Seminar $seminar)
    {
        return self::$seminar_object_pool[$seminar->id] = $seminar;
    }

    /**
     * Constructor
     *
     * Pass nothing to create a seminar, or the seminar_id from an existing seminar to change or delete
     * @access   public
     * @param    string  $seminar_id the seminar to be retrieved
     */
    public function __construct($course_or_id = FALSE)
    {
        $course = Course::toObject($course_or_id);
        if ($course) {
            $this->course = $course;
        } elseif ($course_or_id === false) {
            $this->course = new Course();
            $this->course->setId($this->course->getNewId());
        } else { //hmhmhm
            throw new Exception(sprintf(_('Fehler: Konnte das Seminar mit der ID %s nicht finden!'), $course_or_id));
        }
    }

    public function __get($field)
    {
        if ($field == 'is_new') {
            return $this->course->isNew();
        }
        if ($field == 'metadate') {
            if ($this->_metadate === null) {
                $this->_metadate = new MetaDate($this->id);
                $this->_metadate->setSeminarStartTime($this->start_time);
                $this->_metadate->setSeminarDurationTime($this->duration_time);
            }
            return $this->_metadate;
        }
        if(isset($this->alias[$field])) {
            $field = $this->alias[$field];
        }
        return $this->course->$field;
    }

    public function __set($field, $value)
    {
        if(isset($this->alias[$field])) {
            $field = $this->alias[$field];
        }
        if ($field == 'metadate') {
            return $this->_metadate = $value;
        }
        return $this->course->$field = $value;
    }

    public function __isset($field)
    {
        if ($field == 'metadate') {
            return is_object($this->_metadate);
        }
        if(isset($this->alias[$field])) {
            $field = $this->alias[$field];
        }
        return isset($this->course->$field);
    }

    public function __call($method, $params)
    {
        return call_user_func_array([$this->course, $method], $params);
    }

    public static function GetSemIdByDateId($date_id)
    {
        $stmt = DBManager::get()->prepare("SELECT range_id FROM termine WHERE termin_id = ? LIMIT 1");
        $stmt->execute([$date_id]);
        return $stmt->fetchColumn();
    }

    /**
     *
     * creates an new id for this object
     * @access   private
     * @return   string  the unique id
     */
    public function createId()
    {
        return $this->course->getNewId();
    }

    public function getMembers($status = 'dozent')
    {
        $ret = [];
        foreach($this->course->getMembersWithStatus($status) as $m) {
            $ret[$m->user_id]['user_id'] = $m->user_id;
            $ret[$m->user_id]['username'] = $m->username;
            $ret[$m->user_id]['Vorname'] = $m->vorname;
            $ret[$m->user_id]['Nachname'] = $m->nachname;
            $ret[$m->user_id]['Email'] = $m->email;
            $ret[$m->user_id]['position'] = $m->position;
            $ret[$m->user_id]['label'] = $m->label;
            $ret[$m->user_id]['status'] = $m->status;
            $ret[$m->user_id]['mkdate'] = $m->mkdate;
            $ret[$m->user_id]['fullname'] = $m->getUserFullname();
        }
        return $ret;
    }

    public function getAdmissionMembers($status = 'awaiting')
    {
        $ret = [];
        foreach($this->course->admission_applicants->findBy('status', $status)->orderBy('position nachname') as $m) {
            $ret[$m->user_id]['user_id'] = $m->user_id;
            $ret[$m->user_id]['username'] = $m->username;
            $ret[$m->user_id]['Vorname'] = $m->vorname;
            $ret[$m->user_id]['Nachname'] = $m->nachname;
            $ret[$m->user_id]['Email'] = $m->email;
            $ret[$m->user_id]['position'] = $m->position;
            $ret[$m->user_id]['status'] = $m->status;
            $ret[$m->user_id]['mkdate'] = $m->mkdate;
            $ret[$m->user_id]['fullname'] = $m->getUserFullname();
        }
        return $ret;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    /**
     * return the field VeranstaltungsNummer for the seminar
     *
     * @return  string  the seminar-number for the current seminar
     */
    public function getNumber()
    {
        return $this->seminar_number;
    }

    public function isVisible()
    {
        return $this->visible;
    }

    public function getInstitutId()
    {
        return $this->institut_id;
    }

    public function getSemesterStartTime()
    {
        return $this->semester_start_time;
    }

    public function getSemesterDurationTime()
    {
        return $this->semester_duration_time;
    }

    public function getNextDate($return_mode = 'string')
    {
        $next_date = '';
        if ($return_mode == 'int') {
            echo __class__.'::'.__function__.', line '.__line__.', return_mode "int" ist not supported by this function!';die;
        }

        if (!$termine = SeminarDB::getNextDate($this->id))
            return false;

        foreach ($termine['termin'] as $singledate_id) {
            $next_date .= DateFormatter::formatDateAndRoom($singledate_id, $return_mode) . '<br>';
        }

        if (!empty($termine['ex_termin'])) {
            foreach ($termine['ex_termin'] as $ex_termin_id) {
                $ex_termin = new SingleDate($ex_termin_id);
                $template = $GLOBALS['template_factory']->open('dates/missing_date.php');
                $template->formatted_date = DateFormatter::formatDateAndRoom($ex_termin_id, $return_mode);
                $template->ex_termin = $ex_termin;
                $missing_date = $template->render();

                if (!empty($termine['termin'])) {
                    $termin = new SingleDate($termine['termin'][0]);
                    if ($ex_termin->getStartTime() <= $termin->getStartTime()) {
                        return $next_date . $missing_date;
                    } else {
                        return $next_date;
                    }
                } else {
                    return $missing_date;
                }
            }
        } else {
            return $next_date;
        }

        return false;
    }

    public function getFirstDate($return_mode = 'string') {
        if (!$dates = SeminarDB::getFirstDate($this->id)) {
            return false;
        }

        return DateFormatter::formatDateWithAllRooms(['termin' => $dates], $return_mode);
    }

    /**
     * This function returns an associative array of the dates owned by this seminar
     *
     * @returns  mixed  a multidimensional array of seminar-dates
     */
    public function getUndecoratedData($filter = false)
    {

        // Caching
        $cache = StudipCacheFactory::getCache();
        $cache_key = 'course/undecorated_data/'. $this->id;

        if ($filter) {
            $sub_key = $_SESSION['_language'] .'/'. $this->filterStart .'-'. $this->filterEnd;
        } else {
            $sub_key = $_SESSION['_language'] .'/unfiltered';
        }

        $data = unserialize($cache->read($cache_key));

        // build cache from scratch
Moritz Strohm's avatar
Moritz Strohm committed
        if (empty($data) || empty($data[$sub_key])) {
            $cycles = $this->metadate->getCycleData();
            $dates = $this->getSingleDates($filter, $filter);
            $rooms = [];

            foreach (array_keys($cycles) as $id) {
                if ($this->filterStart && $this->filterEnd
                    && !$this->metadate->hasDates($id, $this->filterStart, $this->filterEnd))
                {
                    unset($cycles[$id]);
                    continue;
                }

                $cycles[$id]['first_date'] = CycleDataDB::getFirstDate($id);
                $cycles[$id]['last_date'] = CycleDataDB::getLastDate($id);
                if (!empty($cycles[$id]['assigned_rooms'])) {
                    foreach ($cycles[$id]['assigned_rooms'] as $room_id => $count) {
                        if (!isset($rooms[$room_id])) {
                            $rooms[$room_id] = 0;
                        }
                        $rooms[$room_id] += $count;
                    }
                }
            }

            // besser wieder mit direktem Query statt Objekten
            if (is_array($cycles) && count($cycles) === 0) {
                $cycles = false;
            }

            $ret['regular']['turnus_data'] = $cycles;

            // the irregular single-dates
            foreach ($dates as $val) {
                $zw = [
                    'metadate_id' => $val->getMetaDateID(),
                    'termin_id'   => $val->getTerminID(),
                    'date_typ'    => $val->getDateType(),
                    'start_time'  => $val->getStartTime(),
                    'end_time'    => $val->getEndTime(),
                    'mkdate'      => $val->getMkDate(),
                    'chdate'      => $val->getMkDate(),
                    'ex_termin'   => $val->isExTermin(),
                    'orig_ex'     => $val->isExTermin(),
                    'range_id'    => $val->getRangeID(),
                    'author_id'   => $val->getAuthorID(),
                    'resource_id' => $val->getResourceID(),
                    'raum'        => $val->getFreeRoomText(),
                    'typ'         => $val->getDateType(),
                    'tostring'    => $val->toString()
                ];

                if ($val->getResourceID()) {
Moritz Strohm's avatar
Moritz Strohm committed
                    if (!isset($rooms[$val->getResourceID()])) {
                        $rooms[$val->getResourceID()] = 0;
                    }
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
                    $rooms[$val->getResourceID()]++;
                }

                $ret['irregular'][$val->getTerminID()] = $zw;
            }

            $ret['rooms'] = $rooms;
            $ret['ort']   = $this->location;

            $data[$sub_key] = $ret;

            // write data to cache
            $cache->write($cache_key, serialize($data), 600);
        }

        return $data[$sub_key];
    }

    public function getFormattedTurnus($short = FALSE)
    {
        // activate this with StEP 00077
        /* $cache = Cache::instance();
         * $cache_key = "formatted_turnus".$this->id;
         * if (! $return_string = $cache->read($cache_key))
         * {
         */
        return $this->getDatesExport(['short' => $short, 'shrink' => true]);

        // activate this with StEP 00077
        // $cache->write($cache_key, $return_string, 60*60);
        // }
    }

    public function getFormattedTurnusDates($short = FALSE)
    {
        if ($cycles = $this->metadate->getCycles()) {
            $return_string = [];
            foreach ($cycles as $id => $c) {
                $return_string[$id] = $c->toString($short);
                //hmm tja...
                if ($c->description){
                    $return_string[$id] .= ' ('. htmlReady($c->description) .')';
                }
            }
            return $return_string;
        } else
            return FALSE;
    }

    public function getMetaDateCount()
    {
        return sizeof($this->metadate->cycles);
    }

    public function getMetaDateValue($key, $value_name)
    {
        return $this->metadate->cycles[$key]->$value_name;
    }

    public function setMetaDateValue($key, $value_name, $value)
    {
        $this->metadate->cycles[$key]->$value_name = $value;
    }

    /**
     * restore the data
     *
     * the complete data of the object will be loaded from the db
     * @access   public
     * @throws   Exception  if there is no such course
     * @return   boolean    always true
     */
    public function restore()
    {
        if ($this->course->id) {
            $this->course->restore();
        }
        $this->irregularSingleDates = null;
        $this->issues = null;
        $this->_metadate = null;
        $this->course_set = null;

        return TRUE;
    }

    /**
     * returns an array of variables from the seminar-object, excluding variables
     * containing objects or arrays
     *
     * @return  array
     */
    public function getSettings() {
        $settings = $this->course->toRawArray();
        unset($settings['config']);
        return $settings;
    }

    public function store($trigger_chdate = true)
    {
        // activate this with StEP 00077
        // $cache = Cache::instance();
        // $cache->expire("formatted_turnus".$this->id);

        //check for security consistency
        if ($this->write_level < $this->read_level) // hier wusste ein Lehrender nicht, was er tat
            $this->write_level = $this->read_level;

        if ($this->irregularSingleDates) {
            foreach ($this->irregularSingleDates as $val) {
                $val->store();
            }
        }

        if ($this->issues) {
            foreach ($this->issues as $val) {
                $val->store();
            }
        }

        $metadate_changed = isset($this->metadate) ? $this->metadate->store() : 0;
        $course_changed = $this->course->store();
        if ($metadate_changed && $trigger_chdate) {
            return $this->course->triggerChdate();
        } else {
            return $course_changed ?: false;
        }
    }

    public function setStartSemester($start)
    {
        global $perm;

        if ($perm->have_perm('tutor') && $start != $this->semester_start_time) {
            // logging >>>>>>
            StudipLog::log("SEM_SET_STARTSEMESTER", $this->getId(), $start);
            NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
            // logging <<<<<<
            $this->semester_start_time = $start;
            $this->metadate->setSeminarStartTime($start);
            $this->createMessage(_("Das Startsemester wurde geändert."));
            $this->createInfo(_("Beachten Sie, dass Termine, die nicht mit den Einstellungen der regelmäßigen Zeit übereinstimmen (z.B. auf Grund einer Verschiebung der regelmäßigen Zeit), teilweise gelöscht sein könnten!"));
            return TRUE;
        }
        return FALSE;
    }

    public function removeAndUpdateSingleDates()
    {
        SeminarCycleDate::removeOutRangedSingleDates(
            $this->semester_start_time,
            $this->getEndSemesterVorlesEnde(),
            $this->id
        );

        foreach ($this->metadate->cycles as $key => $val) {
            $this->metadate->cycles[$key]->readSingleDates();
            $this->metadate->createSingleDates($key);
            $this->metadate->cycles[$key]->termine = NULL;
        }
        NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
    }

    public function getStartSemester()
    {
        return $this->semester_start_time;
    }

    /*
     * setEndSemester
     * @param   end integer 0 (one Semester), -1 (eternal), or timestamp of last happening semester
     * @returns TRUE on success, FALSE on failure
     */
    public function setEndSemester($end)
    {
        global $perm;

        $previousEndSemester = $this->getEndSemester();     // save the end-semester before it is changed, so we can choose lateron in which semesters we need to be rebuilt the SingleDates

        if ($end != $this->getEndSemester()) {  // only change Duration if it differs from the current one

            if ($end == 0) {                    // the seminar takes place just in the selected start-semester
                $this->semester_duration_time = 0;
                $this->metadate->setSeminarDurationTime(0);
                // logging >>>>>>
                StudipLog::log("SEM_SET_ENDSEMESTER", $this->getId(), $end, 'Laufzeit: 1 Semester');
                // logging <<<<<<
            } else if ($end == -1) {    // the seminar takes place in every semester above and including the start-semester
                // logging >>>>>>
                StudipLog::log("SEM_SET_ENDSEMESTER", $this->getId(), $end, 'Laufzeit: unbegrenzt');
                // logging <<<<<<
                $this->semester_duration_time = -1;
                $this->metadate->setSeminarDurationTime(-1);
                SeminarCycleDate::removeOutRangedSingleDates(
                    $this->semester_start_time,
                    $this->getEndSemesterVorlesEnde(),
                    $this->id
                );
            } else {                                    // the seminar takes place  between the selected start~ and end-semester
                // logging >>>>>>
                StudipLog::log("SEM_SET_ENDSEMESTER", $this->getId(), $end);
                // logging <<<<<<
                $this->semester_duration_time = $end - $this->semester_start_time;  // the duration is stored, not the real end-point
                $this->metadate->setSeminarDurationTime($this->semester_duration_time);
            }

            $this->createMessage(_("Die Dauer wurde geändert."));
            NotificationCenter::postNotification("CourseDidChangeSchedule", $this);

            /*
             * If the duration has been changed, we have to create new SingleDates
             * if the new duration is longer than the previous one
             */
            if ( ($previousEndSemester != -1) && ( ($previousEndSemester < $this->getEndSemester()) || (($previousEndSemester == 0) && ($this->getEndSemester() == -1) ) )) {
                // if the previous duration was unlimited, the only option choosable is
                // a shorter duration then 'ever', so there cannot be any new SingleDates

                // special case: if the previous selection was 'one semester' and the new one is 'eternal',
                // than we have to find out the end of the only semester, the start-semester
                if ($previousEndSemester == 0) {
                    $startAfterTimeStamp = $this->course->start_semester->ende;
                } else {
                    $startAfterTimeStamp = $previousEndSemester;
                }

                foreach ($this->metadate->cycles as $key => $val) {
                    $this->metadate->createSingleDates(['metadate_id' => $key, 'startAfterTimeStamp' => $startAfterTimeStamp]);
                    $this->metadate->cycles[$key]->termine = NULL;  // emtpy the SingleDates for each cycle, so that SingleDates, which were not in the current view, are not loaded and therefore should not be visible
                }
            }
        }

        return TRUE;
    }

    /*
     * getEndSemester
     * @returns 0 (one Semester), -1 (eternal), or TimeStamp of last Semester for this Seminar
     */
    public function getEndSemester()
    {
        if ($this->semester_duration_time == 0) return 0;                                       // seminar takes place only in the start-semester
        if ($this->semester_duration_time == -1) return -1;                                 // seminar takes place eternally
        return $this->semester_start_time + $this->semester_duration_time;  // seminar takes place between start~ and end-semester
    }

    public function getEndSemesterVorlesEnde()
    {
        if ($this->semester_duration_time == -1) {
            $semesters = Semester::getAll();
            $very_last_semester = array_pop($semesters);
            return $very_last_semester->vorles_ende;
        }
        return $this->course->end_semester->vorles_ende;
    }

    /**
     * return the name of the seminars start-semester
     *
     * @return  string  the name of the start-semester or false if there is no start-semester
     */
    public function getStartSemesterName()
    {
        return $this->course->start_semester->name;
    }

    /**
     * return an array of singledate-objects for the submitted cycle identified by metadate_id
     *
     * @param  string  $metadate_id  the id identifying the cycle
     *
     * @return mixed   an array of singledate-objects
     */
    public function readSingleDatesForCycle($metadate_id)
    {
        return $this->metadate->readSingleDates($metadate_id, $this->filterStart, $this->filterEnd);
    }

    public function readSingleDates($force = FALSE, $filter = FALSE)
    {
        if (!$force) {
            if (is_array($this->irregularSingleDates)) {
                return TRUE;
            }
        }
        $this->irregularSingleDates = [];

        if ($filter) {
            $data = SeminarDB::getSingleDates($this->id, $this->filterStart, $this->filterEnd);
        } else {
            $data = SeminarDB::getSingleDates($this->id);
        }

        foreach ($data as $val) {
            unset($termin);
            $termin = new SingleDate();
            $termin->fillValuesFromArray($val);
            $this->irregularSingleDates[$val['termin_id']] =& $termin;
        }
    }

    public function &getSingleDate($singleDateID, $cycle_id = '')
    {
        if ($cycle_id == '') {
            $this->readSingleDates();
            return $this->irregularSingleDates[$singleDateID];
        } else {
            $dates = $this->metadate->getSingleDates($cycle_id, $this->filterStart, $this->filterEnd);
            $data =& $dates;
            return $data[$singleDateID];
        }
    }

    public function &getSingleDates($filter = false, $force = false, $include_deleted_dates = false)
    {
        $this->readSingleDates($force, $filter);
        if (!$include_deleted_dates) {
            return $this->irregularSingleDates;
        } else {
            $deleted_dates = [];
            foreach (SeminarDB::getDeletedSingleDates($this->getId(), $this->filterStart, $this->filterEnd) as $val) {
                $termin = new SingleDate();
                $termin->fillValuesFromArray($val);
                $deleted_dates[$val['termin_id']] = $termin;
            }
            $dates = array_merge($this->irregularSingleDates, $deleted_dates);
            uasort($dates, function($a,$b) {
                    if ($a->getStartTime() == $b->getStartTime()) return 0;
                    return $a->getStartTime() < $b->getStartTime() ? -1 : 1;}
            );
            return $dates;
        }
    }

    public function getCycles()
    {
        return $this->metadate->getCycles();
    }

    public function &getSingleDatesForCycle($metadate_id)
    {
        if (!$this->metadate->cycles[$metadate_id]->termine) {
            $this->metadate->readSingleDates($metadate_id, $this->filterStart, $this->filterEnd);
            if (!$this->metadate->cycles[$metadate_id]->termine) {
                $this->readSingleDates();
                $this->metadate->createSingleDates($metadate_id, $this->irregularSingleDates);
                $this->metadate->readSingleDates($metadate_id, $this->filterStart, $this->filterEnd);
            }
            //$this->metadate->readSingleDates($metadate_id, $this->filterStart, $this->filterEnd);
        }
        $dates = $this->metadate->getSingleDates($metadate_id, $this->filterStart, $this->filterEnd);
        return $dates;
    }

    public function readIssues($force = false)
    {
        if (!is_array($this->issues) || $force) {
            $this->issues = [];
            $data = SeminarDB::getIssues($this->id);

            foreach ($data as $val) {
                unset($issue);
                $issue = new Issue();
                $issue->fillValuesFromArray($val);
                $this->issues[$val['issue_id']] =& $issue;
            }
        }
    }

    public function addSingleDate(&$singledate)
    {
        // logging >>>>>>
        StudipLog::log("SEM_ADD_SINGLEDATE", $this->getId(), $singledate->toString(), 'SingleDateID: '.$singledate->getTerminID());
        // logging <<<<<<

        $cache = StudipCacheFactory::getCache();
        $cache->expire('course/undecorated_data/'. $this->getId());

        $this->readSingleDates();
        $this->irregularSingleDates[$singledate->getSingleDateID()] =& $singledate;
        NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
        return TRUE;
    }

    public function addIssue(&$issue)
    {
        $this->readIssues();
        if ($issue instanceof Issue) {
            $max = -1;
            if (is_array($this->issues)) foreach ($this->issues as $val) {
                if ($val->getPriority() > $max) {
                    $max = $val->getPriority();
                }
            }
            $max++;
            $issue->setPriority($max);
            $this->issues[$issue->getIssueID()] =& $issue;
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function deleteSingleDate($date_id, $cycle_id = '')
    {
        $this->readSingleDates();
        // logging >>>>>>
        StudipLog::log("SEM_DELETE_SINGLEDATE",$date_id, $this->getId(), 'Cycle_id: '.$cycle_id);
        // logging <<<<<<
        if ($cycle_id == '') {
            $this->irregularSingleDates[$date_id]->delete(true);
            unset ($this->irregularSingleDates[$date_id]);
            NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
            return TRUE;
        } else {
            $this->metadate->deleteSingleDate($cycle_id, $date_id, $this->filterStart, $this->filterEnd);
            NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
            return TRUE;
        }
    }

    public function cancelSingleDate($date_id, $cycle_id = '')
    {
        if ($cycle_id) {
            return $this->deleteSingleDate($date_id, $cycle_id);
        }
        $this->readSingleDates();
        // logging >>>>>>
        StudipLog::log("SEM_DELETE_SINGLEDATE",$date_id, $this->getId(), 'appointment cancelled');
        // logging <<<<<<
        $this->irregularSingleDates[$date_id]->setExTermin(true);
        $this->irregularSingleDates[$date_id]->store();
        unset ($this->irregularSingleDates[$date_id]);
        NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
        return TRUE;
    }

    public function unDeleteSingleDate($date_id, $cycle_id = '')
    {
        // logging >>>>>>
        StudipLog::log("SEM_UNDELETE_SINGLEDATE",$date_id, $this->getId(), 'Cycle_id: '.$cycle_id);
        NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
        // logging <<<<<<
        if ($cycle_id == '') {
            $termin = new SingleDate($date_id);
            if (!$termin->isExTermin()) {
                return false;
            }
            $termin->setExTermin(false);
            $termin->store();
            return true;
        } else {
            return $this->metadate->unDeleteSingleDate($cycle_id, $date_id, $this->filterStart, $this->filterEnd);
        }
    }

    /**
     * return all stacked messages as a multidimensional array
     *
     * The array has the following structure:
     *   array( 'type' => ..., 'message' ... )
     * where type is one of error, info and success
     *
     * @return mixed the array of stacked messages
     */
    public function getStackedMessages()
    {
        if ( is_array( $this->message_stack ) ) {
            $ret = [];

            // cycle through message types and set title and details appropriate
            foreach ($this->message_stack as $type => $messages ) {
                switch ( $type ) {
                    case 'error':
                        $ret['error'] = [
                            'title'   => _("Es sind Fehler/Probleme aufgetreten!"),
                            'details' => $this->message_stack['error']
                        ];
                        break;

                    case 'info':
                        $ret['info'] = [
                            'title'   => implode('<br>', $this->message_stack['info']),
                            'details' => []
                        ];
                        break;

                    case 'success':
                        $ret['success'] = [
                            'title'   => _("Ihre Änderungen wurden gespeichert!"),
                            'details' => $this->message_stack['success']
                        ];
                        break;
                }
            }

            return $ret;
        }

        return false;
    }

    /**
     * return the next stacked messag-string
     *
     * @return string a message-string
     */
    public function getNextMessage()
    {
        if ($this->messages[0]) {
            $ret = $this->messages[0];
            unset ($this->messages[0]);
            sort($this->messages);
            return $ret;
        }
        return FALSE;
    }

    /**
     * stack an error-message
     *
     * @param string $text the message to stack
     */
    public function createError($text)
    {
        $this->messages[] = 'error§'.$text.'§';
        $this->message_stack['error'][] = $text;
    }

    /**
     * stack an info-message
     *
     * @param string $text the message to stack
     */
    public function createInfo($text)
    {
        $this->messages[] = 'info§'.$text.'§';
        $this->message_stack['info'][] = $text;
    }

    /**
     * stack a success-message
     *
     * @param string $text the message to stack
     */
    public function createMessage($text)
    {
        $this->messages[] = 'msg§'.$text.'§';
        $this->message_stack['success'][] = $text;
    }

    /**
     * add an array of messages to the message-stack
     *
     * @param mixed $messages array of pre-marked message-strings
     * @param bool returns true on success
     */
    public function appendMessages( $messages )
    {
        if (!is_array($messages)) return false;

        foreach ( $messages as $type => $msgs ) {
            foreach ($msgs as $msg) {
                $this->message_stack[$type][] = $msg;
            }
        }
        return true;
    }

    public function addCycle($data = [])
    {
        $new_id = $this->metadate->addCycle($data);
        if($new_id){
            $this->setStartWeek($data['startWeek'], $new_id);
            $this->setTurnus($data['turnus'], $new_id);
        }
        // logging >>>>>>
        if($new_id){
            $cycle_info = $this->metadate->cycles[$new_id]->toString();
            NotificationCenter::postNotification("CourseDidChangeSchedule", $this);
            StudipLog::log("SEM_ADD_CYCLE", $this->getId(), NULL, $cycle_info, '<pre>'.print_r($data,true).'</pre>');
        }
        // logging <<<<<<
        return $new_id;
    }

    /**
     * Change a regular timeslot of the seminar. The data is passed as an array
     * conatining the following fields:
     *   start_stunde, start_minute, end_stunde, end_minute
     *   description, turnus, startWeek, day, sws
     *
     * @param array $data the cycle-data
     *
     * @return void
     */
    public function editCycle($data = [])
    {
        $cycle = $this->metadate->cycles[$data['cycle_id']];
        $new_start = mktime($data['start_stunde'], $data['start_minute']);
        $new_end = mktime($data['end_stunde'], $data['end_minute']);
        $old_start = mktime($cycle->getStartStunde(),$cycle->getStartMinute());
        $old_end = mktime($cycle->getEndStunde(), $cycle->getEndMinute());
        $do_changes = false;

        // check, if the new timeslot exceeds the old one
        if (($new_start < $old_start) || ($new_end > $old_end) || ($data['day'] != $cycle->day) ) {
            $has_bookings = false;

            // check, if there are any booked rooms
            foreach($cycle->getSingleDates() as $singleDate) {
                if ($singleDate->getStarttime() > (time() - 3600) && $singleDate->hasRoom()) {
                    $has_bookings = true;
                    break;
                }
            }

            // if the timeslot exceeds the previous one and has some booked rooms
            // they would be lost, so ask the user for permission to do so.
            if (!$data['really_change'] && $has_bookings) {
                $link_params = [
                    'editCycle_x' => '1',
                    'editCycle_y' => '1',
                    'cycle_id' => $data['cycle_id'],
                    'start_stunde' => $data['start_stunde'],
                    'start_minute' => $data['start_minute'],
                    'end_stunde' => $data['end_stunde'],
                    'end_minute' => $data['end_minute'],