Skip to content
Snippets Groups Projects
User.class.php 57.3 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 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
<?php
/**
 * User.class.php
 * model class for combined auth_user_md5/user_info record
 * this class represents one user, the attributes from tables
 * auth_user_md5 and user_info were merged.
 *
 * @code
 * $a_user = User::find($id);
 * $another_users_email = User::findByUsername($username)->email;
 * $a_user->email = $another_users_email;
 * $a_user->store();
 * @endcode
 *
 * 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      André Noack <noack@data-quest.de>
 * @copyright   2011 Stud.IP Core-Group
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
 *
 * @property string user_id database column
 * @property string id alias column for user_id
 * @property string username database column
 * @property string password database column
 * @property string perms database column
 * @property string vorname database column
 * @property string nachname database column
 * @property string email database column
 * @property string validation_key database column
 * @property string auth_plugin database column
 * @property string locked database column
 * @property string lock_comment database column
 * @property string locked_by database column
 * @property string visible database column
 * @property string hobby computed column read/write
 * @property string lebenslauf computed column read/write
 * @property string publi computed column read/write
 * @property string schwerp computed column read/write
 * @property string home computed column read/write
 * @property string privatnr computed column read/write
 * @property string privatcell computed column read/write
 * @property string privadr computed column read/write
 * @property string score computed column read/write
 * @property string geschlecht computed column read/write
 * @property string mkdate computed column read/write
 * @property string chdate computed column read/write
 * @property string title_front computed column read/write
 * @property string title_rear computed column read/write
 * @property string preferred_language computed column read/write
 * @property string smsforward_copy computed column read/write
 * @property string smsforward_rec computed column read/write
 * @property string guestbook computed column read/write
 * @property string email_forward computed column read/write
 * @property string smiley_favorite computed column read/write
 * @property string motto computed column read/write
 * @property string lock_rule computed column read/write
 * @property SimpleORMapCollection course_memberships has_many CourseMember
 * @property SimpleORMapCollection institute_memberships has_many InstituteMember
 * @property SimpleORMapCollection admission_applications has_many AdmissionApplication
 * @property SimpleORMapCollection archived_course_memberships has_many ArchivedCourseMember
 * @property SimpleORMapCollection datafields has_many DatafieldEntryModel
 * @property SimpleORMapCollection studycourses has_many UserStudyCourse
 * @property SimpleORMapCollection contacts has_many Contact
 * @property UserInfo   info   has_one UserInfo
 * @property UserOnline online has_one UserOnline
 */
