-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathUser.php
More file actions
3017 lines (2558 loc) · 81 KB
/
Copy pathUser.php
File metadata and controls
3017 lines (2558 loc) · 81 KB
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
require_once(dirname(__DIR__) . '/global.php');
require_once(__DIR__ . '/Account.php');
require_once(__DIR__ . '/Badge.php');
require_once(__DIR__ . '/CookieStorage.php');
require_once(__DIR__ . '/CampaignTracker.php');
require_once(__DIR__ . '/Invitation.php');
require_once(dirname(__DIR__) . '/swiftmailer/lib/swift_required.php');
/**
* This class represents a registerd user in the system
*
* Usage:
* <code>
* // Getting currently logged in user
* // Returns User object, same as User::require_login()
* $user = StartupAPI::requireLogin();
* echo 'Welcome, ' . $user->getName() . '!';
* </code>
*
* Note that unless you are absolutely sure that data in your application is only
* specific to one individual, you might want to use Accounts to connect your data
* instead of Users - this way you will be able to add multi-user accounts in the
* future when you're ready.
*
* <code>
* // Getting currently selected account
* $account = $user->getCurrentAccount();
* </code>
*
* Each user gets a personal account created for them out of the box to make it
* easier for you to transition to accounts in the future.
*
* @see Account
*
* @package StartupAPI
*/
class User {
/**
* Checks if user is logged in and returns use object or redirects to login page
*
* This is the easiest way to protect a page from public viewing
*
* Usage:
* <code>
* // Getting currently logged in user
* $user = StartupAPI::requireLogin();
* </code>
*
* Although preferred method is to call a method on StartupAPI object
* <code>
* $user = StartupAPI::requireLogin();
* </code>
*
* @param boolean $allow_impersonation Set to false if you do not want to allow impersonation
*
* @return User Current user
*/
public static function require_login($allow_impersonation = true) {
$user = self::get($allow_impersonation);
if (!is_null($user)) {
return $user;
} else {
self::redirectToLogin();
}
}
/**
* Checks if user is logged in and returns use object or null if user is not logged in
* Disabled users are not allowed to login unless they are being impersonated.
*
* Usage:
* <code>
* // Getting currently logged in user
* $user = User::get();
*
* if (!is_null($user)) {
* echo 'Welcome, ' . $user->getName() . '!';
* }
* </code>
*
* Although preferred method is to call a method on StartupAPI object
* <code>
* $user = StartupAPI::getUser();
* </code>
*
* @param boolean $allow_impersonation Set to false if you do not want to allow impersonation
*
* @return User|null Current user or null if user is not logged in
*/
public static function get($allow_impersonation = true) {
$storage = new MrClay_CookieStorage(array(
'secret' => UserConfig::$SESSION_SECRET,
'mode' => MrClay_CookieStorage::MODE_ENCRYPT,
'path' => UserConfig::$SITEROOTURL,
'httponly' => true
));
$userid = $storage->fetch(UserConfig::$session_userid_key);
if (is_numeric($userid)) {
$user = self::getUser($userid);
if (is_null($user)) {
return null;
}
// if email verification is required, force users to verify it
if (!$user->is_email_verified && UserConfig::$requireVerifiedEmail && !UserConfig::$IGNORE_REQUIRED_EMAIL_VERIFICATION) {
self::redirectToEmailVerification();
}
// only forsing password reset on non-impersonated users
if ($user->requiresPasswordReset() &&
!UsernamePasswordAuthenticationModule::$IGNORE_PASSWORD_RESET) {
self::redirectToPasswordReset();
}
// don't even try impersonating if not admin
if (!$allow_impersonation || !$user->isAdmin()) {
if ($user->isDisabled()) {
return null;
}
return $user;
}
// now, let's check impersonation
$impersonated_userid = $storage->fetch(UserConfig::$impersonation_userid_key);
$impersonated_user = self::getUser($impersonated_userid);
// do not impersonate unknown user or the same user
if (is_null($impersonated_user) || $user->isTheSameAs($impersonated_user)) {
if ($user->isDisabled()) {
return null;
}
return $user;
}
$impersonated_user->impersonator = $user;
return $impersonated_user;
} else {
return null;
}
}
/**
* Updates user activity when user returns to the site more then a day after last access
*
* @throws StartupAPIException
*
* @internal
*/
public static function updateReturnActivity() {
$storage = new MrClay_CookieStorage(array(
'secret' => UserConfig::$SESSION_SECRET,
'mode' => MrClay_CookieStorage::MODE_ENCRYPT,
'path' => UserConfig::$SITEROOTURL,
'httponly' => true
));
$last = $storage->fetch(UserConfig::$last_login_key);
if (!$storage->store(UserConfig::$last_login_key, time())) {
throw new StartupAPIException(implode('; ', $storage->errors));
}
$user = self::get();
if (!is_null($user) && $last > 0
&& $last < time() - UserConfig::$last_login_session_length * 60) {
if ($last > time() - 86400) {
$user->recordActivity(USERBASE_ACTIVITY_RETURN_DAILY);
} else if ($last > time() - 7 * 86400) {
$user->recordActivity(USERBASE_ACTIVITY_RETURN_WEEKLY);
} else if ($last > time() - 30 * 86400) {
$user->recordActivity(USERBASE_ACTIVITY_RETURN_MONTHLY);
}
}
}
/**
* Sets user's referrer based on CampaignTracker's information
*
* @throws DBException
*
* @internal Should not be used other then by login methods
*/
private function setReferer() {
$referer = CampaignTracker::getReferer();
if (is_null($referer)) {
return;
}
$db = UserConfig::getDB();
if ($stmt = $db->prepare('UPDATE u_users SET referer = ? WHERE id = ?')) {
if (!$stmt->bind_param('si', $referer, $this->userid)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
}
/**
* Return the URL this user came from when registered on the site.
*
* @return string Referer URL
*
* @throws DBException
*/
public function getReferer() {
$db = UserConfig::getDB();
$referer = null;
if ($stmt = $db->prepare('SELECT referer FROM u_users WHERE id = ?')) {
if (!$stmt->bind_param('i', $this->userid)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->bind_result($referer)) {
throw new DBBindResultException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->fetch();
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $referer;
}
/**
* Returns a list of users by referrer
*
* @param int $days Number of days to look back for
*
* @return array Array with URLs as keys and values are arrays of users
*
* @throws DBException
*/
public static function getReferers($days = 30) {
$db = UserConfig::getDB();
$sources = array();
if ($stmt = $db->prepare('SELECT referer, id, status, name, username, email, requirespassreset, fb_id, fb_link, UNIX_TIMESTAMP(regtime), points, email_verified FROM u_users WHERE referer IS NOT NULL AND regtime > DATE_SUB(NOW(), INTERVAL ? DAY) ORDER BY regtime DESC')) {
if (!$stmt->bind_param('i', $days)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($referer, $userid, $status, $name, $username, $email, $requirespassreset, $fb_id, $fb_link, $regtime, $points, $is_email_verified)) {
throw new DBBindResultException($db, $stmt);
}
while ($stmt->fetch() === TRUE) {
$sources[$referer][] = new self($userid, $status, $name, $username, $email, $requirespassreset, $fb_id, $fb_link, $regtime, $points, $is_email_verified);
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $sources;
}
/**
* Sets user's campaign they came from
*
* @throws DBException
*
* @internal Used by login/registration scripts to record user's campaign
*/
private function setRegCampaign() {
$campaign = CampaignTracker::getCampaign();
if (is_null($campaign) || !$campaign) {
return;
}
$db = UserConfig::getDB();
$cmp_source_id = null;
if (array_key_exists('cmp_source', $campaign)) {
$cmp_source_id = CampaignTracker::getCampaignSourceID($campaign['cmp_source']);
}
$cmp_medium_id = null;
if (array_key_exists('cmp_medium', $campaign)) {
$cmp_medium_id = CampaignTracker::getCampaignMediumID($campaign['cmp_medium']);
}
$cmp_keywords_id = null;
if (array_key_exists('cmp_keywords', $campaign)) {
$cmp_keywords_id = CampaignTracker::getCampaignKeywordsID($campaign['cmp_keywords']);
}
$cmp_content_id = null;
if (array_key_exists('cmp_content', $campaign)) {
$cmp_content_id = CampaignTracker::getCampaignContentID($campaign['cmp_content']);
;
}
$cmp_name_id = null;
if (array_key_exists('cmp_name', $campaign)) {
$cmp_name_id = CampaignTracker::getCampaignNameID($campaign['cmp_name']);
}
// update user record with compaign IDs
if ($stmt = $db->prepare('UPDATE u_users SET
reg_cmp_source_id = ?,
reg_cmp_medium_id = ?,
reg_cmp_keywords_id = ?,
reg_cmp_content_id = ?,
reg_cmp_name_id = ?
WHERE id = ?')) {
if (!$stmt->bind_param('sssssi', $cmp_source_id, $cmp_medium_id, $cmp_keywords_id, $cmp_content_id, $cmp_name_id, $this->userid)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
}
/**
* Returns campaign they came from when registerd
*
* @return array Array of campaign parameters
*
* @throws DBException
*/
public function getCampaign() {
$db = UserConfig::getDB();
$campaign = array();
if ($stmt = $db->prepare('SELECT cmp.name, cmp_content.content, cmp_keywords.keywords, cmp_medium.medium, cmp_source.source
FROM u_users AS users
LEFT JOIN u_cmp AS cmp ON users.reg_cmp_name_id = cmp.id
LEFT JOIN u_cmp_content AS cmp_content ON users.reg_cmp_content_id = cmp_content.id
LEFT JOIN u_cmp_keywords AS cmp_keywords ON users.reg_cmp_keywords_id = cmp_keywords.id
LEFT JOIN u_cmp_medium AS cmp_medium ON users.reg_cmp_medium_id = cmp_medium.id
LEFT JOIN u_cmp_source AS cmp_source ON users.reg_cmp_source_id = cmp_source.id
WHERE users.id = ?')) {
if (!$stmt->bind_param('i', $this->userid)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($cmp_name, $cmp_content, $cmp_keywords, $cmp_medium, $cmp_source)) {
throw new DBBindResultException($db, $stmt);
}
if ($stmt->fetch() === TRUE) {
$campaign['cmp_name'] = $cmp_name;
$campaign['cmp_content'] = $cmp_content;
$campaign['cmp_keywords'] = $cmp_keywords;
$campaign['cmp_medium'] = $cmp_medium;
$campaign['cmp_source'] = $cmp_source;
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $campaign;
}
/**
* Returns 2-dimensional array with first keys for each campaign param and second keys for each value of that parameter, values of the array are arrays of users.
*
* @param int $days A number of days to look back for
*
* @return array Array of campaign users data
*
* @throws DBException
*/
public static function getCampaigns($days = 30) {
$db = UserConfig::getDB();
$campaigns = array();
if ($stmt = $db->prepare('SELECT cmp.name, cmp_content.content, cmp_keywords.keywords, cmp_medium.medium, cmp_source.source,
users.id, status, users.name, username, email, requirespassreset, fb_id, fb_link, UNIX_TIMESTAMP(regtime), points, email_verified
FROM u_users AS users
LEFT JOIN u_cmp AS cmp ON users.reg_cmp_name_id = cmp.id
LEFT JOIN u_cmp_content AS cmp_content ON users.reg_cmp_content_id = cmp_content.id
LEFT JOIN u_cmp_keywords AS cmp_keywords ON users.reg_cmp_keywords_id = cmp_keywords.id
LEFT JOIN u_cmp_medium AS cmp_medium ON users.reg_cmp_medium_id = cmp_medium.id
LEFT JOIN u_cmp_source AS cmp_source ON users.reg_cmp_source_id = cmp_source.id
WHERE regtime > DATE_SUB(NOW(), INTERVAL ? DAY)
AND (reg_cmp_name_id IS NOT NULL
OR reg_cmp_content_id IS NOT NULL
OR reg_cmp_keywords_id IS NOT NULL
OR reg_cmp_medium_id IS NOT NULL
OR reg_cmp_source_id IS NOT NULL
)
ORDER BY regtime DESC')) {
if (!$stmt->bind_param('i', $days)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($cmp_name, $cmp_content, $cmp_keywords, $cmp_medium, $cmp_source, $userid, $status, $name, $username, $email, $requirespassreset, $fb_id, $fb_link, $regtime, $points, $is_email_verified)) {
throw new DBBindResultException($db, $stmt);
}
while ($stmt->fetch() === TRUE) {
$user = new self($userid, $status, $name, $username, $email, $requirespassreset, $fb_id, $fb_link, $regtime, $points, $is_email_verified);
if (!is_null($cmp_name)) {
$campaigns['cmp_name'][$cmp_name][] = $user;
}
if (!is_null($cmp_content)) {
$campaigns['cmp_content'][$cmp_content][] = $user;
}
if (!is_null($cmp_keywords)) {
$campaigns['cmp_keywords'][$cmp_keywords][] = $user;
}
if (!is_null($cmp_medium)) {
$campaigns['cmp_medium'][$cmp_medium][] = $user;
}
if (!is_null($cmp_source)) {
$campaigns['cmp_source'][$cmp_source][] = $user;
}
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $campaigns;
}
/**
* Creates a personal account for the user meking them an admin
*
* @param bool $set_as_current To set as current account (default) or not
*
* @return Account
*/
public function createPersonalAccount($set_as_current = true) {
$personal = Account::createPersonalAccount($this);
if ($set_as_current) {
$personal->setAsCurrent($this);
}
return $personal;
}
/**
* Returns invitation that was used to invite this user
*
* @return Invitation
*
* @throws DBException
*/
public function getInvitation() {
return Invitation::getUserInvitation($this);
}
/**
* This method is called when new user is created
*
* @throws DBException
*/
private function init() {
$invitation_code = null;
if (array_key_exists(UserConfig::$invitation_code_key, $_SESSION)) {
$invitation_code = $_SESSION[UserConfig::$invitation_code_key];
unset($_SESSION[UserConfig::$invitation_code_key]);
}
$invitation = null;
if (!is_null($invitation_code)) {
$invitation = Invitation::getByCode($invitation_code);
}
if (!is_null($invitation)) {
$invitation->setUser($this);
$invitation->save();
}
$db = UserConfig::getDB();
$userid = $this->getID();
if ($stmt = $db->prepare('INSERT INTO u_user_preferences (user_id) VALUES (?)')) {
if (!$stmt->bind_param('i', $userid)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt, "Can't initialize user preferences");
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db, "Can't prepare DB statement to initialize user preferences");
}
$invitation_account = null;
$plan = null;
if (!is_null($invitation)) {
$invitation_account = $invitation->getAccount();
// only add to account if invited by the admin of a non-individual account
if ($invitation_account !== NULL &&
!$invitation_account->isIndividual() &&
$invitation_account->getUserRole($invitation->getIssuer()) === Account::ROLE_ADMIN
) {
$invitation_account->addUser($this);
}
$plan = $invitation->getPlan();
}
$new_user_account = null;
if (is_null($invitation_account) || UserConfig::$createPersonalAccountsIfInvitedToGroupAccount) {
if ($plan) {
$new_user_account = Account::createAccount($this->name, $plan->getSlug(), null, $this, Account::ROLE_ADMIN);
} else {
$new_user_account = $this->createPersonalAccount(false);
}
}
$current_account = is_null($invitation_account) ? $new_user_account : $invitation_account;
$current_account->setAsCurrent($this);
if (!is_null(UserConfig::$onCreate)) {
call_user_func_array(UserConfig::$onCreate, array($this));
}
if (!is_null(UserConfig::$email_module)) {
UserConfig::$email_module->registerSubscriber($this);
}
}
/**
* Verifies email link code and marks user's email as verified.
*
* If optional User object is passed, will only verify code for this user,
* otherwise will search among all users in the system.
*
* Will also reset the code if successful
*
* @param string $code Code to verify
* @param User $user Optional user object if user is logged in
*
* @return boolean Is code associated with a user or not
*
* @throws DBException
*/
public static function verifyEmailLinkCode($code, User $user = null) {
$db = UserConfig::getDB();
$verified = false;
$code = trim($code);
/*
* If code is empty, fail silently
*/
if (strlen($code) == 0) {
return false;
}
if (is_null($user)) {
$query = 'UPDATE u_users
SET email_verified = 1,
email_verification_code = null,
email_verification_code_time = null
WHERE email_verification_code = ?
AND email_verification_code_time > DATE_SUB(NOW(), INTERVAL ? DAY)';
} else {
$query = 'UPDATE u_users
SET email_verified = 1,
email_verification_code = null,
email_verification_code_time = null
WHERE id = ?
AND email_verification_code = ?
AND email_verification_code_time > DATE_SUB(NOW(), INTERVAL ? DAY)';
}
if ($stmt = $db->prepare($query)) {
if (is_null($user)) {
if (!$stmt->bind_param('si', $code, UserConfig::$emailVerificationCodeExpiresInDays)) {
throw new DBBindParamException($db, $stmt);
}
} else {
$user_id = $user->getID();
if (!$stmt->bind_param('isi', $user_id, $code, UserConfig::$emailVerificationCodeExpiresInDays)) {
throw new DBBindParamException($db, $stmt);
}
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$verified = ($db->affected_rows == 1);
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $verified;
}
public function getEmailVerificationCode() {
$db = UserConfig::getDB();
$code = substr(base64_encode(UserTools::randomBytes(50)), 0, 10);
if ($stmt = $db->prepare('UPDATE u_users SET
email_verification_code = ?,
email_verification_code_time = now()
WHERE id = ?')
) {
if (!$stmt->bind_param('si', $code, $this->userid)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $code;
}
/**
* Sends email verification emai to user's email address
*
* Generates a new verification code and sends it to the user's email address
*
* @throws DBException
*/
public function sendEmailVerificationCode() {
$email = $this->getEmail();
$name = $this->getName();
// Silently fail to avoid email discovery
if (is_null($email)) {
return;
}
$code = $this->getEmailVerificationCode();
$verification_link = UserConfig::$USERSROOTFULLURL . '/verify_email.php?code=' . urlencode($code);
$message_body = call_user_func_array(UserConfig::$onRenderVerificationCodeEmail, array($verification_link, $code));
$subject = UserConfig::$emailVerificationSubject;
$message = new Swift_Message($subject, $message_body);
$message->setFrom(array(UserConfig::$supportEmailFromEmail => UserConfig::$supportEmailFromName));
$message->setTo(array($email => $name));
$message->setReplyTo(array(UserConfig::$supportEmailReplyTo));
$headers = $message->getHeaders();
$headers->addTextHeader('X-Mailer', UserConfig::$supportEmailXMailer);
try {
$result = UserConfig::getMailer()->send($message);
} catch (Exception $e) {
UserTools::debug($e->getMessage());
}
}
/**
* Sends email message inviting another person to join the system
*
* @param string $name Name of the receipient
* @param string $email Email of reciepient
* @param string $note (optional) Invitation message
* @param Account $account (optional) Account object if user is invited to join an account
*/
public function sendInvitation($name, $email, $account = null) {
Invitation::sendUserInvitation($this, $name, $email, $account);
}
/**
* Returns invitations initiated by a user
*
* @return Invitation[] Invitations sent, but not accepted yet
*/
public function getSentInvitations() {
return Invitation::getSent(false, $this);
}
/**
* Returns an array of invitations that were accepted
*
* @return Invitation[] Accepted invitations
*/
public function getAcceptedInvitations() {
return Invitation::getAccepted(false, $this);
}
/**
* Create new user based on facebook info
*
* Used by FacebookAuthenticationModule
*
* @param string $name User's display name
* @param int $fb_id Facebook user ID
* @param array $me Extra user info key/value pairs from /me Graph API call
*
* @return User Newly created user object
*
* @throws DBException
*/
public static function createNewFacebookUser($name, $fb_id, $fb_link = null, $me = null) {
$name = mb_convert_encoding($name, 'UTF-8');
$db = UserConfig::getDB();
$email = null;
if (array_key_exists('email', $me)) {
$email = $me['email'];
}
$existing_users = User::getUsersByEmailOrUsername($email);
if (count($existing_users) > 0) {
throw new ExistingUserException($existing_users[0]);
}
$user = null;
if ($stmt = $db->prepare("INSERT INTO u_users (name, regmodule, tos_version, email, fb_id, fb_link) VALUES (?, 'facebook', ?, ?, ?, ?)")) {
if (!$stmt->bind_param('sisis', $name, UserConfig::$currentTOSVersion, $email, $fb_id, $fb_link)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$id = $stmt->insert_id;
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
$user = self::getUser($id);
$user->setReferer();
$user->setRegCampaign();
$user->init();
$user->sendEmailVerificationCode();
return $user;
}
/*
*/
/**
* Create new user without credentials
*
* Used primarily by modules that will store credentials separately from user table
* Can also be used directly to create "shallow" accounts
*
* @param StartupAPIModule $module Registratin module used when registering the user
* @param string $name User's display name
* @param string $email User's emaol or null if no email is known
* @param boolean $send_verification_code Whatever to send verification email or not
*
* @return User Newly created user object
*
* @throws DBException
*/
public static function createNewWithoutCredentials(StartupAPIModule $module, $name, $email = null, $send_verification_code = TRUE) {
$module_id = $module->getID();
$name = mb_convert_encoding($name, 'UTF-8');
$db = UserConfig::getDB();
$user = null;
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($email === FALSE) {
$email = null;
}
if ($email) {
$existing_users = User::getUsersByEmailOrUsername($email);
if (count($existing_users) > 0) {
throw new ExistingUserException($existing_users[0]);
}
}
if ($stmt = $db->prepare('INSERT INTO u_users (name, email, regmodule, tos_version) VALUES (?, ?, ?, ?)')) {
if (!$stmt->bind_param('sssi', $name, $email, $module_id, UserConfig::$currentTOSVersion)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$id = $stmt->insert_id;
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
$user = self::getUser($id);
$user->setReferer();
$user->setRegCampaign();
$user->init();
if ($send_verification_code) {
$user->sendEmailVerificationCode();
}
return $user;
}
/**
* Create new user with username and password
*
* Used by UsernamePasswordAuthenticationModule
*
* @param string $name User's display name
* @param string $username User's login name/username
* @param string $email User's email
* @param string $password User's password
*
* @return User Newly created user object
*
* @throws DBException
*/
public static function createNew($name, $username, $email, $password) {
$name = mb_convert_encoding($name, 'UTF-8');
$username = mb_convert_encoding($username, 'UTF-8');
$db = UserConfig::getDB();
$user = null;
$salt = substr(base64_encode(UserTools::randomBytes(50)), 0, 13);
$pass = sha1($salt . $password);
if ($stmt = $db->prepare("INSERT INTO u_users (regmodule, tos_version, name, username, email, pass, salt) VALUES ('userpass', ?, ?, ?, ?, ?, ?)")) {
if (!$stmt->bind_param('isssss', UserConfig::$currentTOSVersion, $name, $username, $email, $pass, $salt)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$id = $stmt->insert_id;
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
$user = self::getUser($id);
$user->setReferer();
$user->setRegCampaign();
$user->init();
$user->sendEmailVerificationCode();
return $user;
}
/**
* Deletes user from the system
*
* @throws DBException
*/
public function delete() {
$username = mb_convert_encoding($this->username, 'UTF-8');
$db = UserConfig::getDB();
if ($stmt = $db->prepare('DELETE FROM u_users WHERE username = ?')) {
if (!$stmt->bind_param('s', $username)) {
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
}
/**
* Returns total number of users in the system
*
* @return int Total number of users (including disabled users)
*
* @throws DBException
*/
public static function getTotalUsers() {
$db = UserConfig::getDB();
$total = 0;
if ($stmt = $db->prepare('SELECT COUNT(*) FROM u_users')) {
if (!$stmt->execute()) {
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($total)) {
throw new DBBindResultException($db, $stmt);
}
$stmt->fetch();
$stmt->close();
} else {
throw new DBPrepareStmtException($db);
}
return $total;
}
/**
* Returns a number of active users (with activity after one day from registration)
*
* If date is passed, will calculate active users as of particular day (used for charts).
* Relatively data-intensive task, try to cache this data when produced (it would not change for the past dates)
*
* @param string $date MySQL-formatted date to get the statistics for
*
* @return int Number of active users
*
* @throws DBException
*/
public static function getActiveUsers($date = null) {
$db = UserConfig::getDB();
$total = 0;
if (UserConfig::$adminActiveOnlyWithPoints) {
$activities_with_points = array();
foreach (UserConfig::$activities as $id => $activity) {
if ($activity[1] > 0) {
$activities_with_points[] = $id;
}
}
// if there are no activities that can earn points, no users are active
if (count($activities_with_points) == 0) {
return 0;
}
$in = implode(', ', $activities_with_points);
$query = 'SELECT count(*) AS total FROM (
SELECT user_id, count(*)
FROM u_activity a
INNER JOIN u_users u
ON a.user_id = u.id
WHERE a.time > DATE_ADD(u.regtime, INTERVAL 1 DAY)
AND a.time > DATE_SUB(' .
(is_null($date) ? 'NOW()' : '?') .
', INTERVAL 30 DAY)' .
(is_null($date) ? '' : ' AND a.time < ?') . '
AND a.activity_id IN (' . $in . ')
GROUP BY user_id
) AS active';
} else {
$query = 'SELECT count(*) AS total FROM (
SELECT user_id, count(*)
FROM u_activity a
INNER JOIN u_users u