/
usermanager.lib.php
executable file
·5084 lines (4595 loc) · 195 KB
/
usermanager.lib.php
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
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
use Chamilo\UserBundle\Entity\User;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
/**
*
* Class UserManager
*
* This library provides functions for user management.
* Include/require it in your code to use its functionality.
* @package chamilo.library
* @author Julio Montoya <gugli100@gmail.com> Social network groups added 2009/12
*
*/
class UserManager
{
// This contants are deprecated use the constants located in ExtraField
const USER_FIELD_TYPE_TEXT = 1;
const USER_FIELD_TYPE_TEXTAREA = 2;
const USER_FIELD_TYPE_RADIO = 3;
const USER_FIELD_TYPE_SELECT = 4;
const USER_FIELD_TYPE_SELECT_MULTIPLE = 5;
const USER_FIELD_TYPE_DATE = 6;
const USER_FIELD_TYPE_DATETIME = 7;
const USER_FIELD_TYPE_DOUBLE_SELECT = 8;
const USER_FIELD_TYPE_DIVIDER = 9;
const USER_FIELD_TYPE_TAG = 10;
const USER_FIELD_TYPE_TIMEZONE = 11;
const USER_FIELD_TYPE_SOCIAL_PROFILE = 12;
const USER_FIELD_TYPE_FILE = 13;
const USER_FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
private static $encryptionMethod;
/**
* The default constructor only instanciates an empty user object
* @assert () === null
*/
public function __construct()
{
}
/**
* Repository is use to query the DB, selects, etc
* @return Chamilo\UserBundle\Entity\Repository\UserRepository
*/
public static function getRepository()
{
return Database::getManager()->getRepository('ChamiloUserBundle:User');
}
/**
* Create/update/delete methods are available in the UserManager
* (based in the Sonata\UserBundle\Entity\UserManager)
*
* @return Chamilo\UserBundle\Entity\Manager\UserManager
*/
public static function getManager()
{
$encoderFactory = self::getEncoderFactory();
$userManager = new Chamilo\UserBundle\Entity\Manager\UserManager(
$encoderFactory,
new \FOS\UserBundle\Util\Canonicalizer(),
new \FOS\UserBundle\Util\Canonicalizer(),
Database::getManager(),
'Chamilo\\UserBundle\\Entity\\User'
);
return $userManager;
}
/**
* @param string $encryptionMethod
*/
public static function setPasswordEncryption($encryptionMethod)
{
self::$encryptionMethod = $encryptionMethod;
}
/**
* @return bool|mixed
*/
public static function getPasswordEncryption()
{
$encryptionMethod = self::$encryptionMethod;
if (empty($encryptionMethod)) {
$encryptionMethod = api_get_configuration_value('password_encryption');
}
return $encryptionMethod;
}
/**
* @return EncoderFactory
*/
private static function getEncoderFactory()
{
$encryption = self::getPasswordEncryption();
switch ($encryption) {
case 'none':
$defaultEncoder = new PlaintextPasswordEncoder();
break;
case 'sha1':
case 'md5':
$defaultEncoder = new MessageDigestPasswordEncoder($encryption, false, 1);
break;
case 'bcrypt':
$defaultEncoder = new BCryptPasswordEncoder(4);
}
$encoders = array(
'Chamilo\\UserBundle\\Entity\\User' => $defaultEncoder
);
$encoderFactory = new EncoderFactory($encoders);
return $encoderFactory;
}
/**
* @param User $user
*
* @return \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface
*/
private static function getEncoder(User $user)
{
$encoderFactory = self::getEncoderFactory();
return $encoderFactory->getEncoder($user);
}
/**
* Validates the password
* @param string $password
* @param User $user
*
* @return bool
*/
public static function isPasswordValid($password, User $user)
{
$encoder = self::getEncoder($user);
$validPassword = $encoder->isPasswordValid(
$user->getPassword(),
$password,
$user->getSalt()
);
return $validPassword;
}
/**
* @param string $raw
* @param User $user
*
* @return bool
*/
public static function encryptPassword($raw, User $user)
{
$encoder = self::getEncoder($user);
$encodedPassword = $encoder->encodePassword(
$raw,
$user->getSalt()
);
return $encodedPassword;
}
/**
* @param int $userId
* @param string $password
*
*/
public static function updatePassword($userId, $password)
{
$repository = self::getRepository();
/** @var User $user */
$user = $repository->find($userId);
$userManager = self::getManager();
$user->setPlainPassword($password);
$userManager->updateUser($user, true);
}
/**
* Creates a new user for the platform
* @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
* @author Roan Embrechts <roan_embrechts@yahoo.com>
* @param string Firstname
* @param string Lastname
* @param int Status (1 for course tutor, 5 for student, 6 for anonymous)
* @param string e-mail address
* @param string Login
* @param string Password
* @param string Any official code (optional)
* @param string User language (optional)
* @param string Phone number (optional)
* @param string Picture URI (optional)
* @param string Authentication source (optional, defaults to 'platform', dependind on constant)
* @param string Account expiration date (optional, defaults to null)
* @param int Whether the account is enabled or disabled by default
* @param int The department of HR in which the user is registered (optional, defaults to 0)
* @param array Extra fields
* @param string Encrypt method used if password is given encrypted. Set to an empty string by default
* @param bool $send_mail
* @param bool $isAdmin
*
* @return mixed new user id - if the new user creation succeeds, false otherwise
* @desc The function tries to retrieve user id from the session.
* If it exists, the current user id is the creator id. If a problem arises,
* it stores the error message in global $api_failureList
* @assert ('Sam','Gamegie',5,'sam@example.com','jo','jo') > 1
* @assert ('Pippin','Took',null,null,'jo','jo') === false
*/
public static function create_user(
$firstName,
$lastName,
$status,
$email,
$loginName,
$password,
$official_code = '',
$language = '',
$phone = '',
$picture_uri = '',
$auth_source = PLATFORM_AUTH_SOURCE,
$expirationDate = null,
$active = 1,
$hr_dept_id = 0,
$extra = null,
$encrypt_method = '',
$send_mail = false,
$isAdmin = false
) {
$currentUserId = api_get_user_id();
$hook = HookCreateUser::create();
if (!empty($hook)) {
$hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE);
}
global $_configuration;
$original_password = $password;
$access_url_id = 1;
if (api_get_multiple_access_url()) {
$access_url_id = api_get_current_access_url_id();
}
if (is_array($_configuration[$access_url_id]) &&
isset($_configuration[$access_url_id]['hosting_limit_users']) &&
$_configuration[$access_url_id]['hosting_limit_users'] > 0) {
$num = self::get_number_of_users();
if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
api_warn_hosting_contact('hosting_limit_users');
return api_set_failure('portal users limit reached');
}
}
if ($status === 1 &&
is_array($_configuration[$access_url_id]) &&
isset($_configuration[$access_url_id]['hosting_limit_teachers']) &&
$_configuration[$access_url_id]['hosting_limit_teachers'] > 0
) {
$num = self::get_number_of_users(1);
if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
api_warn_hosting_contact('hosting_limit_teachers');
return api_set_failure('portal teachers limit reached');
}
}
$firstName = Security::remove_XSS($firstName);
$lastName = Security::remove_XSS($lastName);
$loginName = Security::remove_XSS($loginName);
$phone = Security::remove_XSS($phone);
// database table definition
$table_user = Database::get_main_table(TABLE_MAIN_USER);
//Checking the user language
$languages = api_get_languages();
$language = strtolower($language);
if (!in_array($language, $languages['folder'])) {
$language = api_get_setting('platformLanguage');
}
if (!empty($currentUserId)) {
$creator_id = $currentUserId;
} else {
$creator_id = '';
}
// First check wether the login already exists
if (!self::is_username_available($loginName)) {
return api_set_failure('login-pass already taken');
}
$currentDate = api_get_utc_datetime();
$now = new DateTime($currentDate);
if (empty($expirationDate)) {
// Default expiration date
// if there is a default duration of a valid account then
// we have to change the expiration_date accordingly
if (api_get_setting('account_valid_duration') != '') {
$expirationDate = new DateTime($currentDate);
$days = intval(api_get_setting('account_valid_duration'));
$expirationDate->modify('+'.$days.' day');
}
} else {
$expirationDate = api_get_utc_datetime($expirationDate);
$expirationDate = new \DateTime($expirationDate);
}
$userManager = self::getManager();
/** @var User $user */
$user = $userManager->createUser();
$user
->setLastname($lastName)
->setFirstname($firstName)
->setUsername($loginName)
->setStatus($status)
->setPlainPassword($password)
->setEmail($email)
->setOfficialCode($official_code)
->setPictureUri($picture_uri)
->setCreatorId($creator_id)
->setAuthSource($auth_source)
->setPhone($phone)
->setLanguage($language)
->setRegistrationDate($now)
->setHrDeptId($hr_dept_id)
->setActive($active);
if (!empty($expirationDate)) {
$user->setExpirationDate($expirationDate);
}
$userManager->updateUser($user, true);
$userId = $user->getId();
if (!empty($userId)) {
$return = $userId;
$sql = "UPDATE $table_user SET user_id = $return WHERE id = $return";
Database::query($sql);
if ($isAdmin) {
UserManager::add_user_as_admin($userId);
}
if (api_get_multiple_access_url()) {
UrlManager::add_user_to_url($return, api_get_current_access_url_id());
} else {
//we are adding by default the access_url_user table with access_url_id = 1
UrlManager::add_user_to_url($return, 1);
}
if (!empty($email) && $send_mail) {
$recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS);
$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
$email_admin = api_get_setting('emailAdministrator');
if (api_is_multiple_url_enabled()) {
$access_url_id = api_get_current_access_url_id();
if ($access_url_id != -1) {
$url = api_get_access_url($access_url_id);
$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstName, $lastName)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$loginName."\n".get_lang('Pass')." : ".stripslashes($original_password)."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
}
} else {
$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstName, $lastName)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$loginName."\n".get_lang('Pass')." : ".stripslashes($original_password)."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$_configuration['root_web']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
}
/* MANAGE EVENT WITH MAIL */
if (EventsMail::check_if_using_class('user_registration')) {
$values["about_user"] = $return;
$values["password"] = $original_password;
$values["send_to"] = array($return);
$values["prior_lang"] = null;
EventsDispatcher::events('user_registration', $values);
} else {
$phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null;
$additionalParameters = array(
'smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD,
'userId' => $return,
'mobilePhoneNumber' => $phoneNumber,
'password' => $original_password
);
api_mail_html(
$recipient_name,
$email,
$emailsubject,
$emailbody,
$sender_name,
$email_admin,
null,
null,
null,
$additionalParameters
);
}
/* ENDS MANAGE EVENT WITH MAIL */
}
Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $return);
} else {
return api_set_failure('error inserting in Database');
}
if (is_array($extra) && count($extra) > 0) {
$res = true;
foreach ($extra as $fname => $fvalue) {
$res = $res && self::update_extra_field_value($return, $fname, $fvalue);
}
}
self::update_extra_field_value($return, 'already_logged_in', 'false');
if (!empty($hook)) {
$hook->setEventData(array(
'return' => $return,
'originalPassword' => $original_password
));
$hook->notifyCreateUser(HOOK_EVENT_TYPE_POST);
}
return $return;
}
/**
* Can user be deleted? This function checks whether there's a course
* in which the given user is the
* only course administrator. If that is the case, the user can't be
* deleted because the course would remain without a course admin.
* @param int $user_id The user id
* @return boolean true if user can be deleted
* @assert (null) === false
* @assert (-1) === false
* @assert ('abc') === false
*/
public static function can_delete_user($user_id)
{
global $_configuration;
if (isset($_configuration['deny_delete_users']) &&
$_configuration['deny_delete_users'] == true
) {
return false;
}
$table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
if ($user_id != strval(intval($user_id))) {
return false;
}
if ($user_id === false) {
return false;
}
$sql = "SELECT * FROM $table_course_user
WHERE status = '1' AND user_id = '".$user_id."'";
$res = Database::query($sql);
while ($course = Database::fetch_object($res)) {
$sql = "SELECT user_id FROM $table_course_user
WHERE status='1' AND c_id ='".Database::escape_string($course->c_id)."'";
$res2 = Database::query($sql);
if (Database::num_rows($res2) == 1) {
return false;
}
}
return true;
}
/**
* Delete a user from the platform, and all its belongings. This is a
* very dangerous function that should only be accessible by
* super-admins. Other roles should only be able to disable a user,
* which removes access to the platform but doesn't delete anything.
* @param int The ID of th user to be deleted
* @return boolean true if user is successfully deleted, false otherwise
* @assert (null) === false
* @assert ('abc') === false
*/
public static function delete_user($user_id)
{
if ($user_id != strval(intval($user_id))) {
return false;
}
if ($user_id === false) {
return false;
}
if (!self::can_delete_user($user_id)) {
return false;
}
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
$usergroup_rel_user = Database :: get_main_table(TABLE_USERGROUP_REL_USER);
$table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
$table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
$table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
$table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
$table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
$table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
$table_group = Database :: get_course_table(TABLE_GROUP_USER);
$table_work = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
// Unsubscribe the user from all groups in all his courses
$sql = "SELECT c.id FROM $table_course c, $table_course_user cu
WHERE
cu.user_id = '".$user_id."' AND
relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
c.id = cu.c_id";
$res = Database::query($sql);
while ($course = Database::fetch_object($res)) {
$sql = "DELETE FROM $table_group
WHERE c_id = {$course->id} AND user_id = $user_id";
Database::query($sql);
}
// Unsubscribe user from all classes
//Classes are not longer supported
/* $sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
Database::query($sql); */
// Unsubscribe user from usergroup_rel_user
$sql = "DELETE FROM $usergroup_rel_user WHERE user_id = '".$user_id."'";
Database::query($sql);
// Unsubscribe user from all courses
$sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
Database::query($sql);
// Unsubscribe user from all courses in sessions
$sql = "DELETE FROM $table_session_course_user WHERE user_id = '".$user_id."'";
Database::query($sql);
// If the user was added as a id_coach then set the current admin as coach see BT#
$currentUserId = api_get_user_id();
$sql = "UPDATE $table_session SET id_coach = $currentUserId WHERE id_coach = '".$user_id."'";
Database::query($sql);
$sql = "UPDATE $table_session SET id_coach = $currentUserId WHERE session_admin_id = '".$user_id."'";
Database::query($sql);
// Unsubscribe user from all sessions
$sql = "DELETE FROM $table_session_user WHERE user_id = '".$user_id."'";
Database::query($sql);
// Delete user picture
/* TODO: Logic about api_get_setting('split_users_upload_directory') == 'true'
a user has 4 different sized photos to be deleted. */
$user_info = api_get_user_info($user_id);
if (strlen($user_info['picture_uri']) > 0) {
$path = self::getUserPathById($user_id);
$img_path = $path.$user_info['picture_uri'];
if (file_exists($img_path))
unlink($img_path);
}
// Delete the personal course categories
$course_cat_table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
$sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
Database::query($sql);
// Delete user from database
$sql = "DELETE FROM $table_user WHERE user_id = '".$user_id."'";
Database::query($sql);
// Delete user from the admin table
$sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
Database::query($sql);
// Delete the personal agenda-items from this user
$agenda_table = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
$sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
Database::query($sql);
$gradebook_results_table = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
$sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
Database::query($sql);
$extraFieldValue = new ExtraFieldValue('user');
$extraFieldValue->deleteValuesByItem($user_id);
if (api_get_multiple_access_url()) {
$url_id = api_get_current_access_url_id();
UrlManager::delete_url_rel_user($user_id, $url_id);
} else {
//we delete the user from the url_id =1
UrlManager::delete_url_rel_user($user_id, 1);
}
if (api_get_setting('allow_social_tool') == 'true') {
//Delete user from portal groups
$group_list = GroupPortalManager::get_groups_by_user($user_id);
if (!empty($group_list)) {
foreach ($group_list as $group_id => $data) {
GroupPortalManager::delete_user_rel_group($user_id, $group_id);
}
}
// Delete user from friend lists
SocialManager::remove_user_rel_user($user_id, true);
}
// Removing survey invitation
SurveyManager::delete_all_survey_invitations_by_user($user_id);
// Delete students works
$sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
Database::query($sql);
// Add event to system log
$user_id_manager = api_get_user_id();
Event::addEvent(
LOG_USER_DELETE,
LOG_USER_ID,
$user_id,
api_get_utc_datetime(),
$user_id_manager
);
Event::addEvent(
LOG_USER_DELETE,
LOG_USER_OBJECT,
$user_info,
api_get_utc_datetime(),
$user_id_manager
);
return true;
}
/**
* Deletes users completely. Can be called either as:
* - UserManager :: delete_users(1, 2, 3); or
* - UserManager :: delete_users(array(1, 2, 3));
* @param array|int $ids
* @return boolean True if at least one user was successfuly deleted. False otherwise.
* @author Laurent Opprecht
* @uses UserManager::delete_user() to actually delete each user
* @assert (null) === false
* @assert (-1) === false
* @assert (array(-1)) === false
*/
static function delete_users($ids = array())
{
$result = false;
$ids = is_array($ids) ? $ids : func_get_args();
if (!is_array($ids) or count($ids) == 0) { return false; }
$ids = array_map('intval', $ids);
foreach ($ids as $id) {
if (empty($id) or $id < 1) { continue; }
$deleted = self::delete_user($id);
$result = $deleted || $result;
}
return $result;
}
/**
* Disable users. Can be called either as:
* - UserManager :: deactivate_users(1, 2, 3);
* - UserManager :: deactivate_users(array(1, 2, 3));
* @param array|int $ids
* @return boolean
* @author Laurent Opprecht
* @assert (null) === false
* @assert (array(-1)) === false
*/
static function deactivate_users($ids = array())
{
if (empty($ids)) {
return false;
}
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
$ids = is_array($ids) ? $ids : func_get_args();
$ids = array_map('intval', $ids);
$ids = implode(',', $ids);
$sql = "UPDATE $table_user SET active = 0 WHERE user_id IN ($ids)";
$r = Database::query($sql);
if ($r !== false) {
Event::addEvent(LOG_USER_DISABLE, LOG_USER_ID, $ids);
}
return $r;
}
/**
* Enable users. Can be called either as:
* - UserManager :: activate_users(1, 2, 3);
* - UserManager :: activate_users(array(1, 2, 3));
* @param array|int IDs of the users to enable
* @return boolean
* @author Laurent Opprecht
* @assert (null) === false
* @assert (array(-1)) === false
*/
static function activate_users($ids = array())
{
if (empty($ids)) {
return false;
}
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
$ids = is_array($ids) ? $ids : func_get_args();
$ids = array_map('intval', $ids);
$ids = implode(',', $ids);
$sql = "UPDATE $table_user SET active = 1 WHERE user_id IN ($ids)";
$r = Database::query($sql);
if ($r !== false) {
Event::addEvent(LOG_USER_ENABLE,LOG_USER_ID,$ids);
}
return $r;
}
/**
* Update user information with new openid
* @param int $user_id
* @param string $openid
* @return boolean true if the user information was updated
* @assert (false,'') === false
* @assert (-1,'') === false
*/
public static function update_openid($user_id, $openid)
{
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
if ($user_id != strval(intval($user_id)))
return false;
if ($user_id === false)
return false;
$sql = "UPDATE $table_user SET
openid='".Database::escape_string($openid)."'";
$sql .= " WHERE user_id='$user_id'";
return Database::query($sql);
}
/**
* Update user information with all the parameters passed to this function
* @param int The ID of the user to be updated
* @param string The user's firstname
* @param string The user's lastname
* @param string The user's username (login)
* @param string The user's password
* @param string The authentication source (default: "platform")
* @param string The user's e-mail address
* @param int The user's status
* @param string The user's official code (usually just an internal institutional code)
* @param string The user's phone number
* @param string The user's picture URL (internal to the Chamilo directory)
* @param int The user ID of the person who registered this user (optional, defaults to null)
* @param int The department of HR in which the user is registered (optional, defaults to 0)
* @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
* @return boolean true if the user information was updated
* @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
*/
public static function update_user(
$user_id,
$firstname,
$lastname,
$username,
$password = null,
$auth_source = null,
$email,
$status,
$official_code,
$phone,
$picture_uri,
$expiration_date,
$active,
$creator_id = null,
$hr_dept_id = 0,
$extra = null,
$language = 'english',
$encrypt_method = '',
$send_email = false,
$reset_password = 0
) {
$hook = HookUpdateUser::create();
if (!empty($hook)) {
$hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
}
global $_configuration;
$original_password = $password;
if (empty($user_id)) {
return false;
}
$user_info = api_get_user_info($user_id, false, true);
if ($reset_password == 0) {
$password = null;
$auth_source = $user_info['auth_source'];
} elseif ($reset_password == 1) {
$original_password = $password = api_generate_password();
$auth_source = PLATFORM_AUTH_SOURCE;
} elseif ($reset_password == 2) {
$password = $password;
$auth_source = PLATFORM_AUTH_SOURCE;
} elseif ($reset_password == 3) {
$password = $password;
$auth_source = $auth_source;
}
if ($user_id != strval(intval($user_id))) {
return false;
}
if ($user_id === false) {
return false;
}
//Checking the user language
$languages = api_get_languages();
if (!in_array($language, $languages['folder'])) {
$language = api_get_setting('platformLanguage');
}
$change_active = 0;
if ($user_info['active'] != $active) {
$change_active = 1;
}
$userManager = self::getManager();
/** @var Chamilo\UserBundle\Entity\User $user */
$user = self::getRepository()->find($user_id);
if (empty($user)) {
return false;
}
if (!empty($expiration_date)) {
$expiration_date = api_get_utc_datetime($expiration_date);
$expiration_date = new \DateTime($expiration_date);
}
$user
->setLastname($lastname)
->setFirstname($firstname)
->setUsername($username)
->setStatus($status)
->setAuthSource($auth_source)
->setLanguage($language)
->setEmail($email)
->setOfficialCode($official_code)
->setPhone($phone)
->setPictureUri($picture_uri)
->setExpirationDate($expiration_date)
->setActive($active)
->setHrDeptId($hr_dept_id)
;
if (!is_null($password)) {
$user->setPlainPassword($password);
}
$userManager->updateUser($user, true);
if ($change_active == 1) {
if ($active == 1) {
$event_title = LOG_USER_ENABLE;
} else {
$event_title = LOG_USER_DISABLE;
}
Event::addEvent($event_title, LOG_USER_ID, $user_id);
}
if (is_array($extra) && count($extra) > 0) {
$res = true;
foreach ($extra as $fname => $fvalue) {
$res = $res && self::update_extra_field_value(
$user_id,
$fname,
$fvalue
);
}
}
if (!empty($email) && $send_email) {
$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
$email_admin = api_get_setting('emailAdministrator');
if (api_is_multiple_url_enabled()) {
$access_url_id = api_get_current_access_url_id();
if ($access_url_id != -1) {
$url = api_get_access_url($access_url_id);
$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
}
} else {
$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$_configuration['root_web']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
}
api_mail_html(
$recipient_name,
$email,
$emailsubject,
$emailbody,
$sender_name,
$email_admin
);
}
if (!empty($hook)) {
$hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
}
return $user->getId();
}
/**
* Disables or enables a user
* @param int user_id
* @param int Enable or disable
* @return void
* @assert (-1,0) === false
* @assert (1,1) === true
*/
private static function change_active_state($user_id, $active)
{
if (strval(intval($user_id)) != $user_id) {
return false;
}
if ($user_id < 1) {
return false;
}
$user_id = intval($user_id);
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
$sql = "UPDATE $table_user SET active = '$active' WHERE user_id = '$user_id';";
$r = Database::query($sql);
$ev = LOG_USER_DISABLE;
if ($active == 1) {
$ev = LOG_USER_ENABLE;
}
if ($r !== false) {
Event::addEvent($ev, LOG_USER_ID, $user_id);
}
return $r;
}
/**
* Disables a user
* @param int User id
* @return bool
* @uses UserManager::change_active_state() to actually disable the user
* @assert (0) === false
*/
public static function disable($user_id)
{
if (empty($user_id)) {
return false;
}
self::change_active_state($user_id, 0);
return true;
}
/**
* Enable a user
* @param int User id
* @return bool
* @uses UserManager::change_active_state() to actually disable the user
* @assert (0) === false
*/
public static function enable($user_id)
{
if (empty($user_id)) {
return false;
}
self::change_active_state($user_id, 1);
return true;
}
/**
* Returns the user's id based on the original id and field name in
* the extra fields. Returns 0 if no user was found. This function is
* mostly useful in the context of a web services-based sinchronization
* @param string Original user id
* @param string Original field name
* @return int User id
* @assert ('0','---') === 0
*/
public static function get_user_id_from_original_id($original_user_id_value, $original_user_id_name)
{
$t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
$t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
$extraFieldType = EntityExtraField::USER_FIELD_TYPE;
$sql = "SELECT item_id as user_id
FROM $t_uf uf
INNER JOIN $t_ufv ufv
ON ufv.field_id=uf.id
WHERE
variable='$original_user_id_name' AND
value='$original_user_id_value' AND
extra_field_type = $extraFieldType