class User extends AuthUserMd5 implements Range, PrivacyObject
{
    /**
     *
     */
    protected static function configure($config = [])
    {
        $config['has_many']['course_memberships'] = [
            'class_name' => 'CourseMember',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_many']['institute_memberships'] = [
            'class_name' => 'InstituteMember',
            'order_by'   => 'ORDER BY priority ASC',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_many']['admission_applications'] = [
            'class_name' => 'AdmissionApplication',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_many']['archived_course_memberships'] = [
            'class_name' => 'ArchivedCourseMember',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_many']['datafields'] = [
            'class_name'  => 'DatafieldEntryModel',
            'foreign_key' => function ($user) {
                return [$user];
            },
            'assoc_foreign_key' => function ($model, $params) {
                $model->setValue('range_id', $params[0]->id);
            },
            'assoc_func' => 'findByModel',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_many']['studycourses'] = [
            'class_name' => 'UserStudyCourse',
            'assoc_func' => 'findByUser',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_and_belongs_to_many']['contacts'] = [
            'class_name'     => 'User',
            'thru_table'     => 'contact',
            'thru_key'       => 'owner_id',
            'thru_assoc_key' => 'user_id',
            'order_by'       => 'ORDER BY Nachname, Vorname',
            'on_delete'      => 'delete',
            'on_store'       => 'store',
        ];
        $config['has_many']['contactgroups'] = [
            'class_name'        => 'Statusgruppen',
            'assoc_foreign_key' => 'range_id',
            'on_delete'         => 'delete',
            'on_store'          => 'store',
        ];
        $config['has_one']['info'] = [
            'class_name' => 'UserInfo',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_one']['online'] = [
            'class_name' => 'UserOnline',
            'on_delete'  => 'delete',
            'on_store'   => 'store',
        ];
        $config['has_many']['resource_permissions'] = [
            'class_name' => 'ResourcePermission',
            'on_delete'  => 'delete',
            'on_store'   => 'store'
        ];
        $config['has_many']['resource_temporary_permissions'] = [
            'class_name' => 'ResourceTemporaryPermission',
            'on_delete'  => 'delete',
            'on_store'   => 'store'
        ];
        $config['has_many']['consultation_blocks'] = [
            'class_name'        => ConsultationBlock::class,
            'assoc_foreign_key' => 'teacher_id',
            'on_delete'         => 'delete',
        ];
        $config['has_many']['consultation_bookings'] = [
            'class_name' => ConsultationBooking::class,
            'on_delete'  => 'delete',
        ];

        $config['has_many']['mvv_assignments'] = [
            'class_name'        => MvvContact::class,
            'assoc_foreign_key' => 'contact_id',
            'on_delete'         => 'delete',
        ];

        $config['has_and_belongs_to_many']['domains'] = [
            'class_name'        => 'UserDomain',
            'thru_table'        => 'user_userdomains',
            'on_delete'         => 'delete',
            'on_store'          => 'store',
            'order_by'          => 'ORDER BY name',
        ];

        $config['has_one']['courseware'] = [
            'class_name' => \Courseware\StructuralElement::class,
            'assoc_func' => 'getCoursewareUser'
        ];

        $config['has_many']['course_notifications'] = [
            'class_name'        => CourseMemberNotification::class,
            'on_delete'         => 'delete',
        ];

        $config['additional_fields']['config']['get'] = function ($user) {
            return UserConfig::get($user->id);
        };

        $config['registered_callbacks']['after_delete'][] = 'cbRemoveFeedback';
        $config['registered_callbacks']['before_store'][] = 'cbClearCaches';

        $info = new UserInfo();
        $info_meta = $info->getTableMetadata();
        foreach ($info_meta ['fields'] as $field => $meta) {
            if ($field !== $info_meta['pk'][0]) {
                $config['additional_fields'][$field] = [
                    'get'            => '_getAdditionalValueFromRelation',
                    'set'            => '_setAdditionalValueFromRelation',
                    'relation'       => 'info',
                    'relation_field' => $field,
                ];
            }
        }

        parent::configure($config);
    }

    /**
     * Returns the currently authenticated user.
     *
     * @return User User
     */
    public static function findCurrent()
    {
        if (is_object($GLOBALS['user'])) {
            return $GLOBALS['user']->getAuthenticatedUser();
        }
    }

    /**
     * build new object with given data
     *
     * @param $data array assoc array of record
     * @return User
     */
    public static function build($data, $is_new = true)
    {
        $user = new User();
        $user->info = new UserInfo();
        $user->setData($data);
        $user->setNew($is_new);
        foreach (array_keys($user->db_fields) as $field) {
            $user->content_db[$field] = $user->content[$field];
        }
        $user->info = UserInfo::build($data, $is_new);
        return $user;
    }

    /**
     * Returns user object including user_info
     *
     * @param string $id
     * @return User User
     */
    public static function findFull($id)
    {
        $sql = "SELECT *
                FROM auth_user_md5
                LEFT JOIN user_info USING (user_id)
                WHERE user_id = ?";
        $data = DbManager::get()->fetchOne($sql, [$id]);
        if ($data) {
            return self::buildExisting($data);
        }
    }

    /**
     * Returns user objects including user_info
     *
     * @param array $ids
     * @param string $order_by
     * @return User[] User
     */
    public static function findFullMany($ids, $order_by = '')
    {
        $sql = "SELECT *
                FROM auth_user_md5
                LEFT JOIN user_info USING (user_id)
                WHERE user_id IN (?) " . $order_by;
        $data = DbManager::get()->fetchAll($sql, [$ids], 'User::buildExisting');
        return $data;
    }

    /**
     * return user object for given username
     *
     * @param string $username a username
     * @return User
     */
    public static function findByUsername($username)
    {
        return parent::findOneByUsername($username);
    }

    /**
     * returns an array of User-objects that have the given value in the
     * given datafield.
     * @param string $datafield_id
     * @param array of User
     */
    public static function findByDatafield($datafield_id, $value)
    {
        $query = "SELECT range_id
                  FROM datafields_entries
                  WHERE datafield_id = :datafield_id
                    AND content = :value";
        $search = DBManager::get()->prepare($query);
        $search->execute(compact('datafield_id', 'value'));
        $users = [];
        foreach ($search->fetchAll(PDO::FETCH_COLUMN) as $user_id) {
            $users[] = new User($user_id);
        }
        return $users;
    }

