Skip to content
Snippets Groups Projects
module.php 59.7 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
<?php
/**
 * @author      Peter Thienel <thienel@data-quest.de>
 * @license     GPL2 or any later version
 * @since       3.5
 */

require_once 'lib/classes/exportdocument/ExportPDF.class.php';

class Module_ModuleController extends MVVController
{
    public $filter = [];
    protected $show_sidebar_search = false;
    protected $show_sidebar_filter = false;

    public function before_filter(&$action, &$args)
    {
        parent::before_filter($action, $args);
        // set navigation
        Navigation::activateItem($this->me . '/module/module');
        $this->filter = $this->sessGet('filter', []);
        $this->action = $action;

        PageLayout::addSqueezePackage('statusgroups');
    }

    public function index_action()
    {
        PageLayout::setTitle(_('Verwaltung der Module - Alle Module'));
        $this->initPageParams();
        $this->initSearchParams('module');
        $search_result = $this->getSearchResult('Modul');

        // set default semester filter
        if (!isset($this->filter['start_sem.beginn'], $this->filter['end_sem.ende'])) {
            $sem_time_switch = Config::get()->SEMESTER_TIME_SWITCH;
            // switch semester according to time switch
            // (n weeks before next semester)
            $current_sem = Semester::findByTimestamp(
                time() + $sem_time_switch * 7 * 24 * 3600
            );
            if ($current_sem) {
                $this->filter['start_sem.beginn'] = $current_sem->beginn;
                $this->filter['end_sem.ende']     = $current_sem->beginn;
            }
        }

        // Nur Module von verantwortlichen Einrichtungen an denen der User
        // eine Rolle hat
        if (!$this->filter['mvv_modul_inst.institut_id']) {
            unset($this->filter['mvv_modul_inst.institut_id']);
        }
        $this->filter = array_merge(
            [
                'mvv_modul.modul_id'         => $search_result,
                'mvv_modul_inst.gruppe'      => 'hauptverantwortlich',
                'mvv_modul_inst.institut_id' => MvvPerm::getOwnInstitutes()
            ],
            $this->filter
        );
        $this->sortby = $this->sortby ?: 'code';
        $this->order  = $this->order ?: 'ASC';

        //get data
        $this->module = Modul::getAllEnriched(
                $this->sortby,
                $this->order,
                self::$items_per_page,
                self::$items_per_page * (($this->page ?: 1) - 1),
                $this->filter);

        if (!empty($this->filter)) {
            $this->search_result['Modul'] = $this->module->pluck('id');
        }

        if (count($this->module) === 0) {
            if (count($this->filter) || $this->search_term) {
                PageLayout::postInfo(_('Es wurden keine Module gefunden.'));
            } else {
                PageLayout::postInfo(_('Es wurden noch keine Module angelegt.'));
            }
        }
        $this->count = Modul::getCount($this->filter);
        $this->show_sidebar_search = true;
        $this->show_sidebar_filter = true;
        $this->setSidebar();
    }

