BrightSide Workbench Full Report + Source Code
RegisterControl.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2016 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.contacts.zul.register;
20 
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.UnsupportedEncodingException;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30 import org.amic.util.file.FileUtil;
31 import org.turro.string.Strings;
32 import org.apache.commons.mail.EmailException;
33 import org.turro.action.Actions;
34 import org.turro.action.IRegisterCallback;
35 import org.turro.action.MailSenders;
36 import org.turro.action.PushSenders;
37 import org.turro.collections.KeyValueMap;
38 import org.turro.contacts.Connector;
39 import org.turro.contacts.Contact;
40 import org.turro.contacts.SignUp;
41 import org.turro.contacts.db.ContactsPU;
42 import org.turro.contacts.form.ContactWrapper;
43 import org.turro.contacts.profile.ProfileContext;
44 import org.turro.elephant.TemplateControl;
45 import org.turro.elephant.context.Application;
46 import org.turro.elephant.context.ElephantContext;
47 import org.turro.elephant.context.IConstructor;
48 import org.turro.elephant.security.IUser;
49 import org.turro.elephant.util.Messages;
50 import org.turro.elephant.web.tags.SessionTags;
51 import org.turro.i18n.I_;
52 import org.turro.jpa.Dao;
53 import org.turro.mail.sender.MailPool;
54 import org.turro.marker.ElephantMarker;
55 import org.turro.security.SecurityGroup;
56 import org.turro.security.SocialGroups;
57 import org.turro.zkoss.dialog.SelectionDialog;
58 import org.turro.zkoss.layout.TabbedContent;
59 import org.zkoss.zk.ui.event.Event;
60 import org.zkoss.zk.ui.select.annotation.Listen;
61 import org.zkoss.zk.ui.select.annotation.Wire;
62 import org.zkoss.zk.ui.util.Clients;
63 import org.zkoss.zul.Checkbox;
64 import org.zkoss.zul.Hlayout;
65 import org.zkoss.zul.Textbox;
66 
71 public class RegisterControl extends TemplateControl {
72 
73  @Wire("#name")
74  private Textbox name;
75 
76  @Wire("#email")
77  private Textbox email;
78 
79  @Wire("#student")
80  private Checkbox student;
81 
82  @Wire("#professional")
83  private Checkbox professional;
84 
85  @Wire("#comment")
86  private Textbox comment;
87 
88  @Wire("#accepted")
89  private Checkbox accepted;
90 
91  @Wire("#termsrow")
92  private Hlayout termsrow;
93 
94  @Listen("onCheck = #accepted")
95  public void onTerms(Event event) {
96  if(termsBox != null) {
97  if(accepted.isChecked()) {
98  SelectionDialog.showComponent(getPage(), I_.get("Terms of Use"), termsBox, "70%", "500px", null);
99  }
100  }
101  }
102 
103  private SignUp sue;
104 
105  @Listen("onClick = #register")
106  public void onRegister(Event event) {
107  SignUp su = new SignUp();
108  su.setName(name.getValue());
109  su.setEmail(email.getValue());
110  su.setComment(comment.getValue());
111  su.setValueMap(keepValues());
112  if(su.isValid()) {
113  if(existPending(su.getEmail())) {
114  Messages.confirmProcess().add(I_.get("Email pending to confirm"))
115  .paragraph().add(I_.get("Resend confirmation e-mail")).show(() -> {
116  try {
117  sendEmail(sue);
118  Clients.showNotification(I_.format("Confirmation e-mail has been sent to %s", sue.getEmail()));
119  } catch (EmailException ex) {
120  Logger.getLogger(RegisterControl.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
121  }
122  });
123  } else if(existEmail(su.getEmail())) {
124  Clients.showNotification(I_.format("%s already exists", su.getEmail()));
126  } else {
127  if(termsrow.isVisible() && accepted != null && !accepted.isChecked()) {
128  Clients.showNotification(I_.get("Read and accepted") + "?");
129  } else {
130  su = new ContactsPU().saveObject(su);
131  try {
132  sendEmail(su);
133  Clients.showNotification(I_.format("Confirmation e-mail has been sent to %s", su.getEmail()));
134  } catch (EmailException ex) {
135  Logger.getLogger(RegisterControl.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
136  }
137  }
138  }
139  } else {
140  Clients.showNotification("No valid values");
141  }
142  }
143 
144  @Override
145  public void doFinally() {
146  super.doFinally();
147  createTermsOfUse();
148  if(termsBox != null) {
149  accepted.setDisabled(false);
150  }
151  professional.setVisible(ProfileContext.hasCompanies());
152  student.setVisible(ProfileContext.hasCenters());
153  }
154 
155  private static boolean existEmail(String email) {
156  Dao dao = new ContactsPU();
157  List l = dao.getResultList(
158  "select c from Connector c where c.value = ?",
159  new Object[] { email }
160  );
161  if(l.isEmpty()) {
162  l = dao.getResultList(
163  "select c from SignUp c where c.email = ? and confirmed = TRUE",
164  new Object[] { email }
165  );
166  }
167  return !l.isEmpty();
168  }
169 
170  private boolean existPending(String email) {
171  Dao dao = new ContactsPU();
172  List l = dao.getResultList(
173  "select c from SignUp c where c.email = ? and confirmed = FALSE",
174  new Object[] { email }
175  );
176  if(!l.isEmpty()) {
177  sue = (SignUp) l.iterator().next();
178  }
179  return !l.isEmpty();
180  }
181 
182  private boolean sendEmail(SignUp signUp) throws EmailException {
183  new MailPool()
184  .addUser(signUp.getName(), signUp.getEmail())
185  .put("signUp", signUp)
186  .sendTemplate("sign-pending", I_.get("Email pending to confirm") + " : " + ElephantContext.getSiteName());
187  IRegisterCallback regcall = (IRegisterCallback) Application.getApplication().getConstructor()
188  .getSessionAttribute(IRegisterCallback.REGISTER_CALLBACK_KEY);
189  if(regcall != null) {
190  regcall.onRegister(signUp.getEmail());
191  }
192  return true;
193  }
194 
195  public static SignUp confirmEmail(String id) throws Exception {
196  if(!Strings.isBlank(id)) {
197  Dao dao = new ContactsPU();
198  SignUp su = dao.find(SignUp.class, id);
199  if(su != null) {
200  if(su.isValid()) {
201  if(!su.isConfirmed()) {
202  createContact(su);
203  su.setConfirmed(true);
204  dao.saveObject(su);
205  sendMailToAdmin(su);
206  sendWelcomeMailToUser(su);
207  }
208  }
209  }
210  return su;
211  }
212  return null;
213  }
214 
215  public static void writeResultConfirmAction(IConstructor constructor, SignUp signUp) throws Exception {
216  ElephantMarker em = new ElephantMarker(constructor);
217  if(signUp != null && signUp.isConfirmed()) {
218  em.put("signUp", signUp);
219  try {
220  em.put("link", ElephantContext.getRootWebPath() + "?" + Actions.createAction(signUp.getEmail(), "/user/changepass"));
221  } catch (Exception ex) {
222  Logger.getLogger(RegisterControl.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
223  }
224  em.process("signup", "confirmed");
225  } else {
226  em.process("signup", "failed");
227  }
228  }
229 
230  public static void createContact(SignUp signUp) throws Exception {
231  if(!existEmail(signUp.getEmail())) {
232  Contact contact = new Contact();
233  contact.setName(signUp.getName());
234  contact.getComplexName().setFull(signUp.getName());
235  contact.setUserMenu(true);
236  Connector email = new Connector();
237  email.setContact(contact);
239  email.setValue(signUp.getEmail());
240  contact.getConnectors().add(email);
241  try {
242  KeyValueMap kvm = signUp.getValues();
243  for(String key : kvm.keySet()) {
244  if(!Strings.isBlank(key) && !Strings.isBlank(kvm.get(key))) {
245  Connector suv = new Connector();
246  suv.setContact(contact);
247  suv.setDescription(key);
248  suv.setValue(kvm.get(key));
249  contact.getConnectors().add(suv);
250  }
251  }
252  } catch(Exception ex) {}
253  if(!Strings.isBlank(ElephantContext.getSiteSyndicate())) {
254  String groups[] = ElephantContext.getSiteSyndicate().split(",");
255  SocialGroups.syndicate(List.of(contact), Set.of(groups), null);
256  }
257  new ContactWrapper(contact).save();
258  }
259  }
260 
261  private static void sendMailToAdmin(SignUp signUp) {
262  String message = signUp.getName() + ": " + signUp.getEmail();
263  if(!Strings.isBlank(signUp.getComment())) message += "\n" + signUp.getComment();
264  if(!Strings.isBlank(signUp.getValueMap())) message += "\n" + signUp.getValueMap();
265  MailSenders.getPool().addAdministrators().addBySyndication(SecurityGroup.CONTACTS_ADMIN).send("New user", message);
266  PushSenders.getPool().addAdministrators().addBySyndication(SecurityGroup.CONTACTS_ADMIN).send("New user", message);
267  }
268 
269  private static void sendWelcomeMailToUser(SignUp signUp) throws UnsupportedEncodingException, EmailException {
270  Map args = new HashMap();
271  args.put("signUp", signUp);
272  try {
273  args.put("link", ElephantContext.getServerUrl("http") + "?" + Actions.createAction(signUp.getEmail(), "/user"));
274  } catch (Exception ex) {
275  Logger.getLogger(RegisterControl.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
276  }
277  new MailPool()
278  .addUser(signUp.getName(), signUp.getEmail())
279  .putAll(args)
280  .sendTemplate("sign-welcome", I_.get("Welcome") + " : " + ElephantContext.getSiteName());
281  }
282 
283  private void createTermsOfUse() {
284  File dir = new File(ElephantContext.getRealPath("/_internal/terms"));
285  if(dir.exists()) {
286  for(File f : dir.listFiles((File dir1, String name1) -> name1.endsWith(".txt"))) {
287  createTab(f);
288  }
289  }
290  }
291 
292  private TabbedContent termsBox;
293 
294  private void createTab(File f) {
295  if(termsBox == null) {
296  termsBox = new TabbedContent();
297  termsBox.setVflex("true");
298  termsBox.setStyle("width:100%");
299  termsrow.setVisible(true);
300  }
301  Textbox text = new Textbox();
302  text.setReadonly(true);
303  text.setMultiline(true);
304  text.setVflex("true");
305  text.setHflex("true");
306  try {
307  text.setValue(FileUtil.getContent(f, ElephantContext.getEncoding()));
308  termsBox.addContent(FileUtil.getBaseName(f), text);
309  } catch (IOException ex) {
310  Logger.getLogger(RegisterControl.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
311  }
312  }
313 
314  private String keepValues() {
315  HashMap<String, String> keep = new HashMap<>();
316  if(professional.isVisible() && professional.isChecked()) {
317  keep.put("su_professional", "true");
318  }
319  if(student.isVisible() && student.isChecked()) {
320  keep.put("su_student", "true");
321  }
322  String webTags = SessionTags.get().path();
323  if(!Strings.isBlank(webTags)) {
324  keep.put("webTags", webTags);
325  }
326  return keep.isEmpty() ? null : KeyValueMap.format(keep);
327  }
328 
329 }
static String createAction(String email, String redir)
Definition: Actions.java:90
static String createRightNowAction(String values)
Definition: Actions.java:312
static IMailSender getPool()
static IPushSender getPool()
void setContact(org.turro.contacts.Contact contact)
Definition: Connector.java:103
void setDescription(String description)
Definition: Connector.java:87
void setValue(String value)
Definition: Connector.java:95
void setName(String name)
Definition: Contact.java:217
void setUserMenu(boolean userMenu)
Definition: Contact.java:193
ComplexName getComplexName()
Definition: Contact.java:152
Set< Connector > getConnectors()
Definition: Contact.java:367
void setComment(String comment)
Definition: SignUp.java:82
void setEmail(String email)
Definition: SignUp.java:74
void setConfirmed(boolean confirmed)
Definition: SignUp.java:90
void setName(String name)
Definition: SignUp.java:66
void setValueMap(String valueMap)
Definition: SignUp.java:98
static void writeResultConfirmAction(IConstructor constructor, SignUp signUp)
abstract void sendRedirect(String uri)
static String getServerUrl(String scheme)
static Messages confirmProcess()
Definition: Messages.java:95
Messages add(String word)
Definition: Messages.java:50
static String format(String msg, Object... arguments)
Definition: I_.java:49
static String get(String msg)
Definition: I_.java:41
void process(String rootTmpl, String tmpl)
Object put(Object key, Object value)
static void syndicate(List< Contact > contacts, Set< String > socialGroupIds, Dao dao)
static void showComponent(Page page, String title, Component component, String width, String height, final Command command)
static final String CONNECTOR_EMAIL
Definition: IUser.java:27