/
ScooldUtils.java
executable file
·1978 lines (1777 loc) · 73.8 KB
/
ScooldUtils.java
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
/*
* Copyright 2013-2021 Erudika. https://erudika.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For issues and patches go to: https://github.com/erudika
*/
package com.erudika.scoold.utils;
import com.erudika.para.core.utils.Para;
import com.erudika.para.client.ParaClient;
import com.erudika.para.core.Address;
import com.erudika.para.core.ParaObject;
import com.erudika.para.core.Sysprop;
import com.erudika.para.core.Tag;
import com.erudika.para.core.User;
import com.erudika.para.core.Vote;
import com.erudika.para.core.Webhook;
import com.erudika.para.core.utils.ParaObjectUtils;
import com.erudika.para.core.email.Emailer;
import com.erudika.para.core.utils.Config;
import com.erudika.para.core.utils.Pager;
import com.erudika.para.core.utils.Utils;
import com.erudika.para.core.validation.ValidationUtils;
import com.erudika.scoold.ScooldServer;
import static com.erudika.scoold.ScooldServer.*;
import com.erudika.scoold.core.Comment;
import com.erudika.scoold.core.Feedback;
import com.erudika.scoold.core.Post;
import static com.erudika.scoold.core.Post.ALL_MY_SPACES;
import static com.erudika.scoold.core.Post.DEFAULT_SPACE;
import com.erudika.scoold.core.Profile;
import static com.erudika.scoold.core.Profile.Badge.ENTHUSIAST;
import static com.erudika.scoold.core.Profile.Badge.TEACHER;
import com.erudika.scoold.core.Question;
import com.erudika.scoold.core.Reply;
import com.erudika.scoold.core.Report;
import com.erudika.scoold.core.Revision;
import com.erudika.scoold.core.UnapprovedQuestion;
import com.erudika.scoold.core.UnapprovedReply;
import static com.erudika.scoold.utils.HttpUtils.getCookieValue;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.typesafe.config.ConfigObject;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
/**
*
* @author Alex Bogdanovski [alex@erudika.com]
*/
@Component
@Named
public final class ScooldUtils {
private static final Logger logger = LoggerFactory.getLogger(ScooldUtils.class);
private static final Map<String, String> FILE_CACHE = new ConcurrentHashMap<String, String>();
private static final Set<String> APPROVED_DOMAINS = new HashSet<>();
private static final Set<String> ADMINS = new HashSet<>();
private static final String EMAIL_ALERTS_PREFIX = "email-alerts" + Config.SEPARATOR;
private static final Profile API_USER;
private static final Set<String> CORE_TYPES;
private static final Set<String> HOOK_EVENTS;
private static final Map<String, String> WHITELISTED_MACROS;
private static final Map<String, Object> API_KEYS = new LinkedHashMap<>(); // jti => jwt
private List<Sysprop> allSpaces;
static {
API_USER = new Profile("1", "System");
API_USER.setVotes(1);
API_USER.setCreatorid("1");
API_USER.setTimestamp(Utils.timestamp());
API_USER.setPicture(getGravatar(Config.SUPPORT_EMAIL));
API_USER.setGroups(User.Groups.ADMINS.toString());
CORE_TYPES = new HashSet<>(Arrays.asList(Utils.type(Comment.class),
Utils.type(Feedback.class),
Utils.type(Profile.class),
Utils.type(Question.class),
Utils.type(Reply.class),
Utils.type(Report.class),
Utils.type(Revision.class),
Utils.type(UnapprovedQuestion.class),
Utils.type(UnapprovedReply.class),
// Para core types
Utils.type(Address.class),
Utils.type(Sysprop.class),
Utils.type(Tag.class),
Utils.type(User.class),
Utils.type(Vote.class)
));
HOOK_EVENTS = new HashSet<>(Arrays.asList(
"question.create",
"question.close",
"answer.create",
"answer.accept",
"report.create",
"comment.create",
"user.signup",
"revision.restore"));
WHITELISTED_MACROS = new HashMap<String, String>();
WHITELISTED_MACROS.put("spaces", "#spacespage($spaces)");
WHITELISTED_MACROS.put("webhooks", "#webhookspage($webhooks)");
WHITELISTED_MACROS.put("comments", "#commentspage($commentslist)");
WHITELISTED_MACROS.put("simplecomments", "#simplecommentspage($commentslist)");
WHITELISTED_MACROS.put("postcomments", "#commentspage($showpost.comments)");
WHITELISTED_MACROS.put("replies", "#answerspage($answerslist $showPost)");
WHITELISTED_MACROS.put("feedback", "#questionspage($feedbacklist)");
WHITELISTED_MACROS.put("people", "#peoplepage($userlist)");
WHITELISTED_MACROS.put("questions", "#questionspage($questionslist)");
WHITELISTED_MACROS.put("compactanswers", "#compactanswerspage($answerslist)");
WHITELISTED_MACROS.put("answers", "#answerspage($answerslist)");
WHITELISTED_MACROS.put("reports", "#reportspage($reportslist)");
WHITELISTED_MACROS.put("revisions", "#revisionspage($revisionslist $showPost)");
WHITELISTED_MACROS.put("tags", "#tagspage($tagslist)");
}
private final ParaClient pc;
private final LanguageUtils langutils;
private static ScooldUtils instance;
@Inject private Emailer emailer;
@Inject
public ScooldUtils(ParaClient pc, LanguageUtils langutils) {
this.pc = pc;
this.langutils = langutils;
}
public ParaClient getParaClient() {
return pc;
}
public LanguageUtils getLangutils() {
return langutils;
}
public static ScooldUtils getInstance() {
return instance;
}
static void setInstance(ScooldUtils instance) {
ScooldUtils.instance = instance;
}
static {
// multiple domains/admins are now allowed only in Scoold PRO
String approvedDomains = Config.getConfigParam("approved_domains_for_signups", "");
if (!StringUtils.isBlank(approvedDomains)) {
APPROVED_DOMAINS.add(approvedDomains);
}
// multiple admins are now allowed only in Scoold PRO
String admins = Config.getConfigParam("admins", "");
if (!StringUtils.isBlank(admins)) {
ADMINS.add(admins);
}
}
public static void tryConnectToPara(Callable<Boolean> callable) {
retryConnection(callable, 0);
}
private static void retryConnection(Callable<Boolean> callable, int retryCount) {
try {
if (!callable.call()) {
throw new Exception();
} else if (retryCount > 0) {
logger.info("Connected to Para backend.");
}
} catch (Exception e) {
int maxRetries = Config.getConfigInt("connection_retries_max", 10);
int retryInterval = Config.getConfigInt("connection_retry_interval_sec", 10);
int count = ++retryCount;
logger.error("No connection to Para backend. Retrying connection in {}s (attempt {} of {})...",
retryInterval, count, maxRetries);
if (maxRetries < 0 || retryCount < maxRetries) {
Para.asyncExecute(new Runnable() {
public void run() {
try {
Thread.sleep(retryInterval * 1000L);
} catch (InterruptedException ex) {
logger.error(null, ex);
Thread.currentThread().interrupt();
}
retryConnection(callable, count);
}
});
}
}
}
public ParaObject checkAuth(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
Profile authUser = null;
String jwt = HttpUtils.getStateParam(AUTH_COOKIE, req);
if (isApiRequest(req)) {
return checkApiAuth(req);
} else if (jwt != null && !StringUtils.endsWithAny(req.getRequestURI(),
".js", ".css", ".svg", ".png", ".jpg", ".ico", ".gif", ".woff2", ".woff", "people/avatar")) {
User u = pc.me(jwt);
if (u != null && isEmailDomainApproved(u.getEmail())) {
authUser = getOrCreateProfile(u, req);
authUser.setUser(u);
authUser.setOriginalPicture(u.getPicture());
boolean updatedRank = promoteOrDemoteUser(authUser, u);
boolean updatedProfile = updateProfilePictureAndName(authUser, u);
if (updatedRank || updatedProfile) {
authUser.update();
}
} else {
clearSession(req, res);
logger.info("Invalid JWT found in cookie {}.", AUTH_COOKIE);
res.sendRedirect(getServerURL() + CONTEXT_PATH + SIGNINLINK + "?code=3&error=true");
return null;
}
}
return authUser;
}
private ParaObject checkApiAuth(HttpServletRequest req) {
if (req.getRequestURI().equals(CONTEXT_PATH + "/api")) {
return null;
}
String apiKeyJWT = StringUtils.removeStart(req.getHeader(HttpHeaders.AUTHORIZATION), "Bearer ");
if (req.getRequestURI().equals(CONTEXT_PATH + "/api/ping")) {
return API_USER;
} else if (req.getRequestURI().equals(CONTEXT_PATH + "/api/stats") && isValidJWToken(apiKeyJWT)) {
return API_USER;
} else if (!isApiEnabled() || StringUtils.isBlank(apiKeyJWT) || !isValidJWToken(apiKeyJWT)) {
throw new UnauthorizedException();
}
return API_USER;
}
private boolean promoteOrDemoteUser(Profile authUser, User u) {
if (authUser != null) {
if (!isAdmin(authUser) && isRecognizedAsAdmin(u)) {
logger.info("User '{}' with id={} promoted to admin.", u.getName(), authUser.getId());
authUser.setGroups(User.Groups.ADMINS.toString());
return true;
} else if (isAdmin(authUser) && !isRecognizedAsAdmin(u)) {
logger.info("User '{}' with id={} demoted to regular user.", u.getName(), authUser.getId());
authUser.setGroups(User.Groups.USERS.toString());
return true;
} else if (!isMod(authUser) && u.isModerator()) {
authUser.setGroups(User.Groups.MODS.toString());
return true;
}
}
return false;
}
private Profile getOrCreateProfile(User u, HttpServletRequest req) {
Profile authUser = pc.read(Profile.id(u.getId()));
if (authUser == null) {
authUser = Profile.fromUser(u);
authUser.create();
if (!u.getIdentityProvider().equals("generic")) {
sendWelcomeEmail(u, false, req);
}
Map<String, Object> payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(authUser, false));
payload.put("user", u);
triggerHookEvent("user.signup", payload);
logger.info("Created new user '{}' with id={}, groups={}, spaces={}.",
u.getName(), authUser.getId(), authUser.getGroups(), authUser.getSpaces());
}
return authUser;
}
private boolean updateProfilePictureAndName(Profile authUser, User u) {
boolean update = false;
if (!StringUtils.equals(u.getPicture(), authUser.getPicture())
&& !StringUtils.contains(authUser.getPicture(), "gravatar.com")
&& !Config.getConfigBoolean("avatar_edits_enabled", true)) {
authUser.setPicture(u.getPicture());
update = true;
}
if (!Config.getConfigBoolean("name_edits_enabled", true) &&
!StringUtils.equals(u.getName(), authUser.getName())) {
authUser.setName(u.getName());
update = true;
}
if (!StringUtils.equals(u.getName(), authUser.getOriginalName())) {
authUser.setOriginalName(u.getName());
update = true;
}
return update;
}
public boolean isDarkModeEnabled(Profile authUser, HttpServletRequest req) {
return (authUser != null && authUser.getDarkmodeEnabled()) ||
"1".equals(HttpUtils.getCookieValue(req, "dark-mode"));
}
private String getDefaultEmailSignature(String defaultText) {
String template = Config.getConfigParam("emails.default_signature", defaultText);
return Utils.formatMessage(template, Config.APP_NAME);
}
public void sendWelcomeEmail(User user, boolean verifyEmail, HttpServletRequest req) {
// send welcome email notification
if (user != null) {
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String subject = Utils.formatMessage(lang.get("signin.welcome"), Config.APP_NAME);
String body1 = Utils.formatMessage(Config.getConfigParam("emails.welcome_text1",
lang.get("signin.welcome.body1") + "<br><br>"), Config.APP_NAME);
String body2 = Config.getConfigParam("emails.welcome_text2", lang.get("signin.welcome.body2") + "<br><br>");
String body3 = getDefaultEmailSignature(Config.getConfigParam("emails.welcome_text3",
lang.get("notification.signature") + "<br><br>"));
if (verifyEmail && !user.getActive() && !StringUtils.isBlank(user.getIdentifier())) {
Sysprop s = pc.read(user.getIdentifier());
if (s != null) {
String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());
s.addProperty(Config._EMAIL_TOKEN, token);
pc.update(s);
token = getServerURL() + CONTEXT_PATH + SIGNINLINK + "/register?id=" + user.getId() + "&token=" + token;
body3 = "<b><a href=\"" + token + "\">" + lang.get("signin.welcome.verify") + "</a></b><br><br>" + body3;
}
}
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", Utils.formatMessage(lang.get("signin.welcome.title"), escapeHtml(user.getName())));
model.put("body", body1 + body2 + body3);
emailer.sendEmail(Arrays.asList(user.getEmail()), subject, compileEmailTemplate(model));
}
}
public void sendVerificationEmail(String email, HttpServletRequest req) {
if (!StringUtils.isBlank(email)) {
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String subject = Utils.formatMessage(lang.get("signin.welcome"), Config.APP_NAME);
String body = getDefaultEmailSignature(Config.getConfigParam("emails.welcome_text3",
lang.get("notification.signature") + "<br><br>"));
Sysprop s = pc.read(email);
if (s != null) {
String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());
s.addProperty(Config._EMAIL_TOKEN, token);
pc.update(s);
token = getServerURL() + CONTEXT_PATH + SIGNINLINK + "/register?id=" + s.getCreatorid() + "&token=" + token;
body = "<b><a href=\"" + token + "\">" + lang.get("signin.welcome.verify") + "</a></b><br><br>" + body;
}
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", lang.get("hello"));
model.put("body", body);
emailer.sendEmail(Arrays.asList(email), subject, compileEmailTemplate(model));
}
}
public void sendPasswordResetEmail(String email, String token, HttpServletRequest req) {
if (email != null && token != null) {
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String url = getServerURL() + CONTEXT_PATH + SIGNINLINK + "/iforgot?email=" + email + "&token=" + token;
String subject = lang.get("iforgot.title");
String body1 = lang.get("notification.iforgot.body1") + "<br><br>";
String body2 = Utils.formatMessage("<b><a href=\"{0}\">" + lang.get("notification.iforgot.body2") +
"</a></b><br><br>", url);
String body3 = getDefaultEmailSignature(lang.get("notification.signature") + "<br><br>");
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", lang.get("hello"));
model.put("body", body1 + body2 + body3);
emailer.sendEmail(Arrays.asList(email), subject, compileEmailTemplate(model));
}
}
@SuppressWarnings("unchecked")
public void subscribeToNotifications(String email, String channelId) {
if (!StringUtils.isBlank(email) && !StringUtils.isBlank(channelId)) {
Sysprop s = pc.read(channelId);
if (s == null || !s.hasProperty("emails")) {
s = new Sysprop(channelId);
s.addProperty("emails", new LinkedList<>());
}
Set<String> emails = new HashSet<>((List<String>) s.getProperty("emails"));
if (emails.add(email)) {
s.addProperty("emails", emails);
pc.create(s);
}
}
}
@SuppressWarnings("unchecked")
public void unsubscribeFromNotifications(String email, String channelId) {
if (!StringUtils.isBlank(email) && !StringUtils.isBlank(channelId)) {
Sysprop s = pc.read(channelId);
if (s == null || !s.hasProperty("emails")) {
s = new Sysprop(channelId);
s.addProperty("emails", new LinkedList<>());
}
Set<String> emails = new HashSet<>((List<String>) s.getProperty("emails"));
if (emails.remove(email)) {
s.addProperty("emails", emails);
pc.create(s);
}
}
}
@SuppressWarnings("unchecked")
public Set<String> getNotificationSubscribers(String channelId) {
return ((List<String>) Optional.ofNullable(((Sysprop) pc.read(channelId))).
orElse(new Sysprop()).getProperties().getOrDefault("emails", Collections.emptyList())).
stream().collect(Collectors.toSet());
}
public void unsubscribeFromAllNotifications(Profile p) {
User u = p.getUser();
if (u != null) {
unsubscribeFromNewPosts(u);
}
}
public boolean isEmailDomainApproved(String email) {
if (StringUtils.isBlank(email)) {
return false;
}
if (!APPROVED_DOMAINS.isEmpty() && !APPROVED_DOMAINS.contains(StringUtils.substringAfter(email, "@"))) {
logger.warn("Attempted signin from an unknown domain - email {} is part of an unapproved domain.", email);
return false;
}
return true;
}
public Object isSubscribedToNewPosts(HttpServletRequest req) {
if (!isNewPostNotificationAllowed()) {
return false;
}
Profile authUser = getAuthUser(req);
if (authUser != null) {
User u = authUser.getUser();
if (u != null) {
return getNotificationSubscribers(EMAIL_ALERTS_PREFIX + "new_post_subscribers").contains(u.getEmail());
}
}
return false;
}
public void subscribeToNewPosts(User u) {
if (u != null) {
subscribeToNotifications(u.getEmail(), EMAIL_ALERTS_PREFIX + "new_post_subscribers");
}
}
public void unsubscribeFromNewPosts(User u) {
if (u != null) {
unsubscribeFromNotifications(u.getEmail(), EMAIL_ALERTS_PREFIX + "new_post_subscribers");
}
}
private Map<String, Profile> buildProfilesMap(List<User> users) {
if (users != null && !users.isEmpty()) {
Map<String, User> userz = users.stream().collect(Collectors.toMap(u -> u.getId(), u -> u));
List<Profile> profiles = pc.readAll(userz.keySet().stream().
map(uid -> Profile.id(uid)).collect(Collectors.toList()));
Map<String, Profile> profilesMap = new HashMap<String, Profile>(users.size());
profiles.forEach(pr -> profilesMap.put(userz.get(pr.getCreatorid()).getEmail(), pr));
return profilesMap;
}
return Collections.emptyMap();
}
private void sendEmailsToSubscribersInSpace(Set<String> emails, String space, String subject, String html) {
int i = 0;
int max = Config.MAX_ITEMS_PER_PAGE;
List<String> terms = new ArrayList<>(max);
for (String email : emails) {
terms.add(email);
if (++i == max) {
emailer.sendEmail(buildProfilesMap(pc.findTermInList(Utils.type(User.class), Config._EMAIL, terms)).
entrySet().stream().filter(e -> canAccessSpace(e.getValue(), space) &&
!isIgnoredSpaceForNotifications(e.getValue(), space)).
map(e -> e.getKey()).collect(Collectors.toList()), subject, html);
i = 0;
terms.clear();
}
}
if (!terms.isEmpty()) {
emailer.sendEmail(buildProfilesMap(pc.findTermInList(Utils.type(User.class), Config._EMAIL, terms)).
entrySet().stream().filter(e -> canAccessSpace(e.getValue(), space) &&
!isIgnoredSpaceForNotifications(e.getValue(), space)).
map(e -> e.getKey()).collect(Collectors.toList()), subject, html);
}
}
private Set<String> getFavTagsSubscribers(List<String> tags) {
if (!tags.isEmpty()) {
Set<String> emails = new LinkedHashSet<>();
// find all user objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
List<Profile> profiles;
do {
profiles = pc.findQuery(Utils.type(Profile.class),
"properties.favtags:(" + tags.stream().
map(t -> "\"".concat(t).concat("\"")).distinct().
collect(Collectors.joining(" ")) + ") AND properties.favtagsEmailsEnabled:true", pager);
if (!profiles.isEmpty()) {
List<User> users = pc.readAll(profiles.stream().map(p -> p.getCreatorid()).
distinct().collect(Collectors.toList()));
users.stream().forEach(u -> emails.add(u.getEmail()));
}
} while (!profiles.isEmpty());
return emails;
}
return Collections.emptySet();
}
@SuppressWarnings("unchecked")
public void sendUpdatedFavTagsNotifications(Post question, List<String> addedTags, HttpServletRequest req) {
if (!isFavTagsNotificationAllowed()) {
return;
}
// sends a notification to subscibers of a tag if that tag was added to an existing question
if (question != null && !question.isReply() && addedTags != null && !addedTags.isEmpty()) {
Profile postAuthor = question.getAuthor(); // the current user - same as utils.getAuthUser(req)
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String name = postAuthor.getName();
String body = Utils.markdownToHtml(question.getBody());
String picture = Utils.formatMessage("<img src='{0}' width='25'>", escapeHtmlAttribute(postAuthor.getPicture()));
String postURL = getServerURL() + question.getPostLink(false, false);
String tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream().
map(t -> "<span class=\"tag\">" +
(addedTags.contains(t) ? "<b>" + escapeHtml(t) + "<b>" : escapeHtml(t)) + "</span>").
collect(Collectors.joining(" "));
String subject = Utils.formatMessage(lang.get("notification.favtags.subject"), name,
Utils.abbreviate(question.getTitle(), 255));
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", Utils.formatMessage(lang.get("notification.favtags.heading"), picture, escapeHtml(name)));
model.put("body", Utils.formatMessage("<h2><a href='{0}'>{1}</a></h2><div>{2}</div><br>{3}",
postURL, escapeHtml(question.getTitle()), body, tagsString));
Set<String> emails = getFavTagsSubscribers(addedTags);
sendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model));
}
}
@SuppressWarnings("unchecked")
public void sendNewPostNotifications(Post question, HttpServletRequest req) {
if (question == null) {
return;
}
// the current user - same as utils.getAuthUser(req)
Profile postAuthor = question.getAuthor() != null ? question.getAuthor() : pc.read(question.getCreatorid());
if (!question.getType().equals(Utils.type(UnapprovedQuestion.class))) {
if (!isNewPostNotificationAllowed()) {
return;
}
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String name = postAuthor.getName();
String body = Utils.markdownToHtml(question.getBody());
String picture = Utils.formatMessage("<img src='{0}' width='25'>", escapeHtmlAttribute(postAuthor.getPicture()));
String postURL = getServerURL() + question.getPostLink(false, false);
String tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream().
map(t -> "<span class=\"tag\">" + escapeHtml(t) + "</span>").
collect(Collectors.joining(" "));
String subject = Utils.formatMessage(lang.get("notification.newposts.subject"), name,
Utils.abbreviate(question.getTitle(), 255));
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", Utils.formatMessage(lang.get("notification.newposts.heading"), picture, escapeHtml(name)));
model.put("body", Utils.formatMessage("<h2><a href='{0}'>{1}</a></h2><div>{2}</div><br>{3}",
postURL, escapeHtml(question.getTitle()), body, tagsString));
Set<String> emails = new HashSet<String>(getNotificationSubscribers(EMAIL_ALERTS_PREFIX + "new_post_subscribers"));
emails.addAll(getFavTagsSubscribers(question.getTags()));
sendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model));
} else if (postsNeedApproval() && question instanceof UnapprovedQuestion) {
Report rep = new Report();
rep.setDescription("New question awaiting approval");
rep.setSubType(Report.ReportType.OTHER);
rep.setLink(question.getPostLink(false, false));
rep.setAuthorName(postAuthor.getName());
rep.create();
}
}
public void sendReplyNotifications(Post parentPost, Post reply, HttpServletRequest req) {
// send email notification to author of post except when the reply is by the same person
if (parentPost != null && reply != null && !StringUtils.equals(parentPost.getCreatorid(), reply.getCreatorid())) {
Profile replyAuthor = reply.getAuthor(); // the current user - same as utils.getAuthUser(req)
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> lang = getLang(req);
String name = replyAuthor.getName();
String body = Utils.markdownToHtml(reply.getBody());
String picture = Utils.formatMessage("<img src='{0}' width='25'>", escapeHtmlAttribute(replyAuthor.getPicture()));
String postURL = getServerURL() + parentPost.getPostLink(false, false);
String subject = Utils.formatMessage(lang.get("notification.reply.subject"), name,
Utils.abbreviate(reply.getTitle(), 255));
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", Utils.formatMessage(lang.get("notification.reply.heading"),
Utils.formatMessage("<a href='{0}'>{1}</a>", postURL, escapeHtml(parentPost.getTitle()))));
model.put("body", Utils.formatMessage("<h2>{0} {1}:</h2><div>{2}</div>", picture, escapeHtml(name), body));
Profile authorProfile = pc.read(parentPost.getCreatorid());
if (authorProfile != null) {
User author = authorProfile.getUser();
if (author != null) {
if (authorProfile.getReplyEmailsEnabled()) {
parentPost.addFollower(author);
}
}
}
if (postsNeedApproval() && reply instanceof UnapprovedReply) {
Report rep = new Report();
rep.setDescription("New reply awaiting approval");
rep.setSubType(Report.ReportType.OTHER);
rep.setLink(parentPost.getPostLink(false, false) + "#post-" + reply.getId());
rep.setAuthorName(reply.getAuthor().getName());
rep.create();
}
if (isReplyNotificationAllowed() && parentPost.hasFollowers()) {
emailer.sendEmail(new ArrayList<String>(parentPost.getFollowers().values()),
subject,
compileEmailTemplate(model));
}
}
}
public void sendCommentNotifications(Post parentPost, Comment comment, Profile commentAuthor, HttpServletRequest req) {
// send email notification to author of post except when the comment is by the same person
if (parentPost != null && comment != null) {
parentPost.setAuthor(pc.read(Profile.id(parentPost.getCreatorid()))); // parent author is not current user (authUser)
Map<String, Object> payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(comment, false));
payload.put("parent", parentPost);
payload.put("author", commentAuthor);
triggerHookEvent("comment.create", payload);
// get the last 5-6 commentators who want to be notified - https://github.com/Erudika/scoold/issues/201
Pager p = new Pager(1, Config._TIMESTAMP, false, 5);
boolean isCommentatorThePostAuthor = StringUtils.equals(parentPost.getCreatorid(), comment.getCreatorid());
Set<String> last5ids = pc.findChildren(parentPost, Utils.type(Comment.class),
"!(" + Config._CREATORID + ":\"" + comment.getCreatorid() + "\")", p).
stream().map(c -> c.getCreatorid()).distinct().collect(Collectors.toSet());
if (!isCommentatorThePostAuthor && !last5ids.contains(parentPost.getCreatorid())) {
last5ids = new HashSet<>(last5ids);
last5ids.add(parentPost.getCreatorid());
}
Map<String, String> lang = getLang(req);
List<Profile> last5commentators = pc.readAll(new ArrayList<>(last5ids));
last5commentators = last5commentators.stream().filter(u -> u.getCommentEmailsEnabled()).collect(Collectors.toList());
pc.readAll(last5commentators.stream().map(u -> u.getCreatorid()).collect(Collectors.toList())).forEach(author -> {
if (isCommentNotificationAllowed()) {
Map<String, Object> model = new HashMap<String, Object>();
String name = commentAuthor.getName();
String body = Utils.markdownToHtml(comment.getComment());
String pic = Utils.formatMessage("<img src='{0}' width='25'>", escapeHtmlAttribute(commentAuthor.getPicture()));
String postURL = getServerURL() + parentPost.getPostLink(false, false);
String subject = Utils.formatMessage(lang.get("notification.comment.subject"), name, parentPost.getTitle());
model.put("subject", escapeHtml(subject));
model.put("logourl", Config.getConfigParam("small_logo_url", "https://scoold.com/logo.png"));
model.put("heading", Utils.formatMessage(lang.get("notification.comment.heading"),
Utils.formatMessage("<a href='{0}'>{1}</a>", postURL, escapeHtml(parentPost.getTitle()))));
model.put("body", Utils.formatMessage("<h2>{0} {1}:</h2><div class='panel'>{2}</div>", pic, escapeHtml(name), body));
emailer.sendEmail(Arrays.asList(((User) author).getEmail()), subject, compileEmailTemplate(model));
}
});
}
}
private String escapeHtmlAttribute(String value) {
return StringUtils.trimToEmpty(value)
.replaceAll("'", "%27")
.replaceAll("\"", "%22")
.replaceAll("\\\\", "");
}
private String escapeHtml(String value) {
return StringEscapeUtils.escapeHtml4(value);
}
public Profile readAuthUser(HttpServletRequest req) {
Profile authUser = null;
User u = pc.me(HttpUtils.getStateParam(AUTH_COOKIE, req));
if (u != null && isEmailDomainApproved(u.getEmail())) {
return getOrCreateProfile(u, req);
}
return authUser;
}
public Profile getAuthUser(HttpServletRequest req) {
return (Profile) req.getAttribute(AUTH_USER_ATTRIBUTE);
}
public boolean isAuthenticated(HttpServletRequest req) {
return getAuthUser(req) != null;
}
public boolean isNearMeFeatureEnabled() {
return Config.getConfigBoolean("nearme_feature_enabled", !Config.getConfigParam("gmaps_api_key", "").isEmpty());
}
public boolean isFeedbackEnabled() {
return Config.getConfigBoolean("feedback_enabled", false);
}
public boolean isDefaultSpacePublic() {
return Config.getConfigBoolean("is_default_space_public", true);
}
public boolean isWebhooksEnabled() {
return Config.getConfigBoolean("webhooks_enabled", true);
}
public boolean isAnonymityEnabled() {
return Config.getConfigBoolean("profile_anonimity_enabled", false);
}
public boolean isApiEnabled() {
return Config.getConfigBoolean("api_enabled", false);
}
public boolean isFooterLinksEnabled() {
return Config.getConfigBoolean("footer_links_enabled", true);
}
public boolean isNotificationsAllowed() {
return Config.getConfigBoolean("notification_emails_allowed", true);
}
public boolean isNewPostNotificationAllowed() {
return isNotificationsAllowed() && Config.getConfigBoolean("newpost_emails_allowed", true);
}
public boolean isFavTagsNotificationAllowed() {
return isNotificationsAllowed() && Config.getConfigBoolean("favtags_emails_allowed", true);
}
public boolean isReplyNotificationAllowed() {
return isNotificationsAllowed() && Config.getConfigBoolean("reply_emails_allowed", true);
}
public boolean isCommentNotificationAllowed() {
return isNotificationsAllowed() && Config.getConfigBoolean("comment_emails_allowed", true);
}
public boolean isDarkModeEnabled() {
return Config.getConfigBoolean("dark_mode_enabled", true);
}
public boolean isAvatarValidationEnabled() {
return Config.getConfigBoolean("avatar_validation_enabled", false); // this should be deleted in the future
}
public static boolean isGravatarEnabled() {
return Config.getConfigBoolean("gravatars_enabled", true);
}
public String getFooterHTML() {
return Config.getConfigParam("footer_html", "");
}
public boolean isNavbarLink1Enabled() {
return !StringUtils.isBlank(getNavbarLink1URL());
}
public String getNavbarLink1URL() {
return Config.getConfigParam("navbar_link1_url", "");
}
public String getNavbarLink1Text() {
return Config.getConfigParam("navbar_link1_text", "Link1");
}
public boolean isNavbarLink2Enabled() {
return !StringUtils.isBlank(getNavbarLink2URL());
}
public String getNavbarLink2URL() {
return Config.getConfigParam("navbar_link2_url", "");
}
public String getNavbarLink2Text() {
return Config.getConfigParam("navbar_link2_text", "Link2");
}
public boolean isNavbarMenuLink1Enabled() {
return !StringUtils.isBlank(getNavbarMenuLink1URL());
}
public String getNavbarMenuLink1URL() {
return Config.getConfigParam("navbar_menu_link1_url", "");
}
public String getNavbarMenuLink1Text() {
return Config.getConfigParam("navbar_menu_link1_text", "Menu Link1");
}
public boolean isNavbarMenuLink2Enabled() {
return !StringUtils.isBlank(getNavbarMenuLink2URL());
}
public String getNavbarMenuLink2URL() {
return Config.getConfigParam("navbar_menu_link2_url", "");
}
public String getNavbarMenuLink2Text() {
return Config.getConfigParam("navbar_menu_link2_text", "Menu Link2");
}
public boolean alwaysHideCommentForms() {
return Config.getConfigBoolean("always_hide_comment_forms", true);
}
public Set<String> getCoreScooldTypes() {
return Collections.unmodifiableSet(CORE_TYPES);
}
public Set<String> getCustomHookEvents() {
return Collections.unmodifiableSet(HOOK_EVENTS);
}
public Pager getPager(String pageParamName, HttpServletRequest req) {
return pagerFromParams(pageParamName, req);
}
public Pager pagerFromParams(HttpServletRequest req) {
return pagerFromParams("page", req);
}
public Pager pagerFromParams(String pageParamName, HttpServletRequest req) {
Pager p = new Pager();
p.setPage(Math.min(NumberUtils.toLong(req.getParameter(pageParamName), 1), Config.MAX_PAGES));
p.setLimit(NumberUtils.toInt(req.getParameter("limit"), Config.MAX_ITEMS_PER_PAGE));
String lastKey = req.getParameter("lastKey");
String sort = req.getParameter("sortby");
String desc = req.getParameter("desc");
if (!StringUtils.isBlank(desc)) {
p.setDesc(Boolean.parseBoolean(desc));
}
if (!StringUtils.isBlank(lastKey)) {
p.setLastKey(lastKey);
}
if (!StringUtils.isBlank(sort)) {
p.setSortby(sort);
}
return p;
}
public String getLanguageCode(HttpServletRequest req) {
String langCodeFromConfig = Config.getConfigParam("default_language_code", "");
String cookieLoc = getCookieValue(req, LOCALE_COOKIE);
Locale fromReq = (req == null) ? Locale.getDefault() : req.getLocale();
Locale requestLocale = langutils.getProperLocale(fromReq.toString());
return (cookieLoc != null) ? cookieLoc : (StringUtils.isBlank(langCodeFromConfig) ?
requestLocale.getLanguage() : langutils.getProperLocale(langCodeFromConfig).getLanguage());
}
public Locale getCurrentLocale(String langname) {
Locale currentLocale = langutils.getProperLocale(langname);
if (currentLocale == null) {
currentLocale = langutils.getProperLocale(langutils.getDefaultLanguageCode());
}
return currentLocale;
}
public Map<String, String> getLang(HttpServletRequest req) {
return getLang(getCurrentLocale(getLanguageCode(req)));
}
public Map<String, String> getLang(Locale currentLocale) {
Map<String, String> lang = langutils.readLanguage(currentLocale.toString());
if (lang == null || lang.isEmpty()) {
lang = langutils.getDefaultLanguage();
}
return lang;
}
public boolean isLanguageRTL(String langCode) {
return StringUtils.equalsAnyIgnoreCase(langCode, "ar", "he", "dv", "iw", "fa", "ps", "sd", "ug", "ur", "yi");
}
public void fetchProfiles(List<? extends ParaObject> objects) {
if (objects == null || objects.isEmpty()) {
return;
}
Map<String, String> authorids = new HashMap<String, String>(objects.size());
Map<String, Profile> authors = new HashMap<String, Profile>(objects.size());
for (ParaObject obj : objects) {
if (obj.getCreatorid() != null) {
authorids.put(obj.getId(), obj.getCreatorid());
}
}
List<String> ids = new ArrayList<String>(new HashSet<String>(authorids.values()));
if (ids.isEmpty()) {
return;
}
// read all post authors in batch
for (ParaObject author : pc.readAll(ids)) {
authors.put(author.getId(), (Profile) author);
}
// add system profile
authors.put(API_USER.getId(), API_USER);
// set author object for each post
for (ParaObject obj : objects) {
if (obj instanceof Post) {
((Post) obj).setAuthor(authors.get(authorids.get(obj.getId())));
} else if (obj instanceof Revision) {
((Revision) obj).setAuthor(authors.get(authorids.get(obj.getId())));
}
}
}
//get the comments for each answer and the question
public void getComments(List<Post> allPosts) {
Map<String, List<Comment>> allComments = new HashMap<String, List<Comment>>();
List<String> allCommentIds = new ArrayList<String>();
List<Post> forUpdate = new ArrayList<Post>(allPosts.size());
// get the comment ids of the first 5 comments for each post
for (Post post : allPosts) {
// not set => read comments if any and embed ids in post object
if (post.getCommentIds() == null) {
forUpdate.add(reloadFirstPageOfComments(post));
allComments.put(post.getId(), post.getComments());
} else {
// ids are set => add them to list for bulk read
allCommentIds.addAll(post.getCommentIds());
}
}
if (!allCommentIds.isEmpty()) {
// read all comments for all posts on page in bulk
for (ParaObject comment : pc.readAll(allCommentIds)) {
List<Comment> postComments = allComments.get(comment.getParentid());
if (postComments == null) {
allComments.put(comment.getParentid(), new ArrayList<Comment>());
}
allComments.get(comment.getParentid()).add((Comment) comment);
}
}