    public static function findDozentenByTermin_id($termin_id)
    {
        $record = new User();
        $db = DBManager::get();
        $sql = "SELECT `{$record->db_table}`.*
                FROM `{$record->db_table}`
                INNER JOIN `termin_related_persons` USING (user_id)
                WHERE `termin_related_persons`.`range_id` = ?
                ORDER BY Nachname, Vorname ASC";
        $statement = $db->prepare($sql);
        $statement->execute([$termin_id]);

        $ret = [];
        while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
            $item = new User();
            $item->setData($row, true);
            $item->setNew(false);

            $ret[] = $item;
        }
        return $ret;
    }

    /**
     * Wraps a search parameter in %..% if the parameter itself does not
     * contain % or _.
     *
     * @param String $needle Search parameter
     * @return String containing the wrapped needle if neccessary
     */
    private static function searchParam($needle)
    {
        if (preg_match('/[%_]/S', $needle)) {
            return $needle;
        }

        return '%' . $needle . '%';
    }

    /**
     * Temporary migrate to User.class.php
     *
     * @param $attributes
     * @return array
     */
    public static function search($attributes)
    {
        $params = [];
        $joins  = [];
        $where  = [];

        $query = "SELECT au.*, ui.*
                  FROM `auth_user_md5` au
                  LEFT JOIN `user_online` uo ON (au.`user_id` = uo.`user_id`)
                  LEFT JOIN `user_info` ui ON (au.`user_id` = ui.`user_id`)";

        if ($attributes['username']) {
            $where[] =  "au.`username` like :username";
            $params[':username'] = self::searchParam($attributes['username']);
        }

        if ($attributes['vorname']) {
            $where[] = "au.`Vorname` LIKE :vorname";
            $params[':vorname'] = self::searchParam($attributes['vorname']);
        }

        if ($attributes['nachname']) {
            $where[] = "au.`Nachname` LIKE :nachname";
            $params[':nachname'] = self::searchParam($attributes['nachname']);
        }

        if ($attributes['email']) {
            $where[] = "au.`Email` LIKE :email";
            $params[':email'] = self::searchParam($attributes['email']);
        }

        //permissions
        if (!is_null($attributes['perm']) && $attributes['perm'] != 'alle') {
            $where[] = "au.`perms` = :perms";
            $params[':perms'] = $attributes['perm'];
        }

        //locked user
        if ((int)$attributes['locked'] == 1) {
            $where[] = "au.`locked` = 1";
        }

        // show only users who are not lecturers
        if ($attributes['show_only_not_lectures']) {
            $where[] = "au.`user_id` NOT IN (SELECT `user_id` FROM `seminar_user` WHERE `status` = 'dozent') ";
        }

        if ($attributes['auth_plugins']) {
            $where[] = "IFNULL(`auth_plugin`, 'preliminary') = :auth_plugins ";
            $params[':auth_plugins'] = $attributes['auth_plugins'];
        }

        //inactivity
        if (!is_null($attributes['inaktiv']) && $attributes['inaktiv'][0] != 'nie') {
            $comp = in_array(trim($attributes['inaktiv'][0]), ['=', '>', '<=']) ? $attributes['inaktiv'][0] : '=';
            $days = (int)$attributes['inaktiv'][1];
            $where[] = "uo.`last_lifesign` {$comp} UNIX_TIMESTAMP(TIMESTAMPADD(DAY, -{$days}, NOW())) ";
        } elseif (!is_null($attributes['inaktiv'])) {
            $where[] = "uo.`last_lifesign` IS NULL";
        }

        //datafields
        if (!is_null($attributes['datafields']) && count($attributes['datafields']) > 0) {
            $joins[] = "LEFT JOIN `datafields_entries` de ON (de.`range_id` = au.`user_id`)";
            foreach ($attributes['datafields'] as $id => $entry) {
                $where[] = "de.`datafield_id` = :df_id_". $id;
                $where[] = "de.`content` LIKE :df_content_". $id;
                $params[':df_id_' . $id] = $id;
                $params[':df_content_' . $id] = $entry;
            }
        }

        // roles
        if (!empty($attributes['roles'])) {
            $joins[] = "LEFT JOIN `roles_user` ON roles_user.`userid` = au.`user_id`";
            $where[] = "roles_user.`roleid` IN (:roles)";
            $params[':roles'] = $attributes['roles'];
        }

        // userdomains
        if ($attributes['userdomains']) {
            $joins[] = "LEFT JOIN `user_userdomains` uud ON (au.`user_id` = uud.`user_id`)";
            $joins[] = "LEFT JOIN `userdomains` uds USING (`userdomain_id`)";
            if ($attributes['userdomains'] === 'null-domain') {
                $where[] = "`userdomain_id` IS NULL ";
            } else {
                $where[] = "userdomain_id = :userdomains";
                $params[':userdomains'] = $attributes['userdomains'];
            }
        }

        // degree or studycourse
        if (!empty($attributes['degree']) || !empty($attributes['studycourse']) || !empty($attributes['fachsem'])) {
            $joins[] = "LEFT JOIN `user_studiengang` us ON (us.`user_id` = au.`user_id`)";
            if (!empty($attributes['degree'])) {
                $where[] = "us.`abschluss_id` IN (:degree)";
                $params[':degree'] = $attributes['degree'];
            }

            if (!empty($attributes['studycourse'])) {
                $where[] = "us.`fach_id` IN (:studycourse)";
                $params[':studycourse'] = $attributes['studycourse'];
            }

            if(!empty($attributes['fachsem'])) {
                $where[] = 'us.`semester` = :fachsem';
                $params[':fachsem'] = $attributes['fachsem'];
            }
        }

        if ($attributes['institute']) {
            $joins[] = "LEFT JOIN `user_inst` uis ON uis.`user_id` = au.`user_id`";
            $where[] = "uis.`Institut_id` = :institute";
            $params[':institute'] = $attributes['institute'];
        }

        $query .= implode(' ', $joins);
        $query .= " WHERE 1 AND ";
        $query .= implode(' AND ', $where);
        $query .= " GROUP BY au.`user_id` ";

        //sortieren
        switch ($attributes['sort']) {
            case "perms":
                $query .= "ORDER BY au.`perms` {$attributes['order']}, au.`username`";
                break;
            case "Vorname":
                $query .= "ORDER BY au.`Vorname` {$attributes['order']}, au.`Nachname`";
                break;
            case "Nachname":
                $query .= "ORDER BY au.`Nachname` {$attributes['order']}, au.`Vorname`";
                break;
            case "Email":
                $query .= "ORDER BY au.`Email` {$attributes['order']}, au.`username`";
                break;
            case "changed":
                $query .= "ORDER BY uo.`last_lifesign` {$attributes['order']}, au.`username`";
                break;
            case "mkdate":
                $query .= "ORDER BY ui.`mkdate` {$attributes['order']}, au.`username`";
                break;
            case "auth_plugin":
                $query .= "ORDER BY `auth_plugin` {$attributes['order']}, au.`username`";
                break;
            default:
                $query .= " ORDER BY au.`username` {$attributes['order']}";
        }

        return DBManager::get()->fetchAll($query, $params, __CLASS__ . '::buildExisting');
    }


    /**
     * @see SimpleORMap::store()
     */
    public function store()
    {
        if ($this->isDirty() && !$this->info->isFieldDirty('chdate')) {
            $this->info->setValue('chdate', time());
        }
        return parent::store();
    }

    /**
     * @see SimpleORMap::triggerChdate()
     */
    public function triggerChdate()
    {
       return $this->info->triggerChdate();
    }

    /**
     * returns the name in specified format
     * (formats defined in $GLOBALS['_fullname_sql'])
     *
     * @param string one of full,full_rev,no_title,no_title_rev,no_title_short,no_title_motto,full_rev_username
     * @return string guess what - the fullname
     */
    public function getFullName($format = 'default')
    {
        static $concat,$left,$if,$quote;

        if ($format === 'default') {
            $format = 'full';
        }

        $sql = $GLOBALS['_fullname_sql'][$format];
        if (!$sql || $format == 'no_title') {
            return $this->vorname . ' ' . $this->nachname;
        }
        if ($format == 'no_title_rev') {
            return $this->nachname . ', ' . $this->vorname;
        }
        if ($concat === null) {
            $concat = function() {return join('', func_get_args());};
            $left = function($str, $c = 0) {return mb_substr($str,0,$c);};
            $if = function($ok,$yes,$no) {return $ok ? $yes : $no;};
            $quote = function($str) {return "'" . addcslashes($str, "\\'\0") . "'";};
        }

        $data = array_map($quote, $this->toArray('vorname nachname username title_front title_rear motto perms'));
        $replace_func['CONCAT'] = '$concat';
        $replace_func['LEFT'] = '$left';
        $replace_func['UCASE'] = 'mb_strtoupper';
        $replace_func['IF'] = '$if';
        $eval = strtr($sql, $replace_func);
        $eval = strtr(mb_strtolower($eval), $data);
        return eval('return ' . $eval . ';');
    }

    public function toArrayRecursive($only_these_fields = null)
    {
        $ret = parent::toArrayRecursive($only_these_fields);
        unset($ret['info']);
        return  $ret;
    }

    /**
     * Returns whether the user was assigned a certain role.
     *
     * @param string $role         The role to check
     * @param string $institute_id An optional institute_id
     * @return bool True if the user was assigned this role, false otherwise
     */
    public function hasRole($role, $institute_id = '')
    {
        return RolePersistence::isAssignedRole($this->user_id, $role, $institute_id);
    }

    /**
     * Returns the roles that were assigned to the user.
     *
     * @param boolean $with_implicit
     * @return array
     */
    public function getRoles($with_implicit = false)
    {
        return RolePersistence::getAssignedRoles($this->user_id, $with_implicit);
    }

    /**
     * Returns whether the given user is stored in contacts.
     *
     * @param User $another_user
     * @return bool
     */
    public function isFriendOf($another_user)
    {
        return (bool) DBManager::get()->fetchColumn("SELECT 1 FROM contact WHERE owner_id=? AND user_id=?", [$this->user_id, $another_user->user_id]);
    }

    /**
     * checks if at least one field was modified since last restore
     *
     * @return boolean
     */
    public function isDirty()
    {
        return parent::isDirty() || $this->info->isDirty();
    }

    /**
     * checks if given field was modified since last restore
     *
     * @param string $field
     * @return boolean
     */
    public function isFieldDirty($field)
    {
        $field = mb_strtolower($field);
        return (array_key_exists($field, $this->content_db) ? parent::isFieldDirty($field) : $this->info->isFieldDirty($field));
    }

    /**
     * reverts value of given field to last restored value
     *
     * @param string $field
     * @return mixed the restored value
     */
    public function revertValue($field)
    {
        $field = mb_strtolower($field);
        return (array_key_exists($field, $this->content_db) ? parent::revertValue($field) : $this->info->revertValue($field));
    }

    /**
     * returns unmodified value of given field
     *
     * @param string $field
     * @throws InvalidArgumentException
     * @return mixed
     */
    public function getPristineValue($field)
    {
        $field = mb_strtolower($field);
        return (array_key_exists($field, $this->content_db) ? parent::getPristineValue($field) : $this->info->getPristineValue($field));
    }

    /**
     * Returns data of table row as assoc array with raw contents like
     * they are in the database.
     * Pass array of fieldnames or ws separated string to limit
     * fields.
     *
     * @param mixed $only_these_fields
     * @return array
     */
    public function toRawArray($only_these_fields = null)
    {
        return array_merge($this->info->toRawArray($only_these_fields), parent::toRawArray($only_these_fields));
    }

    /**
     * @param string $relation
     */
    public function initRelation($relation)
    {
        parent::initRelation($relation);
        if ($relation == 'info' && is_null($this->relations['info'])) {
            $options = $this->getRelationOptions($relation);
            $result = new $options['class_name'];
            $foreign_key_value = call_user_func($options['assoc_func_params_func'], $this);
            call_user_func($options['assoc_foreign_key_setter'], $result, $foreign_key_value);
            $this->relations[$relation] = $result;
        }
    }

    /**
     * This function returns the perms allowed for an institute for the current user
     *
     * @return array list of perms
     */
    public function getInstitutePerms()
    {
        if($this->perms === 'admin') {
            return ['admin'];
        }
        $allowed_status = [];
        $possible_status = ['autor', 'tutor', 'dozent'];

        $pos = array_search($this->perms, $possible_status);

        if ($pos !== false) {
            $allowed_status = array_slice($possible_status, 0, $pos + 1);
        }
        return $allowed_status;
    }

    /**
     * Get the decorated StudIP-Kings information
     * @return String
     */
    public function getStudipKingIcon()
    {
        $is_king = StudipKing::is_king($this->user_id, TRUE);

        $result = '';
        foreach ($is_king as $type => $text) {
            $type = str_replace('_', '-', $type);
            $result .= Assets::img('crowns/crown-' . $type . '.png', ['alt' => $text, 'title' => $text]);
        }

        return $result ?: null;
    }

    /**
     * Builds an array containing all available elements that are part of a
     * user's homepage together with their visibility. It isn't sufficient to
     * just load the visibility settings from database, because if the user
     * has added some data (e.g. CV) but not yet assigned a special visibility
     * to that field, it wouldn't show up.
     *
     * @return array An array containing all available homepage elements
     * together with their visibility settings in the form
     * $name => $visibility.
     */
    public function getHomepageElements()
    {
        $homepage_visibility = get_local_visibility_by_id($this->id, 'homepage');
        if (is_array(json_decode($homepage_visibility, true))) {
            $homepage_visibility = json_decode($homepage_visibility, true);
        } else {
            $homepage_visibility = [];
        }

        // News
        $news = StudipNews::GetNewsByRange($this->id, true);

        // Non-private dates.
        if (Config::get()->CALENDAR_ENABLE) {
            $dates = CalendarEvent::countBySql('range_id = ?', [$this->id]);
        }

        // Votes
        if (Config::get()->VOTE_ENABLE) {
            $activeVotes  = Questionnaire::countBySQL("user_id = ? AND visible = '1'", [$this->id]);
            $stoppedVotes = Questionnaire::countBySQL("user_id = ? AND visible = '0'", [$this->id]);
        }
        // Evaluations
        $evalDB = new EvaluationDB();
        $activeEvals = $evalDB->getEvaluationIDs($this->id, EVAL_STATE_ACTIVE);
        // Free datafields
        $data_fields = DataFieldEntry::getDataFieldEntries($this->id, 'user');
        $homepageplugins = [];

        // Now join all available elements with visibility settings.
        $homepage_elements = [];

        if (Avatar::getAvatar($this->id)->is_customized() && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['picture']) {
            $homepage_elements['picture'] = [
                'name'        => _('Eigenes Bild'),
                'visibility'  => $homepage_visibility['picture'] ?: get_default_homepage_visibility($this->id),
                'extern'      => true,
                'identifier'  => 'commondata'
            ];
        }

        if ($this->info->motto && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['motto']) {
            $homepage_elements['motto'] = [
                'name'       => _('Motto'),
                'visibility' => $homepage_visibility['motto'] ?: get_default_homepage_visibility($this->id),
                'identifier' => 'privatedata'
            ];
        }
        if (Config::get()->ENABLE_SKYPE_INFO) {
            if ($GLOBALS['user']->cfg->getValue('SKYPE_NAME') && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['skype_name']) {
                $homepage_elements['skype_name'] = [
                    'name'       => _('Skype Name'),
                    'visibility' => $homepage_visibility['skype_name'] ?: get_default_homepage_visibility($this->id),
                    'identifier' => 'privatedata'
                ];
            }
        }
        if ($this->info->privatnr && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['Private Daten_phone']) {
            $homepage_elements['private_phone'] = [
                'name'       => _('Private Telefonnummer'),
                'visibility' => $homepage_visibility['private_phone'] ?: get_default_homepage_visibility($this->id),
                'identifier' => 'privatedata'
            ];
        }
        if ($this->info->privatcell && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['private_cell']) {
            $homepage_elements['private_cell'] = [
                'name'       => _('Private Handynummer'),
                'visibility' => $homepage_visibility['private_cell'] ?: get_default_homepage_visibility($this->id),
                'identifier' => 'privatedata'
            ];
        }
        if ($this->info->privadr && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['privadr']) {
            $homepage_elements['privadr'] = [
                'name'         => _('Private Adresse'),
                'visibility'   => $homepage_visibility['privadr'] ?: get_default_homepage_visibility($this->id),
                'identifier'   => 'privatedata'
            ];
        }
        if ($this->info->home && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['homepage']) {
            $homepage_elements['homepage'] = [
                'name'        => _('Homepage-Adresse'),
                'visibility'  => $homepage_visibility['homepage'] ?: get_default_homepage_visibility($this->id),
                'extern'      => true,
                'identifier'  => 'privatedata'
            ];
        }
        if ($news && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['news']) {
            $homepage_elements['news'] = [
                'name'       => _('Ankündigungen'),
                'visibility' => $homepage_visibility['news'] ?: get_default_homepage_visibility($this->id),
                'extern'     => true,
                'identifier' => 'commondata'
            ];
        }
        if (Config::get()->CALENDAR_ENABLE && $dates && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['dates']) {
            $homepage_elements['termine'] = [
                'name'       => _('Termine'),
                'visibility' => $homepage_visibility['termine'] ?: get_default_homepage_visibility($this->id),
                'extern'     => true,
                'identifier' => 'commondata'
            ];
        }
        if (Config::get()->VOTE_ENABLE && ($activeVotes || $stoppedVotes || $activeEvals) && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['votes']) {
            $homepage_elements['votes'] = [
                'name'       => _('Fragebögen'),
                'visibility' => $homepage_visibility['votes'] ?: get_default_homepage_visibility($this->id),
                'identifier' => 'commondata'
            ];
        }

        $query = "SELECT 1
                  FROM user_inst
                  LEFT JOIN Institute USING (Institut_id)
                  WHERE user_id = ? AND inst_perms = 'user'";
        $statement = DBManager::get()->prepare($query);
        $statement->execute([$this->id]);
        if ($statement->fetchColumn() && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['studying']) {
            $homepage_elements['studying'] = [
                'name'       => _('Wo ich studiere'),
                'visibility' => $homepage_visibility['studying'] ?: get_default_homepage_visibility($this->id),
                'identifier' => 'studdata'
            ];
        }
        if ($this->info->lebenslauf && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['lebenslauf']) {
            $homepage_elements['lebenslauf'] = [
                'name'       => _('Lebenslauf'),
                'visibility' => $homepage_visibility['lebenslauf'] ?: get_default_homepage_visibility($this->id),
                'extern'     => true,
                'identifier' => 'privatedata'
            ];
        }
        if ($this->info->hobby && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['hobby']) {
            $homepage_elements['hobby'] = [
                'name'       => _('Hobbys'),
                'visibility' => $homepage_visibility['hobby'] ?: get_default_homepage_visibility($this->id),
                'identifier' => 'privatedata'
            ];
        }
        if ($this->info->publi && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['publi']) {
            $homepage_elements['publi'] = [
                'name'       => _('Publikationen'),
                'visibility' => $homepage_visibility['publi'] ?: get_default_homepage_visibility($this->id),
                'extern'     => true,
                'identifier' => 'privatedata'
            ];
        }
        if ($this->info->schwerp && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms]['schwerp']) {
            $homepage_elements['schwerp'] = [
                'name'       => _('Arbeitsschwerpunkte'),
                'visibility' => $homepage_visibility['schwerp'] ?: get_default_homepage_visibility($this->id),
                'extern'     => true,
                'identifier' => 'privatedata'
            ];
        }

        if ($data_fields) {
            foreach ($data_fields as $key => $field) {
                if ($field->getValue() && $field->isEditable($this->perms) && !$GLOBALS['NOT_HIDEABLE_FIELDS'][$this->perms][$key]) {
                    $homepage_elements[$key] = [
                        'name'       => $field->getName(),
                        'visibility' => $homepage_visibility[$key] ?: get_default_homepage_visibility($this->id),
                        'extern'     => true,
                        'identifier' => 'additionaldata'
                    ];
                }
            }
        }

        foreach (Kategorie::findByUserId($this->id) as $category) {
            $homepage_elements['kat_' . $category->id] = [
                'name'       => $category->name,
                'visibility' => $homepage_visibility['kat_' . $category->id] ?: get_default_homepage_visibility($this->id),
                'extern'     => true,
                'identifier' => 'owncategory'
            ];
        }

        if ($homepageplugins) {
            foreach ($homepageplugins as $plugin) {
                $homepage_elements['plugin_' . $plugin->getPluginId()] = [
                    'name'       => $plugin->getPluginName(),
                    'visibility' => $homepage_visibility['plugin_'.$plugin->getPluginId()] ?: get_default_homepage_visibility($this->id),
                    'identifier' => 'plugins'
                ];
            }
        }
        return $homepage_elements;
    }

    /**
     * Changes a user's email adress.
     *
     * @param string $email New email
     * @param bool   $force Force update (even if nothing actually changed)
     * @return bool
     */
    public function changeEmail($email, $force = false)
    {
        // Email did not actually change and update is not forced
        if ($this->email === $email && !$force) {
            return true;
        }

        // Is changing of email globally allowed?
        if (!Config::get()->ALLOW_CHANGE_EMAIL) {
            return false;
        }

        // Is changing of email allowed by auth plugin?
        if (StudipAuthAbstract::CheckField('auth_user_md5.Email', $this->auth_plugin) || LockRules::check($this->user_id, 'email')) {
            return false;
        }

        $validator          = new email_validation_class; ## Klasse zum Ueberpruefen der Eingaben
        $validator->timeout = 10;
        $REMOTE_ADDR        = $_SERVER['REMOTE_ADDR'];
        $Zeit               = date('H:i:s, d.m.Y');

        // accept only registered domains if set
        $email_restriction = trim(Config::get()->EMAIL_DOMAIN_RESTRICTION);
        if (!$validator->ValidateEmailAddress($email, $email_restriction)) {
            if ($email_restriction) {
                $email_restriction_msg_part = '';
                $email_restriction_parts    = explode(',', $email_restriction);
                for ($email_restriction_count = 0; $email_restriction_count < count($email_restriction_parts); $email_restriction_count++) {
                    if ($email_restriction_count == count($email_restriction_parts) - 1) {
                        $email_restriction_msg_part .= '@' . trim($email_restriction_parts[$email_restriction_count]) . '<br>';
                    } else if (($email_restriction_count + 1) % 3) {
                        $email_restriction_msg_part .= '@' . trim($email_restriction_parts[$email_restriction_count]) . ', ';
                    } else {
                        $email_restriction_msg_part .= '@' . trim($email_restriction_parts[$email_restriction_count]) . ',<br>';
                    }
                }
                PageLayout::postError(sprintf(_('Die E-Mail-Adresse fehlt, ist falsch geschrieben oder gehört nicht zu folgenden Domains:%s'),
                    '<br>' . htmlReady($email_restriction_msg_part)));
            } else {
                PageLayout::postError(_('Die E-Mail-Adresse fehlt oder ist falsch geschrieben!'));
            }
            return false;
        }

        if (!$validator->ValidateEmailHost($email)) {     // Mailserver nicht erreichbar, ablehnen
            PageLayout::postError(_('Der Mailserver ist nicht erreichbar. Bitte überprüfen Sie, ob Sie E-Mails mit der angegebenen Adresse verschicken können!'));
            return false;
        } else {       // Server ereichbar
            if (!$validator->ValidateEmailBox($email)) {    // aber user unbekannt. Mail an abuse!
                StudipMail::sendAbuseMessage("edit_about", "Emailbox unbekannt\n\nUser: " . $this->username . "\nEmail: ".$email ."\n\nIP: " . $REMOTE_ADDR ." \nZeit: " . $Zeit . "\n");
                PageLayout::postError(_('Die angegebene E-Mail-Adresse ist nicht erreichbar. Bitte überprüfen Sie Ihre Angaben!'));
                return false;
            }
        }

        if (self::countBySql('email = ? AND user_id != ?', [$email, $this->user_id])) {
            PageLayout::postError(sprintf(_('Die angegebene E-Mail-Adresse wird bereits von einem anderen Benutzer (%s) verwendet. Bitte geben Sie eine andere E-Mail-Adresse an.'),
                htmlReady($this->getFullName())));
            return false;
        }

        if (StudipAuthAbstract::CheckField('auth_user_md5.validation_key', $this->auth_plugin)) {
            PageLayout::postSuccess(_('Ihre E-Mail-Adresse wurde geändert!'));
        } else {
            // auth_plugin does not map validation_key (what if...?)

            // generate 10 char activation key
            $key = '';
            mt_srand((double)microtime() * 1000000);
            for ($i = 1; $i <= 10; $i++) {
                $temp = mt_rand() % 36;
                if ($temp < 10)
                    $temp += 48;   // 0 = chr(48), 9 = chr(57)
                else
                    $temp += 87;   // a = chr(97), z = chr(122)
                $key .= chr($temp);