Project-Pier /application/models/users/User.class.php

Language PHP Lines 1280
MD5 Hash 47b408125fb3ea51dca341855b4085de
Repository https://github.com/fb83/Project-Pier.git View Raw File
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
<?php

  function filenamecmp($a, $b) { return strcmp($a->getFileName(), $b->getFileName()); }

  /**
  * User class
  *
  * @http://www.projectpier.org/
  */
  class User extends BaseUser {

    /**
    * LDAP secure connection values 
    */
    const LDAP_SECURE_CONNECTION_NO  = 'no';
    const LDAP_SECURE_CONNECTION_TLS = 'tls';
    
    /**
    * Cached project permission values. Two level array. First level are projects (project ID) and
    * second are permissions associated with permission name
    *
    * @var array
    */
    private $project_permissions_cache = array();
    
    /**
    * Associative array. Key is project ID and value is true if user has access to that project
    *
    * @var array
    */
    private $is_project_user_cache = array();
    
    /**
    * True if user is member of owner company. This value is read on first request and cached
    *
    * @var boolean
    */
    private $is_member_of_owner_company = null;
    
    /**
    * Cached is_administrator value. First time value is requested it will be checked and cached. 
    * After that every request will return cached value
    *
    * @var boolean
    */
    private $is_administrator = null;
    
    /**
    * Cached is_account_owner value. Value is retrieved on first requests
    *
    * @var boolean
    */
    private $is_account_owner = null;
    
    /**
    * Cached value of all projects
    *
    * @var array
    */
    private $projects;
    
    /**
    * Cached value of active projects
    *
    * @var array
    */
    private $active_projects;
    
    /**
    * Cached value of active main projects
    *
    * @var array
    */
    private $active_main_projects;

    /**
    * Cached value of finished projects
    *
    * @var array
    */
    private $finished_projects;
    
    /**
    * Array of all active milestons
    *
    * @var array
    */
    private $all_active_milestons;
    
    /**
    * Cached late milestones
    *
    * @var array
    */
    private $late_milestones;
    
    /**
    * Cached today milestones
    *
    * @var array
    */
    private $today_milestones;
    
    /**
    * Cached array of new objects
    *
    * @var array
    */
    private $whats_new;
    
    /**
    * canSeeCompany() method will cache its result here (company_id => visible as bool)
    *
    * @var array
    */
    private $visible_companies = array();
    
    /**
    * Cached array of new files
    *
    * @var array
    */
    private $files;

    /**
    * Cached array of new files
    *
    * @var array
    */
    private $importantfiles;

    /**
    * Contact reference. This value is read on first request and cached
    *
    * @var boolean
    */
    private $contact = null;

    /**
    * Construct user object
    *
    * @param void
    * @return User
    */
    function __construct() {
      parent::__construct();
      $this->addProtectedAttribute('password', 'salt', 'session_lifetime', 'token', 'twister', 'last_login', 'last_visit', 'last_activity');
      $this->active_projects = array();
    } // __construct
    
    /**
    * Check if this user is member of specific company
    *
    * @access public
    * @param Company $company
    * @return boolean
    */
    function isMemberOf(Company $company) {
      trace(__FILE__,'isMemberOf()');
      return $this->getContact()->getCompanyId() == $company->getId();
    } // isMemberOf
    
    /**
    * Usualy we check if user is member of owner company so this is the shortcut method
    *
    * @param void
    * @return boolean
    */
    function isMemberOfOwnerCompany() {
      trace(__FILE__,'isMemberOfOwnerCompany()');
      if (is_null($this->is_member_of_owner_company)) {
        $this->is_member_of_owner_company = $this->isMemberOf(owner_company());
      }
      return $this->is_member_of_owner_company;
    } // isMemberOfOwnerCompany
    
    /**
    * Check if this user is part of specific project
    *
    * @param Project $project
    * @return boolean
    */
    function isProjectUser(Project $project) {
      if (is_null($project)) {
        return false;
      }
      if ($project->getCreatedById() == $this->getId()) {
        return true;
      }
      if (!isset($this->is_project_user_cache[$project->getId()])) {
        $project_user = ProjectUsers::findById(array(
          'project_id' => $project->getId(), 
          'user_id' => $this->getId())
        ); // findById
        $this->is_project_user_cache[$project->getId()] = $project_user instanceof ProjectUser;
      } // if
      return $this->is_project_user_cache[$project->getId()];
    } // isProjectUser

    /**
    * Set the project specific note for this user
    *
    * @param Project $project
    * @param string $data
    * @return boolean
    */
    function setProjectNote(Project $project, $data) {
      if (is_null($project)) {
        return false;
      }
      if (!$this->isProjectUser($project)) {
        return false;
      }
      $project_user = ProjectUsers::findById(array(
        'project_id' => $project->getId(), 
        'user_id' => $this->getId())
      ); // findById
      if ($project_user instanceof ProjectUser) {
        $project_user->setNote($data);
        return $project_user->save();
      } // if
      return false;
    } // setProjectNote

    /**
    * Set the project specific note for this user
    *
    * @param Project $project
    * @param string $data
    * @return boolean
    */
    function getProjectNote(Project $project) {
      if (is_null($project)) {
        return false;
      }
      if (!$this->isProjectUser($project)) {
        return false;
      }
      $project_user = ProjectUsers::findById(array(
        'project_id' => $project->getId(), 
        'user_id' => $this->getId())
      ); // findById
      if ($project_user instanceof ProjectUser) {
        return $project_user->getNote();
      } // if
      return false;
    } // getProjectNote
    

    /**
    * Set the project specific note for this user
    *
    * @param Project $project
    * @param string $data
    * @return boolean
    */
    function setProjectNoteView(Project $project, $data) {
      if (is_null($project)) {
        return false;
      }
      if (!$this->isProjectUser($project)) {
        return false;
      }
      $project_user = ProjectUsers::findById(array(
        'project_id' => $project->getId(), 
        'user_id' => $this->getId())
      ); // findById
      if ($project_user instanceof ProjectUser) {
        $project_user->setNoteView($data);
        return $project_user->save();
      } // if
      return false;
    } // setProjectNote


    
    /**
    * Check if this of specific company website. If must be member of that company and is_admin flag set to true
    *
    * @param void
    * @return boolean
    */
    function isAdministrator() {
      trace(__FILE__,'isAdministrator():begin');
      if (is_null($this->is_administrator)) {
        trace(__FILE__,'isAdministrator():init is_administrator');
        //$this->is_administrator = $this->isAccountOwner() || ($this->isMemberOfOwnerCompany() && $this->getIsAdmin());
        $this->is_administrator = ($this->isMemberOfOwnerCompany() && $this->getIsAdmin());
      } // if
      trace(__FILE__,'isAdministrator():end');
      return $this->is_administrator;
    } // isAdministrator
    
    /**
    * Account owner is user account that was created when company website is created
    *
    * @param void
    * @return boolean
    */
    function isAccountOwner() {
      //if (is_null($this->is_account_owner)) {
      //  $this->is_account_owner = $this->isMemberOfOwnerCompany() && (owner_company()->getCreatedById() == $this->getId());
      //} // if
      //return $this->is_account_owner;
      return false;
    } // isAccountOwner
    
    /**
    * Return project permission for specific user if he is on project. In case of any error $default is returned
    *
    * @access public
    * @param Project $project
    * @param string $permission Permission name
    * @param boolean $default Default value
    * @return boolean
    */
    function getProjectPermission(Project $project, $permission, $default = false) {
      trace(__FILE__,"getProjectPermission($permission, $default)");
      if (is_null($project)) return false;
      static $valid_permissions;
      if (!isset($valid_permissions)) {
        trace(__FILE__,"getProjectPermission($permission, $default):getPermissionsText()");
        $valid_permissions = array_keys(permission_manager()->getPermissionsText());
      } // if
      
      if (!in_array($permission, $valid_permissions)) {
        return $default;
      } // if
      
      trace(__FILE__,"getProjectPermission($permission, $default):findById project={$project->getId()}");
      $project_user = ProjectUsers::findById(array(
        'project_id' => $project->getId(),
        'user_id' => $this->getId()
      )); // findById
      if (!($project_user instanceof ProjectUser)) {
        return $default;
      } // if

      trace(__FILE__,"getProjectPermission($permission, $default):getPermissions()");
      $value = in_array($permission,$project_user->getPermissions()) ? true : false;
      return $value;
    } // getProjectPermission
    
    /**
    * Return if user can manage projects
    *
    * @access public
    * @return boolean
    */
    function canManageProjects() {
      trace(__FILE__,'canManageProjects()');

      $permission = PermissionManager::CAN_MANAGE_PROJECTS;
      
      $project_user = new ProjectUser();
      $project_user->setUserId($this->getId());
      $project_user->setProjectId(0);

      $value = in_array($permission,$project_user->getPermissions()) ? true : false;
      return $value;
    } // canManageProjects

    /***
    * Set a permission for this user
    *
    * @param string $permissionString Name of the permission. There are set of constants
    *   in ProjectUser that hold permission names (PermissionManager::CAN_MANAGE_MESSAGES ...)
    * @param int $value 1 if the user should be granted the permission, any other value is a denial
    * @return boolean
    */
    function setPermission($permission_name, $value) {
      $permission_id = Permissions::getPermissionId($permission_name);
      if (!isset($permission_id) || !$permission_id) {
        return false;
      }
      // delete permission
      ProjectUserPermissions::delete( array(
           '`user_id` = ? AND `project_id` = ? AND `permission_id` = ?', 
           $this->getId(),
           0,
           $permission_id
      ));
      // add if $value == 1
      if ($value == 1) {
        $pup = new ProjectUserPermission();
        $pup->setProjectId(0);
        $pup->setUserId($this->getId());
        $pup->setPermissionId($permission_id);
        $pup->save();
      } // if
    } // setPermission
    
    /***
    * Set a permission for this user
    *
    * @param Project $project
    * @param string $permissionString Name of the permission. There are set of constants
    *   in ProjectUser that hold permission names (PermissionManager::CAN_MANAGE_MESSAGES ...)
    * @param boolean $granted true=granted, false=denied
    * @return boolean
    */
    function setProjectPermission(Project $project, $permission_name, $granted) {
      trace(__FILE__, "setProjectPermission(project, $permission_name, $granted):begin");
      $permission_id = Permissions::getPermissionId($permission_name);
      if (!isset($permission_id) || !$permission_id) {
        return false;
      }
      if ($granted) {
        trace(__FILE__, "setProjectPermission(project, $permission_name, $granted):granted");
        $pup = new ProjectUserPermission();
        $pup->setProjectId($project->getId());
        $pup->setUserId($this->getId());
        $pup->setPermissionId($permission_id);
        $pup->save();
      } else {
        $pup = ProjectUserPermissions::findOne(array('conditions' => '`project_id` = '.$project->getId().' and `user_id` = '.$this->getId().' and `permission_id` = '.$permission_id));
        if (isset($pup) && ($pup instanceOf ProjectUserPermission)) {
          $pup->delete();
        } // if
      } // if
    } // setProjectPermission

    /***
    * Set a permission for this user
    *
    * @param Project $project
    * @param string $permission_group Name of the permission group
    * @param boolean $granted true=granted, false=denied
    * @return boolean
    */
    function setProjectPermissionsByGroup(Project $project, $permission_group, $granted) {
      trace(__FILE__, "setProjectPermissionsByGroup(project, $permission_name, $granted):begin");
      $permissions = PermissionManager::getPermissionsByGroup($permission_group);
      foreach($permissions as $permission_name) {
        $this->setProjectPermission($project, $permission_name, $granted);
      }
    } // setProjectPermission
    
    
    /**
    * This function will check if this user has all project permissions
    *
    * @param Project $project
    * @param boolean $use_cache
    * @return boolean
    */
    function hasAllProjectPermissions(Project $project, $use_cache = true) {
      $permissions = array_keys(PermissionManager::getPermissionsText());
      if (is_array($permissions)) {
        foreach ($permissions as $permission) {
          if (!$this->getProjectPermission($project, $permission)) {
            return false;
          }
        } // foreach
      } // if
      return true;
    } // hasAllProjectPermissions
    
    // ---------------------------------------------------
    //  Retrieve
    // ---------------------------------------------------
    
    /**
    * Return owner company
    *
    * @access public
    * @param void
    * @return Company
    */
    function getCompany() {
      return $this->getContact()->getCompany();
    } // getCompany

    /**
    * Return owner company
    *
    * @access public
    * @param void
    * @return Company
    */
    function getCompanyId() {
      return $this->getContact()->getCompanyId();
    } // getCompany

    /**
    * Return display name for company of this user.
    *
    * @access public
    * @param void
    * @return string
    */
    function getCompanyDisplayName() {
      $company = self::getCompany();
      return is_null($company) ? '' : $company->getName();
    } // getDisplayName

    /**
    * Return associated contact
    *
    * @param void
    * @return Contact
    */
    function getContact() {
      if (!isset($this->contact)) {
        $contact = Contacts::findOne(array('conditions' => array('`user_id` = ? ', $this->getId())));
        if ($contact instanceof Contact) {
          $this->contact = $contact;
        } else {
          $this->contact = new Contact;
          $this->contact->setDisplayName(lang('missing contact'));
          $this->contact->setCompanyId(owner_company()->getId());
        }
      }
      return $this->contact;
    } // getContact
    
    /**
    * Return time zone
    *
    * @access public
    * @param void
    * @return Company
    */
    function getTimezone() {
      return $this->getContact()->getTimezone();
    } // getTimezone

    /**
    * Return all projects that this user is member of
    *
    * @access public
    * @param void
    * @return array
    */
    function getProjects() {
      if (is_null($this->projects)) {
        $this->projects = ProjectUsers::getProjectsByUser($this);
      } // if
      return $this->projects;
    } // getProjects
 
    /**
    * Return array of active main projects that this user have access
    *
    * @access public
    * @param void
    * @return array
    */
    function getActiveMainProjects($sort = 'name') {
      trace(__FILE__, "getActiveMainProjects($sort)");
      if (is_null($this->active_main_projects)) {
        trace(__FILE__, '- initialize cache: active_main_projects');
        $this->active_main_projects = array();
      } // if
      if (!isset($this->active_main_projects[$sort])) {
        $projects_table = Projects::instance()->getTableName(true);
        $empty_datetime = DB::escape(EMPTY_DATETIME);
        $this->active_main_projects[$sort] = ProjectUsers::getProjectsByUser($this, "$projects_table.`completed_on` = $empty_datetime AND $projects_table.`parent_id` = 0", $sort);
      } // if
      return $this->active_main_projects[$sort];
    } // getActiveMainProjects
   
    /**
    * Return array of active projects that this user have access
    *
    * @access public
    * @param void
    * @return array
    */
    function getActiveProjects($sort = 'name') {
      trace(__FILE__, 'getActiveProjects()');
      if (is_null($this->active_projects)) {
        trace(__FILE__, '- initialize cache: active_projects');
        $this->active_projects = array();
      } // if
      if (!isset($this->active_projects[$sort])) {
        $projects_table = Projects::instance()->getTableName(true);
        $empty_datetime = DB::escape(EMPTY_DATETIME);
        $this->active_projects[$sort] = ProjectUsers::getProjectsByUser($this, "$projects_table.`completed_on` = $empty_datetime", $sort);
      } // if
      return $this->active_projects[$sort];
    } // getActiveProjects
    
    /**
    * Return array of finished projects
    *
    * @access public
    * @param void
    * @return array
    */
    function getFinishedProjects() {
      if (is_null($this->finished_projects)) {
        $projects_table = Projects::instance()->getTableName(true);
        $this->finished_projects = ProjectUsers::getProjectsByUser($this, "$projects_table.`completed_on` > " . DB::escape(EMPTY_DATETIME));
      } // if
      return $this->finished_projects;
    } // getFinishedProjects
    
    /**
    * Return all active milestones assigned to this user
    *
    * @param void
    * @return array
    */
    function getActiveMilestones() {
      if (is_null($this->all_active_milestons)) {
        $this->all_active_milestons = ProjectMilestones::getActiveMilestonesByUser($this);
      } // if
      return $this->all_active_milestons;
    } // getActiveMilestones
    
    /**
    * Return late milestones that this user have access to
    *
    * @access public
    * @param void
    * @return array
    */
    function getLateMilestones() {
      if (is_null($this->late_milestones)) {
        $this->late_milestones = ProjectMilestones::getLateMilestonesByUser($this);
      } // if
      return $this->late_milestones;
    } // getLateMilestones
    
    /**
    * Return today milestones that this user have access to
    *
    * @access public
    * @param void
    * @return array
    */
    function getTodayMilestones() {
      if (is_null($this->today_milestones)) {
        $this->today_milestones = ProjectMilestones::getTodayMilestonesByUser($this);
      } // if
      return $this->today_milestones;
    } // getTodayMilestones
    
    /**
    * Return array of active projects that this user have access
    *
    * @access public
    * @param void
    * @return array
    */
    function getFiles($sort = 'name') {
      trace(__FILE__, 'getFiles()');
      if (is_null($this->files)) {
        trace(__FILE__, '- initialize cache: files');
        $this->files = array();
      } // if
      if (!isset($this->files[$sort])) {
        $files = array();
        $projects = $this->getActiveProjects();
        foreach($projects as $project) {
          $projectfiles = ProjectFiles::getAllFilesByProject($project);
          $i=0;
          while (isset($projectfiles[$i])){
            $files[] = $projectfiles[$i];
            unset($projectfiles[$i]);
            $i++;
          }
        }
        usort($files, "filenamecmp");
        $this->files[$sort] = $files;
      } // if
      return $this->files[$sort];
    } // getFiles

    /**
    * Return array of active projects that this user have access
    *
    * @access public
    * @param void
    * @return array
    */
    function getImportantFiles($sort = 'name') {
      trace(__FILE__, 'getImportantFiles()');
      if (is_null($this->importantfiles)) {
        trace(__FILE__, '- initialize cache: files');
        $this->importantfiles = array();
      } // if
      if (!isset($this->importantfiles[$sort])) {
        $files = array();
        $projects = $this->getActiveProjects();
        if (is_array($projects)) {
          foreach($projects as $project) {
            $projectfiles = ProjectFiles::getImportantProjectFiles($project);
            $i=0;
            while (isset($projectfiles[$i])){
              $files[] = $projectfiles[$i];
              unset($projectfiles[$i]);
              $i++;
            }
          }
        }
        usort($files, "filenamecmp");
        $this->importantfiles[$sort] = $files;
      } // if
      return $this->importantfiles[$sort];
    } // getImportantFiles
    
    /**
    * Return display name for this account. If there is no display name set username will be used
    *
    * @access public
    * @param void
    * @return string
    */
    function getDisplayName() {
      $display = $this->getContact()->getDisplayName();
      return trim($display) == '' ? $this->getUsername() : $display;
    } // getDisplayName
    
    // ---------------------------------------------------
    //  Utils
    // ---------------------------------------------------
    
    /**
    * This function will generate new user password, set it and return it
    *
    * @param boolean $save Save object after the update
    * @return string
    */
    function resetPassword($save = true) {
      $new_password = substr(sha1(uniqid(rand(), true)), rand(0, 25), 13);
      $this->setPassword($new_password);
      if ($save) {
        $this->save();
      } // if
      return $new_password;
    } // resetPassword
    
    /**
    * Set password value
    *
    * @param string $value
    * @return boolean
    */
    function setPassword($value) {
      do {
        $salt = substr(sha1(uniqid(rand(), true)), rand(0, 25), 13);
        $token = sha1($salt . $value);
      } while (Users::tokenExists($token));
      
      $this->setToken($token);
      $this->setSalt($salt);
      $this->setTwister(StringTwister::getTwister());
    } // setPassword
    
    /**
    * Return twisted token
    *
    * @param void
    * @return string
    */
    function getTwistedToken() {
      return StringTwister::twistHash($this->getToken(), $this->getTwister());
    } // getTwistedToken
    
    /**
    * Check if $check_password is valid user password
    *
    * @param string $check_password
    * @return boolean
    */
    function isValidPassword($check_password) {
      if ($this->getUseLDAP()) {
        return $this->doLDAP($check_password);
      }
      return sha1($this->getSalt() . $check_password) == $this->getToken();
    } // isValidPassword
    
    /**
    * Check if $twisted_token is valid for this user account
    *
    * @param string $twisted_token
    * @return boolean
    */
    function isValidToken($twisted_token) {
      return StringTwister::untwistHash($twisted_token, $this->getTwister()) == $this->getToken();
    } // isValidToken

    /**
    * Authenticate using LDAP.
    *
    * @param string $pass
    * @param string config_option('ldap_domain')
    * @param string config_option('ldap_host')
    * @param string config_option('ldap_secure_connection')
    * @return boolean
    */
    function doLDAP($pass) {
      if (!function_exists('ldap_connect')) {
        return false;
      }
      $username = $this->getUsername();
      if (strlen(config_option('ldap_domain', '')) != 0) {
        //$username = $username . '@' . config_option('ldap_domain');
        $username = sprintf(config_option('ldap_domain'), $username);
      }	

      $ldapconn = ldap_connect('ldap://' . config_option('ldap_host', ''));

      if (!$ldapconn) {
        return false;
      }
      ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
      $ldap_secure_connection = config_option('ldap_secure_connection', self::LDAP_SECURE_CONNECTION_NO);
      if ($ldap_secure_connection == self::LDAP_SECURE_CONNECTION_TLS) {
        if (!ldap_start_tls($ldapconn)) {
          ldap_close($ldapconn);
          return false;
	}
      }

      $ldapbind = ldap_bind($ldapconn, $username, $pass);
      ldap_close($ldapconn);
      return $ldapbind;
    } // doLDAP
    
    // ---------------------------------------------------
    //  Permissions
    // ---------------------------------------------------
    
    /**
    * Can specific user add user to specific company
    *
    * @access public
    * @param User $user
    * @param Company $to Can user add user to this company
    * @return boolean
    */
    function canAdd(User $user, Company $to) {
      if ($user->isAccountOwner()) {
        return true;
      } // if
      return $user->isAdministrator();
    } // canAdd
    
    /**
    * Check if specific user can update this user account
    *
    * @access public
    * @param User $user
    * @return boolean
    */
    function canEdit(User $user) {
      if ($user->getId() == $this->getId()) {
        return true; // account owner
      } // if
      if ($user->isAccountOwner()) {
        return true;
      } // if
      return $user->isAdministrator();
    } // canEdit
    
    /**
    * Check if specific user can delete specific account
    *
    * @param User $user
    * @return boolean
    */
    function canDelete(User $user) {
      if ($this->isAccountOwner()) {
        return false; // can't delete accountowner
      } // if
      
      if ($this->getId() == $user->getId()) {
        return false; // can't delete self
      } // if
      
      return $user->isAdministrator();
    } // canDelete
    
    /**
    * Returns true if this user can see $user
    *
    * @param User $user
    * @return boolean
    */
    function canSeeUser(User $user) {
      if ($this->isMemberOfOwnerCompany()) {
        return true; // see all
      } // if
      if ($user->getCompanyId() == $this->getCompanyId()) {
        return true; // see members of your own company
      } // if
      if ($user->isMemberOfOwnerCompany()) {
        return true; // see members of owner company
      } // if
      return false;
    } // canSeeUser

    /**
    * Returns true if this user can see $contact
    * TODO shouldn't it be in the Contact model?
    *
    * @param Contact $contact
    * @return boolean
    */
    function canSeeContact(Contact $contact) {
      if ($this->isMemberOfOwnerCompany()) {
        return true; // see all
      } // if
      if ($contact->getCompanyId() == $this->getCompanyId()) {
        return true; // see members of your own company
      } // if
      if ($contact->isMemberOfOwnerCompany()) {
        return true; // see members of owner company
      } // if
      return false;
    } // canSeeContact
    

    
    /**
    * Returns true if this user can see $company. Members of owener company and
    * coworkers are visible without project check! Also, members of owner company
    * can see all clients without any prior check!
    *
    * @param Company $company
    * @return boolean
    */
    function canSeeCompany(Company $company) {
      if ($this->isMemberOfOwnerCompany()) {
        return true;
      } // if
            
      if ($company->isOwner()) {
        $this->visible_companies[$company->getId()] = true;
        return true;
      } // if

      if (isset($this->visible_companies[$company->getId()])) {
        return $this->visible_companies[$company->getId()];
      } // if

      if ($this->getCompanyId() == $company->getId()) {
        $this->visible_companies[$company->getId()] = true;
        return true;
      } // if
      
      // Lets company projects for company of this user and for $company and 
      // compare if we have projects where both companies work together
      $projects_1 = DB::executeAll("SELECT `project_id` FROM " . ProjectCompanies::instance()->getTableName(true) . " WHERE `company_id` = ?", $this->getCompanyId());
      $projects_2 = DB::executeAll("SELECT `project_id` FROM " . ProjectCompanies::instance()->getTableName(true) . " WHERE `company_id` = ?", $company->getId());
      
      if (!is_array($projects_1) || !is_array($projects_2)) {
        $this->visible_companies[$company->getId()] = false;
        return false;
      } // if
      
      foreach ($projects_1 as $project_id) {
        if (in_array($project_id, $projects_2)) {
          $this->visible_companies[$company->getId()] = true;
          return true;
        } // if
      } // foreach
      
      $this->visible_companies[$company->getId()] = false;
      return false;
    } // canSeeCompany
    
    /**
    * Check if specific user can update this profile
    *
    * @param User $user
    * @return boolean
    */
    function canUpdateProfile(User $user) {
      if ($this->getId() == $user->getId()) {
        return true;
      } // if
      if ($user->isAdministrator()) {
        return true;
      } // if
      return false;
    } // canUpdateProfile
    
    /**
    * Check if this user can update this users permissions
    *
    * @param User $user
    * @return boolean
    */
    function canUpdatePermissions(User $user) {
      if ($this->isAccountOwner()) {
        return false; // noone will touch this
      } // if
      return $user->isAdministrator();
    } // canUpdatePermissions
    
    /**
    * Check if this user is company administration (used to check many other permissions). User must
    * be part of the company and have is_admin stamp set to true
    *
    * @access public
    * @param Company $company
    * @return boolean
    */
    function isCompanyAdmin(Company $company) {
      return ($this->getCompanyId() == $company->getId()) && $this->getIsAdmin();
    } // isCompanyAdmin
    
   
    // ---------------------------------------------------
    //  URLs
    // ---------------------------------------------------
    
    /**
    * Return view account URL of this user
    *
    * @access public
    * @param void
    * @return string
    */
    function getAccountUrl() {
      return get_url('account', 'index');
    } // getAccountUrl
    
    /**
    * Show company card page
    *
    * @access public
    * @param void
    * @return null
    */
    function getCardUrl() {
      return get_url('contacts', 'card', $this->getContact()->getId());
    } // getCardUrl
    
    /**
    * Return edit user URL
    *
    * @access public
    * @param void
    * @return string
    */
    function getEditUrl() {
      return $this->getContact()->getEditUserAccountUrl();
    } // getEditUrl
    
    /**
    * Return delete user URL
    *
    * @access public
    * @param void
    * @return string
    */
    function getDeleteUrl() {
      return get_url('user', 'delete', $this->getId());
    } // getDeleteUrl
    
    /**
    * Return edit profile URL
    *
    * @param string $redirect_to URL where we need to redirect user when he updates profile
    * @return string
    */
    function getEditProfileUrl($redirect_to = null) {
      $attributes = array('id' => $this->getContact()->getId());
      if (trim($redirect_to) <> '') {
        $attributes['redirect_to'] = str_replace('&amp;', '&', trim($redirect_to));
      } // if
      
      return get_url('contacts', 'edit', $attributes);
    } // getEditProfileUrl
    
    /**
    * Edit users password
    *
    * @param string $redirect_to URL where we need to redirect user when he updates password
    * @return null
    */
    function getEditPasswordUrl($redirect_to = null) {
      $attributes = array('id' => $this->getId());
      if (trim($redirect_to) <> '') {
        $attributes['redirect_to'] = str_replace('&amp;', '&', trim($redirect_to));
      } // if
      
      return get_url('account', 'edit_password', $attributes);
    } // getEditPasswordUrl

    /**
    * Return edit user permissions page URL
    *
    * @param string $redirect_to
    * @return string
    */
    function getEditPermissionsUrl($redirect_to = null) {
      $attributes = array('id' => $this->getId());
      if (trim($redirect_to) <> '') {
        $attributes['redirect_to'] = str_replace('&amp;', '&', trim($redirect_to));
      } // if
      
      return get_url('account', 'edit_permissions', $attributes);
    } // getEditPermissionsUrl
    
    /**
    * Return radio URL
    *
    * @param string 
    * @return string
    */
    function getRadioUrl() {
      $attributes = array('id' => $this->getContact()->getId(), 'target' => '_blank');
      return get_url('account', 'radio', $attributes);
    } // getRadioUrl

    /**
    * Return update user permissions page URL
    *
    * @param string $redirect_to
    * @return string
    */
    function getUpdatePermissionsUrl($redirect_to = null) {
      $attributes = array('id' => $this->getId());
      if (trim($redirect_to) <> '') {
        $attributes['redirect_to'] = str_replace('&amp;', '&', trim($redirect_to));
      } // if
      
      return get_url('account', 'update_permissions', $attributes);
    } // getUpdatePermissionsUrl
    
    /**
    * Return edit user URL
    *
    * @access public
    * @param void
    * @return string
    */
    function getEditProjectPermissionsUrl($project) {
      $attributes = array('id' => $this->getId());
      if ($project instanceof Project) {
        $attributes['project_id'] = $project->getId();
      }
      
      return get_url('account', 'update_permissions', $attributes);
    } // getEditUrl
    
    /**
    * Return recent activities feed URL
    * 
    * If $project is valid project instance URL will be limited for that project only, else it will be returned for 
    * overal feed
    *
    * @param Project $project
    * @return string
    */
    function getRecentActivitiesFeedUrl($project = null) {
      $params = array(
        'id' => $this->getId(),
        'token' => $this->getTwistedToken(),
      ); // array
      
      if ($project instanceof Project) {
        $params['project'] = $project->getId();
        return get_url('feed', 'project_activities', $params, null, false);
      } else {
        return get_url('feed', 'recent_activities', $params, null, false);
      } // if
    } // getRecentActivitiesFeedUrl
    
    /**
    * Return iCalendar URL
    * 
    * If $project is valid project instance calendar will be rendered just for that project, else it will be rendered 
    * for all active projects this user is involved with
    *
    * @param Project $project
    * @return string
    */
    function getICalendarUrl($project = null) {
      $params = array(
        'id' => $this->getId(),
        'token' => $this->getTwistedToken(),
      ); // array
      
      if ($project instanceof Project) {
        $params['project'] = $project->getId();
        return get_url('feed', 'project_ical', $params, null, false);
      } else {
        return get_url('feed', 'user_ical', $params, null, false);
      } // if
    } // getICalendarUrl
    
    // ---------------------------------------------------
    //  System functions
    // ---------------------------------------------------
    
    /**
    * Validate data before save
    *
    * @access public
    * @param array $errors
    * @return void
    */
    function validate(&$errors) {
      
      // Validate username if present
      if ($this->validatePresenceOf('username')) {
        if (!$this->validateUniquenessOf('username')) {
          $errors[] = lang('username must be unique');
        }
      } else {
        $errors[] = lang('username value required');
      } // if
      
      if (!$this->validatePresenceOf('token')) {
        $errors[] = lang('password value required');
      }
      
      // Validate email if present
      if ($this->validatePresenceOf('email')) {
        if (!$this->validateFormatOf('email', EMAIL_FORMAT)) {
          $errors[] = lang('invalid email address');
        }
      } else {
        $errors[] = lang('email value is required');
      } // if
            
    } // validate
    
    /**
    * Delete this object
    *
    * @param void
    * @return boolean
    */
    function delete() {
      if ($this->isAccountOwner()) {
        return false;
      } // if
      
      ProjectUsers::clearByUser($this);
      MessageSubscriptions::clearByUser($this);
      return parent::delete();
    } // delete
    
    // ---------------------------------------------------
    //  ApplicationDataObject implementation
    // ---------------------------------------------------
    
    /**
    * Return object name
    *
    * @access public
    * @param void
    * @return string
    */
    function getObjectName() {
      return $this->getDisplayName();
    } // getObjectName
    
    /**
    * Return object type name
    *
    * @param void
    * @return string
    */
    function getObjectTypeName() {
      return lang('user');
    } // getObjectTypeName
    
    /**
    * Return object URl
    *
    * @access public
    * @param void
    * @return string
    */
    function getObjectUrl() {
      return $this->getCardUrl();
    } // getObjectUrl
  
  } // User 

?>
Back to Top