    public function modul_action($modul_id = null, $institut_id = null)
    {
        $own_institutes = MvvPerm::getOwnInstitutes();

        if (!isset($this->modul)) {
            $this->modul = Modul::find($modul_id);
            if (!$this->modul) {
                $this->modul = new Modul();
                $this->modul->setNewId();
            }
        }
        if ($institut_id) {
            $institut = new Institute($institut_id);
            if (!$institut->isNew()) {
                $this->institut_id = $institut->getId();
            }
        }

        $this->contacts = $this->modul->contact_assignments;
        $this->range_id = $modul_id;
        $this->range_type = 'Modul';

        $this->setSidebar();
        $sidebar = Sidebar::get();

        if ($this->modul->isNew()) {
            PageLayout::setTitle(_('Neues Modul anlegen'));
            $success_message = ('Das Modul "%s" wurde angelegt.');
            $this->display_language = $this->modul->getDefaultLanguage();
            $this->deskriptor = $this->modul->getDeskriptor($this->display_language, true);
            $this->reset_search('Modul');
            if (!$modul_id) {
                PageLayout::postInfo(sprintf(
                    _('Sie legen ein neues Modul an. Das Modul muss zunächst in der Ausgabesprache <em>%s</em> angelegt werden.'),
                    $GLOBALS['MVV_MODUL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['name']
                ));
            }
            // set default language of instruction
            if ($GLOBALS['MVV_MODUL']['SPRACHE']['default']) {
                $this->modul->assignLanguagesOfInstruction([
                    $GLOBALS['MVV_MODUL']['SPRACHE']['default']
                ]);
            }
        } else {
            $this->display_language = Request::option(
                'display_language',
                $this->modul->getDefaultLanguage()
            );

            $this->deskriptor = $this->modul->getDeskriptor($this->display_language, true);
            $this->translations = $this->deskriptor->getAvailableTranslations();
            if (!in_array($this->display_language, $this->translations)) {
                PageLayout::setTitle(
                    sprintf(
                        _('Modul: <em>%s</em> in der Ausgabesprache <em>%s</em> neu anlegen.'),
                        $this->modul->getDisplayName(),
                        $GLOBALS['MVV_MODUL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['name']
                    )
                );
            } else {
                PageLayout::setTitle(sprintf(
                    _('Modul: %s bearbeiten'), $this->modul->getDisplayName()
                ));
            }

            $success_message = _('Das Modul "%s" wurde geändert.');
            // language selector as sidebar widget
            $template_factory = $this->get_template_factory();
            $sidebar_template = $template_factory->render('shared/deskriptor_language', [
                'modul'   => $this->modul,
                'sprache' => $this->display_language,
                'link'    => $this->url_for('/modul', $this->modul->id, $this->institut_id),
                'url'     => $this->url]
            );

            $widget  = new SidebarWidget();
            $widget->setTitle(_('Ausgabesprache'));
            $widget->addElement(new WidgetElement($sidebar_template));
            $sidebar->addWidget($widget, 'language');

            $action_widget = $sidebar->getWidget('actions');
            $action_widget->addLink(
                _('Download der Modulbeschreibung'),
                $this->url_for('module/download/details', $this->modul->id, $this->display_language),
                Icon::create('file-word')
            );
            $action_widget->addLink(
                _('Modulbeschreibung als PDF'),
                $this->url_for('module/download/details/' . $this->modul->id . '/' . $this->display_language, ['pdf' => '1']),
                Icon::create('file-pdf')
            );
            $action_widget->addLink(
                _('Vergleich mit anderem Modul'),
                $this->url_for('/diff_select', $this->modul->id),
                Icon::create('learnmodule'),
                ['data-dialog' => 'size=auto']
            );

            if ($this->modul->stat === 'planung' && MvvPerm::haveFieldPermStat($this->modul)) {
                $action_widget->addLink(
                    _('Modul genehmigen'),
                    $this->url_for('/approve', $this->modul->id),
                    Icon::create('accept'),
                    ['data-dialog' => 'size=auto;buttons=false']
                );
            }

            $action_widget->addLink(
                _('Log-Einträge dieses Moduls'),
                $this->url_for('shared/log_event/show/Modul/' . $this->modul->id,
                    ['object2_type' => 'ModulDeskriptor', 'object2_id' => $this->deskriptor->id]
                ),
                Icon::create('log')
            )->asDialog();

            // list all variants
            $variants = $this->modul->getVariants();
            if (count($variants)) {
                $widget = new SidebarWidget();
                $widget->setTitle(_('Varianten'));
                $widget->addElement(new WidgetElement(
                    $template_factory->render('shared/modul_variants',
                        [
                            'variants' => $variants,
                            'link'     => $this->url_for('/modul')
                        ])
                ));
                $sidebar->addWidget($widget, 'variants');
            }
        }
        $this->semester = array_reverse(Semester::getAll());
        $this->def_lang = $this->display_language === $this->modul->getDefaultLanguage();
        ModuleManagementModel::setContentLanguage($this->display_language);
        if (!$this->def_lang) {
            $action_widget = $sidebar->getWidget('actions');
            $action_widget->addLink(
                _('Alle Texte der Originalfassung anzeigen'),
                '#', Icon::create('consultation'),
                ['class' => 'mvv-show-all-original']
            );
        }

        $this->language = $GLOBALS['MVV_MODUL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['content_language'];
        if (Request::isPost()) {
            CSRFProtection::verifyUnsafeRequest();
            $stored = false;
            if ($this->def_lang) {
                $this->modul->variante = Request::option('modul_item');
                $this->modul->flexnow_modul = trim(Request::get('flexnow_modul'));
                $this->modul->code = trim(Request::get('code'));
                $this->modul->start = Request::option('start');
                $this->modul->end = Request::option('end') ?: null;
                $this->modul->beschlussdatum = strtotime(trim(Request::get('beschlussdatum')));
                $this->modul->assignLanguagesOfInstruction(Request::optionArray('language_items'));
                $this->modul->dauer = trim(Request::get('dauer'));
                if (Request::get('kap_unbegrenzt')) {
                    $this->modul->kapazitaet = '';
                } else {
                    $kapazitaet = trim(Request::get('kapazitaet'));
                    $this->modul->kapazitaet = $kapazitaet === '' ? null : $kapazitaet;
                }
                $this->modul->kp = Request::float('kp');
                $this->modul->wl_selbst = Request::int('wl_selbst');
                $this->modul->wl_pruef = Request::int('wl_pruef');
                $this->modul->pruef_ebene = Request::option('pruef_ebene');
                $this->modul->faktor_note = StringToFloat(trim(Request::get('faktor_note')));
                $this->modul->stat = Request::option('status', $GLOBALS['MVV_MODUL']['STATUS']['default']);
                $this->modul->kommentar_status = trim(Request::get('kommentar_status'));
                $this->modul->assignInstitutes(Request::optionArray('institutes_items'));
                $this->modul->assignResponsibleInstitute(Request::option('responsible_item'));
                $this->modul->fassung_nr = Request::int('fassung_nr');
                $this->modul->fassung_typ = Request::option('fassung_typ');
                $this->modul->version = trim(Request::get('version'));
                $this->modul->verantwortlich = trim(Request::get('verantwortlich'));
            }

            $deskriptor_fields = ['bezeichnung', 'verantwortlich',
                'voraussetzung', 'kompetenzziele', 'inhalte', 'literatur',
                'links', 'kommentar', 'turnus', 'kommentar_kapazitaet',
                'kommentar_wl_selbst', 'kommentar_wl_pruef', 'kommentar_sws',
                'kommentar_note', 'pruef_vorleistung', 'pruef_leistung',
                'pruef_wiederholung', 'ersatztext'];

            foreach ($deskriptor_fields as $deskriptor_field) {
                if ($this->deskriptor->isI18nField($deskriptor_field)) {
                    $this->deskriptor->$deskriptor_field->setLocalized(
                        trim(Request::get($deskriptor_field)),
                        $this->language
                    );
                } else {
                    $this->deskriptor->setValue(
                        $deskriptor_field,
                        trim(Request::get($deskriptor_field))
                    );
                }
            }

            // update datafields
            foreach (Request::getArray('datafields') as $df_key => $df_value) {
                $df = $this->deskriptor->datafields->findOneBy('datafield_id', $df_key);
                if ($df) {
                    $tdf = $df->getTypedDatafield();
                    $tdf->setContentLanguage($this->language);
                    $tdf->setValueFromSubmit($df_value);
                    $tdf->store();
                }
            }
            if (Request::submitted('store')) {
                try {
                    $this->modul->verifyPermission();
                    $stored = $this->modul->store();
                } catch (InvalidValuesException $e) {
                    PageLayout::postError(htmlReady($e->getMessage()));
                }
                if ($stored !== false) {
                    PageLayout::postSuccess(sprintf(
                        $success_message,
                        htmlReady($this->modul->getDisplayName())
                    ));
                    $this->redirect($this->url_for('/index'));
                    return;
                }
            }
        }

        $query = "SELECT modul_id, CONCAT(mmd.bezeichnung, ' (', code, ')') as name FROM mvv_modul mm
                LEFT JOIN mvv_modul_deskriptor mmd USING(modul_id)
                WHERE (code LIKE :input OR mmd.bezeichnung LIKE :input)
                AND mm.modul_id <> " . DBManager::get()->quote($this->modul->id ?: ''). " ORDER BY name ASC";
        $sql_search_modul = new SQLSearch($query, _('Modul suchen'));
        $this->qs_id_module = md5(serialize($sql_search_modul));
        $this->search_modul =
                QuickSearch::get('modul', $sql_search_modul)
                ->fireJSFunctionOnSelect('STUDIP.MVV.Search.addSelected')
                ->noSelectbox();

        $sql_search_user = new PermissionSearch(
            'user',
            _('Person suchen'),
            'user_id',
            ['permission' => words('tutor dozent admin'), 'exclude_user' => '']
        );
        $this->qs_id_users = md5(serialize($sql_search_user));
        $qs_users = QuickSearch::get('users', $sql_search_user);
        $this->qs_frame_id_users = $qs_users->getId();
        $this->search_users = $qs_users
                ->fireJSFunctionOnSelect('STUDIP.MVV.Search.addSelected')
                ->noSelectbox();

        $query = 'SELECT DISTINCT Institute.Institut_id, Institute.Name AS name
                    FROM Institute
                    LEFT JOIN range_tree ON (range_tree.item_id = Institute.Institut_id)
                    WHERE (Institute.Name LIKE :input OR range_tree.name LIKE :input )';
        if (count($own_institutes)) {
            $query .= 'AND Institut_id IN('
                    . DBManager::get()->quote($own_institutes) . ') ';
        }
        $query .= ' ORDER BY Institute.Name';
        $sql_search_responsible = new SQLSearch($query, _('Einrichtung suchen'),
                'Institut_id');
        $this->qs_id_responsible = md5(serialize($sql_search_responsible));
        $qs_responsible = QuickSearch::get('responsible', $sql_search_responsible);
        $this->qs_frame_id_responsible = $qs_responsible->getId();
        $this->search_responsible = $qs_responsible
                ->fireJSFunctionOnSelect('STUDIP.MVV.Search.addSelected')
                ->noSelectbox();

        $query = 'SELECT DISTINCT Institute.Institut_id, Institute.Name AS name
                FROM Institute
                LEFT JOIN range_tree ON (range_tree.item_id = Institute.Institut_id)
                WHERE (Institute.Name LIKE :input
                OR range_tree.name LIKE :input )
                ORDER BY Institute.Name';
        $sql_search_institutes = new SQLSearch($query, _('Einrichtung suchen'),
                'Institut_id');
        $this->qs_id_institutes = md5(serialize($sql_search_institutes));
        $qs_institutes = QuickSearch::get('institutes', $sql_search_institutes);
        $this->qs_frame_id_institutes = $qs_institutes->getId();
        $this->search_institutes = $qs_institutes
                ->fireJSFunctionOnSelect('STUDIP.MVV.Search.addSelected')
                ->noSelectbox();

        $this->cancel_url = $this->url_for('/index');

        $this->render_template('module/module/modul', $this->layout);
    }

    /**
     * Deletes a descriptor from module
     *
     * @param type $deskriptor_id
     * @throws Trails_Exception
     */
    public function delete_modul_deskriptor_action($deskriptor_id, $language)
    {
        $deskriptor = ModulDeskriptor::find($deskriptor_id);
        if (is_null($deskriptor)) {
            throw new Trails_Exception(404, _('Unbekannter Deskriptor'));
        }
        $def_lang = $deskriptor->modul->getDefaultLanguage();
        if ($language === $def_lang) {
            throw new Trails_Exception(403, _('Ein Deskriptor in der Original-Sprache kann nicht gelöscht werden.'));
        }
        if (Request::submitted('delete')) {
            CSRFProtection::verifyUnsafeRequest();
            if ($deskriptor->deleteTranslation($language)) {
                PageLayout::postSuccess(sprintf(
                    _('Der Deskriptor "%s" des Moduls "%s" wurde gelöscht!'),
                    htmlReady($deskriptor->getDisplayName()),
                    htmlReady($deskriptor->modul->getDisplayName())
                ));
            }
        }
        $this->redirect($this->url_for('/index'));
    }

    public function assignments_action($modul_id)
    {
        $this->modul = Modul::find($modul_id);
        PageLayout::setTitle(_('Zuordnungen'));
    }

    public function description_action($modul_id)
    {
        $response = $this->relay('shared/modul/description/' . $modul_id);
        if (Request::isXhr()) {
            $this->render_text($response->body);
        } else {
            $this->render_nothing();
        }
    }

    public function approve_action($modul_id)
    {
        $this->modul_id = $modul_id;
        $this->modul = Modul::find($modul_id);

        if (Request::submitted('approval')) {
            $modul = Modul::get($modul_id);
            $modul->stat = 'genehmigt';
            $stored = $modul->store(false);
            if ($stored) {
                PageLayout::postSuccess(sprintf(
                    _('Modul "%s" genehmigt!'),
                    htmlReady($this->modul->getDisplayName())
                ));
                $this->redirect($this->url_for('/details/' . $modul_id));
                return;
            }
        }
        PageLayout::setTitle(_('Modul genehmigen'));
        $this->setSidebar();
        $this->render_template('module/module/approve', $this->layout);
    }

    public function copy_form_action($modul_id)
    {
        // find the latest version of the given module
        $modul = Modul::find($modul_id);
        $this->modul = Modul::findOneBySql('LEFT JOIN semester_data '
            . 'ON start = semester_id '
            . "WHERE modul_id = ? OR quelle = ? AND stat = 'genehmigt' "
            . 'ORDER BY beginn DESC LIMIT 1',
            [$modul->id, $modul->quelle]);
        if (!$this->modul) {
            PageLayout::postError(_('Unbekanntes Modul'));
        } else {
            $this->perm = MvvPerm::get($this->modul);
            $this->submit_url = $this->url_for('/copy/' . $this->modul->id);
            $this->cancel_url = $this->url_for('/index');
        }
        PageLayout::setTitle(_('Modul kopieren'));
    }


    public function copy_action($modul_id)
    {
        $modul = Modul::find($modul_id);
        if (!$modul) {
            PageLayout::postError(_('Unbekanntes Modul'));
        } else {
            $perm = MvvPerm::get($modul);
            if (Request::submitted('copy')) {
                CSRFProtection::verifyUnsafeRequest();
                // Assign the copied module to the same versions of studycourses
                // as the original?
                $copy_assignments_to_versions = Request::get('copy_assignments');
                $copy = $modul->copy(true, $copy_assignments_to_versions);
                // Kopie kennzeichnen (eindeutiger Code und Titel des Moduls in
                // allen Deskriptoren
                $copy->code = $modul->code;
                $copy->beschlussdatum = null;
                $current = Semester::find($copy->end);
                $next = Semester::findNext($current->beginn);
                if (is_array($next) && !empty($next)) {
                    $next = array_pop($next);
                }
                $copy->start = $next->id;
                // get end semester from selection
                $end_sem = Semester::find(Request::option('end_sem'));
                $copy->end = $next->beginn > $end_sem->beginn ? '' : $end_sem->id;

                // quelle: Klammerung von (Gültigkeit-) Versionen desselben Moduls
                // Gießen: Modul-ID des ursprünglichen Moduls
                $copy->quelle = $modul->quelle ?: $modul->id;
                //UOL Version um 1 hochzählen
                $copy->version = $copy->version + 1;
                // don't show the new Modul
                $copy->stat = 'planung';

                $store = false;
                try {
                    $copy->verifyPermission();
                    // UOL: Don't validate
                    $copy->store(false);
                    PageLayout::postSuccess(sprintf(
                        _('Das Modul "%s" und alle zugehörigen Modulteile wurden kopiert!'),
                        htmlReady($modul->getDisplayName())
                    ));
                } catch (InvalidValuesException $e) {
                    PageLayout::postError(
                        _('Das Modul konnte nicht kopiert werden!') . ' ' . htmlReady($e->getMessage())
                    );
                } catch (Exception $e) {
                    PageLayout::postError(_('Beim Kopieren trat ein Fehler auf!'));
                }
            }
        }
        $this->redirect($this->url_for('/index'));
    }

    /**
     * Retrieves all fields from descriptor in the original language and
     * returns them as a json object.
     */
    public function show_original_action()
    {
        if (Request::isXhr()) {
            if (Request::option('type') === 'modulteil') {
                $parent = Modulteil::find(Request::option('id'));
                $formatted_fields = [
                    'voraussetzung',
                    'kommentar',
                    'kommentar_kapazitaet',
                    'kommentar_wl_praesenz',
                    'kommentar_wl_bereitung',
                    'kommentar_wl_selbst',
                    'kommentar_wl_pruef',
                    'pruef_vorleistung pruef_leistung'];
            } else {
                $parent = Modul::find(Request::option('id'));
                $formatted_fields = [
                    'voraussetzung',
                    'kompetenzziele',
                    'inhalte',
                    'literatur',
                    'links',
                    'kommentar',
                    'kommentar_kapazitaet',
                    'kommentar_wl_selbst',
                    'kommentar_wl_pruef',
                    'pruef_vorleistung',
                    'pruef_leistung',
                    'pruef_wiederholung ersatztext'
                ];
            }
            if ($parent) {
                $deskriptor_array = [];
                $deskriptor = $parent->getDeskriptor();
                foreach ($deskriptor->toArray() as $key => $value) {
                    if ($deskriptor->isI18nField($key) && MVVController::trim($value->original()) !== '') {
                        if (in_array($key, $formatted_fields)) {
                            $deskriptor_array[$key]['value'] = formatReady($value->original());
                        } else {
                            $deskriptor_array[$key]['value'] = $value->original();
                        }
                        $deskriptor_array[$key]['empty'] = 0;
                    } else {
                        $deskriptor_array[$key]['value'] = _('Keine Angabe in Originalfassung.');
                        $deskriptor_array[$key]['empty'] = 1;
                    }
                }

                // datafields
                foreach ($deskriptor->datafields as $entry) {
                    if ($entry->lang === '') {
                        $df = $entry->getTypedDatafield();
                        $value = $df->getDisplayValue();
                        $df_id = 'datafields_' . $entry->datafield_id;
                        if (MVVController::trim($value)) {
                            $deskriptor_array[$df_id]['value'] = $value;
                            $deskriptor_array[$df_id]['empty'] = 0;
                        } else {
                            $deskriptor_array[$df_id]['value'] = _('Keine Angabe in Originalfassung.');
                            $deskriptor_array[$df_id]['empty'] = 1;
                        }
                    }
                }
                $this->render_json($deskriptor_array);
            } else {
                $this->render_nothing();
            }
        } else {
            $this->redirect($this->url_for('/index'));
        }
    }

    public function modulteil_action($modulteil_id = null)
    {
        $this->modulteil = Modulteil::find($modulteil_id);
        if (!$this->modulteil) {
            $this->modul = Modul::find(Request::option('modul_id'));
            if (!$this->modul) {
                PageLayout::postError(_('Unbekanntes Modul'));
                $this->redirect($this->url_for('/index'));
                return;
            }
            $this->modulteil = new Modulteil();
            $this->modulteil->setNewId();
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
            $this->modulteil->modul_id = $this->modul->id;
        } else {
            $this->modul = $this->modulteil->modul;
        }

        $this->formen = [];
        foreach ($GLOBALS['MVV_MODULTEIL']['LERNLEHRFORM']['values'] as $key => $form) {
            if ($form['parent'] === '') {
                if ($form['visible'] || is_null($form['visible'])) {
                    $this->formen[$key]['group'] = [
                        'key'  => $key,
                        'name' => $form['name']
                    ];
                }
            } else {
                if ($form['visible']) {
                    $this->formen[$form['parent']]['options'][] = [
                        'key'  => $key,
                        'name' => $form['name']
                    ];
                }
            }
        }
        $this->setSidebar();

        if ($this->modulteil->isNew()) {
            PageLayout::setTitle(_('Neuen Modulteil anlegen'));
            $success_message = ('Der Modulteil "%s" wurde angelegt.');
            $this->display_language = $this->modulteil->getDefaultLanguage();
            $this->deskriptor = $this->modulteil->getDeskriptor($this->display_language, true);
            PageLayout::postInfo(sprintf(
                _('Sie legen einen neuen Modulteil für das Modul <em>%s</em> an. Der Modulteil muss zunächst in der Ausgabesprache <em>%s</em> angelegt werden.'),
                htmlReady($this->modul->getDisplayName()),
                htmlReady($GLOBALS['MVV_MODUL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['name'])
            ));
            // set default language of instruction
            if ($GLOBALS['MVV_MODULTEIL']['SPRACHE']['default']) {
                $this->modulteil->assignLanguagesOfInstruction([
                    $GLOBALS['MVV_MODULTEIL']['SPRACHE']['default']
                ]);
            }
        } else {
            $this->display_language = Request::option('display_language', $this->modulteil->getDefaultLanguage());
            $this->deskriptor = $this->modulteil->getDeskriptor($this->display_language, true);
            $this->translations = $this->deskriptor->getAvailableTranslations();

            if (!in_array($this->display_language, $this->translations)) {
                PageLayout::setTitle(sprintf(
                    _('Modulteil: "%s" in der Ausgabesprache "%s" neu anlegen.'),
                    $this->modulteil->getDisplayName(),
                    $GLOBALS['MVV_MODULTEIL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['name']
                ));
            } else {
                PageLayout::setTitle(sprintf(_('Modulteil: %s'), htmlReady($this->modulteil->getDisplayName())));
            }
            $success_message = _('Der Modulteil "%s" wurde geändert.');
            // sidebar widget for selecting language
            $template_factory = $this->get_template_factory();
            $sidebar = Sidebar::get();
            $widget = new ListWidget();
            $widget->setTitle(_('Ausgabesprache'));
            $widget_element = new WidgetElement(
                $template_factory->render('shared/deskriptor_language',
                    [
                        'modul'   => $this->modulteil,
                        'sprache' => $this->display_language,
                        'link'    => $this->url_for('/modulteil', $this->modulteil->id),
                        'url'     => $this->url
                    ]
                )
            );
            $widget->addElement($widget_element);
            $sidebar->addWidget($widget, 'languages');
        }

        $this->def_lang = $this->display_language === $this->modulteil->getDefaultLanguage();

        if (!$this->def_lang) {
            $action_widget = $sidebar->getWidget('actions');
            $action_widget->addLink(
                _('Alle Texte der Originalfassung anzeigen'),
                '#',
                Icon::create('consultation'),
                ['class' => 'mvv-show-all-original']
            );
        }

        $this->language = $GLOBALS['MVV_MODULTEIL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['content_language'];
        if (Request::submitted('store')) {
            CSRFProtection::verifyUnsafeRequest();
            $stored = false;
            if ($this->def_lang) {
                $this->modulteil->modul_id = Request::option('modul_id');
                $this->modulteil->flexnow_modul = trim(Request::get('flexnow_modul'));
                $this->modulteil->nummer = Request::int('nummer');
                $this->modulteil->num_bezeichnung = Request::option('num_bezeichnung');
                $this->modulteil->lernlehrform = Request::option('lernlehrform');
                $this->modulteil->semester = Request::option('semester');
                if (Request::get('kap_unbegrenzt')) {
                    $this->modulteil->kapazitaet = '';
                } else {
                    $kapazitaet = trim(Request::get('kapazitaet'));
                    $this->modulteil->kapazitaet = $kapazitaet === '' ? null : $kapazitaet;
                }
                $this->modulteil->kp = Request::float('kp');
                $this->modulteil->sws = Request::int('sws', 0);
                $this->modulteil->wl_praesenz = Request::int('wl_praesenz', 0);
                $this->modulteil->wl_bereitung = Request::int('wl_bereitung', 0);
                $this->modulteil->wl_selbst = Request::int('wl_selbst', 0);
                $this->modulteil->wl_pruef = Request::int('wl_pruef', 0);
                $this->modulteil->anteil_note = Request::int('anteil_note', 0);
                $this->modulteil->ausgleichbar = Request::int('ausgleichbar', 0);
                $this->modulteil->pflicht = Request::int('pflicht', 0);
                $this->modulteil->assignLanguagesOfInstruction(Request::optionArray('language_items'));
            }

            $deskriptor_fields = ['bezeichnung', 'voraussetzung', 'kommentar',
                'kommentar_kapazitaet', 'kommentar_wl_praesenz',
                'kommentar_wl_bereitung', 'kommentar_wl_selbst',
                'kommentar_wl_pruef', 'pruef_vorleistung', 'pruef_leistung',
                'kommentar_pflicht'];

            foreach ($deskriptor_fields as $deskriptor_field) {
                if ($this->deskriptor->isI18nField($deskriptor_field)) {
                    $this->deskriptor->$deskriptor_field->setLocalized(
                        trim(Request::get($deskriptor_field)),
                        $this->language
                    );
                } else {
                    $this->deskriptor->setValue($deskriptor_field, trim(Request::get($deskriptor_field)));
                }
            }

            // update datafields
            foreach (Request::getArray('datafields') as $df_key => $df_value) {
                $df = $this->deskriptor->datafields->findOneBy('datafield_id', $df_key);
                if ($df) {
                    $tdf = $df->getTypedDatafield();
                    $tdf->setContentLanguage($this->language);
                    $tdf->setValueFromSubmit($df_value);
                    $tdf->store();
                }
            }

            // check permission (add a Modulteil to Modul) if Modulteil is new
            if ($this->modulteil->isNew()) {
                $perm = MvvPerm::get($this->modul);
                if (!$perm->haveFieldPermModulteile(MvvPerm::PERM_CREATE)) {
                    throw new AccessDeniedException();
                }
            }

            try {
                $this->modulteil->verifyPermission();
                $stored = $this->modulteil->store();
            } catch (InvalidValuesException $e) {
                PageLayout::postError(htmlReady($e->getMessage()));
            }
            if ($stored !== false) {
                if ($stored) {
                    PageLayout::postSuccess(sprintf(
                        $success_message,
                        htmlReady($this->modulteil->getDisplayName())
                    ));
                } else {
                    PageLayout::postInfo(_('Es wurden keine Änderungen vorgenommen.'));
                }
                $this->redirect($this->url_for('/details/' . $this->modulteil->modul_id));
                return;
            }
        }
        if ($this->display_language !== $this->modulteil->getDefaultLanguage() && $this->deskriptor->isNew()) {
            PageLayout::postInfo(sprintf(
                _('Neue Beschreibung zum Modulteil "%s" in der Ausgabesprache %s anlegen.'),
                htmlReady($this->modulteil->getDisplayName()),
                htmlReady($GLOBALS['MVV_MODUL_DESKRIPTOR']['SPRACHE']['values'][$this->display_language]['name'])
            ));
        }
        $this->cancel_url = $this->url_for('/details/' .  $this->modulteil->modul_id);

        $action_widget = Sidebar::get()->getWidget('actions');
        $action_widget->addLink(
            _('Log-Einträge dieses Modulteils'),
            $this->url_for('shared/log_event/show/Modulteil/' . $this->modulteil->id,
                ['object2_type' => 'ModulteilDeskriptor', 'object2_id' => $this->deskriptor->id]
            ),
            Icon::create('log')
        )->asDialog();

        $this->render_template('module/module/modulteil', $this->layout);
    }

    /**
     * Deletes a descriptor from Modulteil
     *
     * @param type $deskriptor_id
     * @throws Trails_Exception
     */
    public function delete_modulteil_deskriptor_action($deskriptor_id, $language)
    {
        $deskriptor = ModulteilDeskriptor::find($deskriptor_id);
        if (is_null($deskriptor)) {
            throw new Trails_Exception(404, _('Unbekannter Deskriptor'));
        }
        $def_lang = $deskriptor->modulteil->getDefaultLanguage();
        if ($language === $def_lang) {
            throw new Trails_Exception(403, _('Ein Deskriptor in der Original-Sprache kann nicht gelöscht werden.'));
        }
        if (Request::submitted('delete')) {
            CSRFProtection::verifyUnsafeRequest();
            if ($deskriptor->deleteTranslation($language)) {
                PageLayout::postSuccess(sprintf(
                    _('Der Deskriptor "%s" des Modulteils "%s" wurde gelöscht!'),
                    htmlReady($deskriptor->getDisplayName()),
                    htmlReady($deskriptor->modulteil->getDisplayName())
                ));
            }
        }
        $this->redirect($this->url_for('/details/' . Request::option('modul_id')));
    }

    public function copy_modulteil_action($modulteil_id)
    {
        $modulteil = Modulteil::find($modulteil_id);
        if (!$modulteil) {
            PageLayout::postError(_('Unbekannter Modulteil'));
            $this->redirect($this->url_for('/index'));
            return;
        }
        $copy_modulteil = $modulteil->copy();
        $copy_modulteil->store();
        PageLayout::postInfo(sprintf(
            _('Der Modulteil "%s" wurde kopiert. Klicken Sie auf "übernehmen", um Änderungen an der Kopie zu speichern.'),
            htmlReady($copy_modulteil->getDisplayName())
        ));
        $this->redirect($this->url_for('/modulteil/' . $copy_modulteil->id));
    }

    public function modulteil_lvg_action($modulteil_id)
    {
        $this->modulteil = Modulteil::find($modulteil_id);
        if (is_null($this->modulteil)) {
            PageLayout::postError(_('Unbekannter Modulteil'));
            $this->redirect($this->url_for('/index'));
            return;
        } else {
            $this->modulteil_id = $this->modulteil->getId();
            $this->search_lvgruppe($this->modulteil->getId());
            if (Request::isXhr()) {
                $this->render_template('module/module/modulteil_lvg', null);
            } else {
                $this->modul = Modul::get($this->modulteil->modul_id);
                $this->modul_id = $this->modul->getId();
                $this->perform_relayed('details/' . $this->modulteil->modul_id . '/' . $this->modulteil->id);
            }
        }
    }

    private function search_lvgruppe($modulteil_id)
    {
        //Quicksearch
        $query = 'SELECT lvgruppe_id, name
                FROM mvv_lvgruppe WHERE name LIKE :input
                AND lvgruppe_id NOT IN (
                    SELECT lvgruppe_id FROM mvv_lvgruppe_modulteil WHERE modulteil_id = ' . DBManager::get()->quote($modulteil_id) .
            ')';
        $search = new SQLSearch($query, _('LV-Gruppe suchen'));
        $this->qs_search_id = md5(serialize($search));
        $this->search = QuickSearch::get(
            'lvgruppe_id_' . $modulteil_id, $search
        )->setInputStyle('width: 240px')
            ->noSelectbox();
    }

    public function add_lvgruppe_action($modulteil_id)
    {
        $this->modulteil = Modulteil::find($modulteil_id);
        if (is_null($this->modulteil)) {
            PageLayout::postError(_('Unbekannter Modulteil'));
            $this->redirect($this->url_for('/index'));
            return;
        } else {
            $this->lvgruppe = Lvgruppe::find(
                Request::option('lvgruppe_id_' . $this->modulteil->getId())
            );
            if (!$this->lvgruppe) {
                PageLayout::postError(_('Unbekannte Lehrveranstaltungsgruppe'));
            } else {
                $this->lvg_modulteil = LvgruppeModulteil::get(
                    [
                        $this->lvgruppe->getId(),
                        $this->modulteil->getId()
                    ]
                );
                if ($this->lvg_modulteil->isNew()) {
                    $this->lvg_modulteil->store();
                    PageLayout::postSuccess(sprintf(
                        _('Die Lehrveranstaltungsgruppe "%s" wurde dem Modulteil "%s" zugeordnet.'),
                        htmlReady($this->lvgruppe->getDisplayName()),
                        htmlReady($this->modulteil->getDisplayName())
                    ));
                } else {
                    PageLayout::postInfo(sprintf(
                        _('Die bestehende Zuordnung der Lehrveranstaltungsgruppe "%s" zum Modulteil "%s" wurde nicht geändert.'),
                        htmlReady($this->lvgruppe->getDisplayName()),
                        htmlReady($this->modulteil->getDisplayName())
                    ));
                }
            }
            $this->redirect($this->url_for('/details/' . $this->modulteil->modul_id . '/' . $this->modulteil->id));
        }
    }

    public function delete_lvgruppe_action($modulteil_id, $lvgruppe_id)
    {
        $lvg_modulteil = LvgruppeModulteil::find([$lvgruppe_id, $modulteil_id]);
        if (!$lvg_modulteil) {
            PageLayout::postError(_('Unbekannte Zuordnung'));
        } else {
            $lvgruppe = Lvgruppe::find($lvgruppe_id);
            $modulteil = Modulteil::find($modulteil_id);
            if (Request::submitted('delete')) {
                CSRFProtection::verifyUnsafeRequest();
                PageLayout::postSuccess(sprintf(
                    _('Die Lehrveranstaltungsgruppe "%s" wurde vom Modulteil "%s" entfernt.'),
                    htmlReady($lvgruppe->getDisplayName()),
                    htmlReady($modulteil->getDisplayName())
                ));
                $lvg_modulteil->delete();
            }
        }
        $this->redirect($this->url_for('/details/' . $modulteil->modul_id . '/' . $modulteil->id));
    }

    public function lvgruppe_action($modulteil_id, $lvgruppe_id = null)
    {
        $this->modulteil = Modulteil::find($modulteil_id);
        if (is_null($this->modulteil)) {
            PageLayout::postError(_('Unbekannter Modulteil'));
            $this->redirect($this->url_for('/index'));
            return;
        } else {
            $this->lvgruppe = Lvgruppe::get($lvgruppe_id);
            if ($this->lvgruppe->isNew()) {
                $this->lvgruppe = new Lvgruppe();
                PageLayout::setTitle(_('Neue Lehrveranstaltungsgruppe anlegen'));
                $success_message = _('Die Lehrveranstaltungsgruppe "%s" wurde angelegt.');
                $this->headline = _('Neue Lehrveranstaltungsgruppe anlegen.');
            } else {
                PageLayout::setTitle(_('Lehrveranstaltungsgruppe bearbeiten'));
                $success_message = _('Die Lehrveranstaltungsgruppe "%s" wurde geändert.');
                $this->headline = sprintf(_('Lehrveranstaltungsgruppe "%s" bearbeiten.'),
                    $this->lvgruppe->getDisplayName());
            }
            $this->cancel_url = $this->url_for('/index');
            $this->submit_url = $this->url_for('/lvgruppe' . '/' . $this->modulteil->id . '/' . $this->lvgruppe->id);
            if (Request::submitted('store')) {
                CSRFProtection::verifyUnsafeRequest();
                $stored = false;
                $this->lvgruppe->name = trim(Request::get('name'));
                $this->lvgruppe->alttext = Request::i18n('alttext')->trim();

                try {
                    $stored = $this->lvgruppe->store();
                    if ($stored) {
                        $this->lvg_modulteil = LvgruppeModulteil::get(
                            [
                                $this->lvgruppe->getId(),
                                $this->modulteil->getId()
                            ]
                        );
                        $stored_modulteil = $this->lvg_modulteil->store();
                    }
                } catch (InvalidValuesException $e) {
                    PageLayout::postError($e->getMessage());
                }
                if ($stored !== false && $stored_modulteil !== false) {
                    if ($stored) {
                        PageLayout::postSuccess(sprintf(
                            $success_message,
                            htmlReady($this->lvgruppe->getDisplayName())
                        ));
                    } else {
                        PageLayout::postInfo(_('Es wurden keine Änderungen vorgenommen.'));
                    }
                    $this->relocate('/details/' . $this->modulteil->modul_id . '/' . $this->modulteil->id);
                    return;
                }
            }
        }
        $this->render_template('lvgruppen/lvgruppen/lvgruppe');
    }