1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.service.impl;
24  
25  import com.liferay.portal.AccountNameException;
26  import com.liferay.portal.CompanyMxException;
27  import com.liferay.portal.CompanyVirtualHostException;
28  import com.liferay.portal.CompanyWebIdException;
29  import com.liferay.portal.NoSuchCompanyException;
30  import com.liferay.portal.NoSuchLayoutSetException;
31  import com.liferay.portal.NoSuchUserException;
32  import com.liferay.portal.PortalException;
33  import com.liferay.portal.SystemException;
34  import com.liferay.portal.kernel.language.LanguageUtil;
35  import com.liferay.portal.kernel.search.BooleanClauseOccur;
36  import com.liferay.portal.kernel.search.BooleanQuery;
37  import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
38  import com.liferay.portal.kernel.search.Field;
39  import com.liferay.portal.kernel.search.Hits;
40  import com.liferay.portal.kernel.search.SearchEngineUtil;
41  import com.liferay.portal.kernel.util.LocaleUtil;
42  import com.liferay.portal.kernel.util.StringPool;
43  import com.liferay.portal.kernel.util.TimeZoneUtil;
44  import com.liferay.portal.kernel.util.Validator;
45  import com.liferay.portal.model.Account;
46  import com.liferay.portal.model.Company;
47  import com.liferay.portal.model.CompanyConstants;
48  import com.liferay.portal.model.Contact;
49  import com.liferay.portal.model.ContactConstants;
50  import com.liferay.portal.model.Group;
51  import com.liferay.portal.model.GroupConstants;
52  import com.liferay.portal.model.Role;
53  import com.liferay.portal.model.RoleConstants;
54  import com.liferay.portal.model.User;
55  import com.liferay.portal.search.lucene.LuceneUtil;
56  import com.liferay.portal.service.ServiceContext;
57  import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
58  import com.liferay.portal.util.PrefsPropsUtil;
59  import com.liferay.portal.util.PropsKeys;
60  import com.liferay.portal.util.PropsValues;
61  import com.liferay.util.Encryptor;
62  import com.liferay.util.EncryptorException;
63  
64  import java.io.File;
65  import java.io.IOException;
66  import java.io.InputStream;
67  
68  import java.util.Calendar;
69  import java.util.Date;
70  import java.util.List;
71  import java.util.Locale;
72  
73  import javax.portlet.PortletException;
74  import javax.portlet.PortletPreferences;
75  
76  /**
77   * <a href="CompanyLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
78   *
79   * @author Brian Wing Shun Chan
80   *
81   */
82  public class CompanyLocalServiceImpl extends CompanyLocalServiceBaseImpl {
83  
84      public Company addCompany(String webId, String virtualHost, String mx)
85          throws PortalException, SystemException {
86  
87          // Company
88  
89          virtualHost = virtualHost.trim().toLowerCase();
90  
91          if ((Validator.isNull(webId)) ||
92              (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) ||
93              (companyPersistence.fetchByWebId(webId) != null)) {
94  
95              throw new CompanyWebIdException();
96          }
97  
98          validate(webId, virtualHost, mx);
99  
100         Company company = checkCompany(webId, mx);
101 
102         company.setVirtualHost(virtualHost);
103         company.setMx(mx);
104 
105         companyPersistence.update(company, false);
106 
107         return company;
108     }
109 
110     public Company checkCompany(String webId)
111         throws PortalException, SystemException {
112 
113         String mx = webId;
114 
115         return checkCompany(webId, mx);
116     }
117 
118     public Company checkCompany(String webId, String mx)
119         throws PortalException, SystemException {
120 
121         // Company
122 
123         Date now = new Date();
124 
125         Company company = companyPersistence.fetchByWebId(webId);
126 
127         if (company == null) {
128             String virtualHost = webId;
129 
130             if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
131                 virtualHost = _DEFAULT_VIRTUAL_HOST;
132             }
133 
134             String homeURL = null;
135             String name = webId;
136             String legalName = null;
137             String legalId = null;
138             String legalType = null;
139             String sicCode = null;
140             String tickerSymbol = null;
141             String industry = null;
142             String type = null;
143             String size = null;
144 
145             long companyId = counterLocalService.increment();
146 
147             company = companyPersistence.create(companyId);
148 
149             try {
150                 company.setKeyObj(Encryptor.generateKey());
151             }
152             catch (EncryptorException ee) {
153                 throw new SystemException(ee);
154             }
155 
156             company.setWebId(webId);
157             company.setVirtualHost(virtualHost);
158             company.setMx(mx);
159 
160             companyPersistence.update(company, false);
161 
162             updateCompany(
163                 companyId, virtualHost, mx, homeURL, name, legalName, legalId,
164                 legalType, sicCode, tickerSymbol, industry, type, size);
165 
166             // Lucene
167 
168             LuceneUtil.checkLuceneDir(company.getCompanyId());
169 
170             // Demo settings
171 
172             if (webId.equals("liferay.net")) {
173                 company = companyPersistence.findByWebId(webId);
174 
175                 company.setVirtualHost("demo.liferay.net");
176 
177                 companyPersistence.update(company, false);
178 
179                 updateSecurity(
180                     companyId, CompanyConstants.AUTH_TYPE_EA, true, true, true,
181                     true, false, true);
182 
183                 PortletPreferences preferences = PrefsPropsUtil.getPreferences(
184                     companyId);
185 
186                 try {
187                     preferences.setValue(
188                         PropsKeys.ADMIN_EMAIL_FROM_NAME, "Liferay Demo");
189                     preferences.setValue(
190                         PropsKeys.ADMIN_EMAIL_FROM_ADDRESS, "test@liferay.net");
191 
192                     preferences.store();
193                 }
194                 catch (IOException ioe) {
195                     throw new SystemException(ioe);
196                 }
197                 catch (PortletException pe) {
198                     throw new SystemException(pe);
199                 }
200             }
201         }
202         else {
203 
204             // Lucene
205 
206             LuceneUtil.checkLuceneDir(company.getCompanyId());
207         }
208 
209         long companyId = company.getCompanyId();
210 
211         // Key
212 
213         checkCompanyKey(companyId);
214 
215         // Default user
216 
217         User defaultUser = null;
218 
219         try {
220             defaultUser = userLocalService.getDefaultUser(companyId);
221 
222             if (!defaultUser.isAgreedToTermsOfUse()) {
223                 defaultUser.setAgreedToTermsOfUse(true);
224 
225                 userPersistence.update(defaultUser, false);
226             }
227         }
228         catch (NoSuchUserException nsue) {
229             long userId = counterLocalService.increment();
230 
231             defaultUser = userPersistence.create(userId);
232 
233             defaultUser.setCompanyId(companyId);
234             defaultUser.setCreateDate(now);
235             defaultUser.setModifiedDate(now);
236             defaultUser.setDefaultUser(true);
237             defaultUser.setContactId(counterLocalService.increment());
238             defaultUser.setPassword("password");
239             defaultUser.setScreenName(String.valueOf(defaultUser.getUserId()));
240             defaultUser.setEmailAddress("default@" + company.getMx());
241             defaultUser.setLanguageId(LocaleUtil.getDefault().toString());
242             defaultUser.setTimeZoneId(TimeZoneUtil.getDefault().getID());
243             defaultUser.setGreeting(
244                 LanguageUtil.format(
245                     companyId, defaultUser.getLocale(), "welcome-x",
246                     StringPool.BLANK, false));
247             defaultUser.setLoginDate(now);
248             defaultUser.setFailedLoginAttempts(0);
249             defaultUser.setAgreedToTermsOfUse(true);
250             defaultUser.setActive(true);
251 
252             userPersistence.update(defaultUser, false);
253 
254             // Contact
255 
256             Contact defaultContact = contactPersistence.create(
257                 defaultUser.getContactId());
258 
259             defaultContact.setCompanyId(defaultUser.getCompanyId());
260             defaultContact.setUserId(defaultUser.getUserId());
261             defaultContact.setUserName(StringPool.BLANK);
262             defaultContact.setCreateDate(now);
263             defaultContact.setModifiedDate(now);
264             defaultContact.setAccountId(company.getAccountId());
265             defaultContact.setParentContactId(
266                 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
267             defaultContact.setFirstName(StringPool.BLANK);
268             defaultContact.setMiddleName(StringPool.BLANK);
269             defaultContact.setLastName(StringPool.BLANK);
270             defaultContact.setMale(true);
271             defaultContact.setBirthday(now);
272 
273             contactPersistence.update(defaultContact, false);
274         }
275 
276         // System roles
277 
278         roleLocalService.checkSystemRoles(companyId);
279 
280         // System groups
281 
282         groupLocalService.checkSystemGroups(companyId);
283 
284         // Default password policy
285 
286         passwordPolicyLocalService.checkDefaultPasswordPolicy(companyId);
287 
288         // Default user must have the Guest role
289 
290         Role guestRole = roleLocalService.getRole(
291             companyId, RoleConstants.GUEST);
292 
293         roleLocalService.setUserRoles(
294             defaultUser.getUserId(), new long[] {guestRole.getRoleId()});
295 
296         // Default admin
297 
298         if (userPersistence.countByCompanyId(companyId) == 1) {
299             long creatorUserId = 0;
300             boolean autoPassword = false;
301             String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
302             String password2 = password1;
303             boolean autoScreenName = false;
304             String screenName = PropsValues.DEFAULT_ADMIN_SCREEN_NAME;
305             String emailAddress =
306                 PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + "@" + mx;
307             String openId = StringPool.BLANK;
308             Locale locale = defaultUser.getLocale();
309             String firstName = PropsValues.DEFAULT_ADMIN_FIRST_NAME;
310             String middleName = PropsValues.DEFAULT_ADMIN_MIDDLE_NAME;
311             String lastName = PropsValues.DEFAULT_ADMIN_LAST_NAME;
312             int prefixId = 0;
313             int suffixId = 0;
314             boolean male = true;
315             int birthdayMonth = Calendar.JANUARY;
316             int birthdayDay = 1;
317             int birthdayYear = 1970;
318             String jobTitle = StringPool.BLANK;
319 
320             Group guestGroup = groupLocalService.getGroup(
321                 companyId, GroupConstants.GUEST);
322 
323             long[] groupIds = new long[] {guestGroup.getGroupId()};
324 
325             long[] organizationIds = null;
326 
327             Role adminRole = roleLocalService.getRole(
328                 companyId, RoleConstants.ADMINISTRATOR);
329 
330             Role powerUserRole = roleLocalService.getRole(
331                 companyId, RoleConstants.POWER_USER);
332 
333             long[] roleIds = new long[] {
334                 adminRole.getRoleId(), powerUserRole.getRoleId()
335             };
336 
337             long[] userGroupIds = null;
338             boolean sendEmail = false;
339             ServiceContext serviceContext = new ServiceContext();
340 
341             userLocalService.addUser(
342                 creatorUserId, companyId, autoPassword, password1, password2,
343                 autoScreenName, screenName, emailAddress, openId, locale,
344                 firstName, middleName, lastName, prefixId, suffixId, male,
345                 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
346                 organizationIds, roleIds, userGroupIds, sendEmail,
347                 serviceContext);
348         }
349 
350         return company;
351     }
352 
353     public void checkCompanyKey(long companyId)
354         throws PortalException, SystemException {
355 
356         Company company = companyPersistence.findByPrimaryKey(companyId);
357 
358         if (company.getKeyObj() == null) {
359             try {
360                 company.setKeyObj(Encryptor.generateKey());
361             }
362             catch (EncryptorException ee) {
363                 throw new SystemException(ee);
364             }
365         }
366 
367         companyPersistence.update(company, false);
368     }
369 
370     public List<Company> getCompanies() throws SystemException {
371         return companyPersistence.findAll();
372     }
373 
374     public Company getCompanyById(long companyId)
375         throws PortalException, SystemException {
376 
377         return companyPersistence.findByPrimaryKey(companyId);
378     }
379 
380     public Company getCompanyByLogoId(long logoId)
381         throws PortalException, SystemException {
382 
383         return companyPersistence.findByLogoId(logoId);
384     }
385 
386     public Company getCompanyByMx(String mx)
387         throws PortalException, SystemException {
388 
389         return companyPersistence.findByMx(mx);
390     }
391 
392     public Company getCompanyByVirtualHost(String virtualHost)
393         throws PortalException, SystemException {
394 
395         virtualHost = virtualHost.trim().toLowerCase();
396 
397         return companyPersistence.findByVirtualHost(virtualHost);
398     }
399 
400     public Company getCompanyByWebId(String webId)
401         throws PortalException, SystemException {
402 
403         return companyPersistence.findByWebId(webId);
404     }
405 
406     public Hits search(long companyId, String keywords, int start, int end)
407         throws SystemException {
408 
409         return search(companyId, null, 0, null, keywords, start, end);
410     }
411 
412     public Hits search(
413             long companyId, String portletId, long groupId, String type,
414             String keywords, int start, int end)
415         throws SystemException {
416 
417         try {
418             BooleanQuery contextQuery = BooleanQueryFactoryUtil.create();
419 
420             contextQuery.addRequiredTerm(Field.COMPANY_ID, companyId);
421 
422             if (Validator.isNotNull(portletId)) {
423                 contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);
424             }
425 
426             if (groupId > 0) {
427                 contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
428             }
429 
430             if (Validator.isNotNull(type)) {
431                 contextQuery.addRequiredTerm(Field.TYPE, type);
432             }
433 
434             BooleanQuery searchQuery = BooleanQueryFactoryUtil.create();
435 
436             if (Validator.isNotNull(keywords)) {
437                 searchQuery.addTerm(Field.TITLE, keywords);
438                 searchQuery.addTerm(Field.CONTENT, keywords);
439                 searchQuery.addTerm(Field.DESCRIPTION, keywords);
440                 searchQuery.addTerm(Field.PROPERTIES, keywords);
441                 searchQuery.addTerm(Field.TAGS_ENTRIES, keywords);
442             }
443 
444             BooleanQuery fullQuery = BooleanQueryFactoryUtil.create();
445 
446             fullQuery.add(contextQuery, BooleanClauseOccur.MUST);
447 
448             if (searchQuery.clauses().size() > 0) {
449                 fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
450             }
451 
452             return SearchEngineUtil.search(companyId, fullQuery, start, end);
453         }
454         catch (Exception e) {
455             throw new SystemException(e);
456         }
457     }
458 
459     public Company updateCompany(long companyId, String virtualHost, String mx)
460         throws PortalException, SystemException {
461 
462         virtualHost = virtualHost.trim().toLowerCase();
463 
464         Company company = companyPersistence.findByPrimaryKey(companyId);
465 
466         validate(company.getWebId(), virtualHost, mx);
467 
468         company.setVirtualHost(virtualHost);
469 
470         if (PropsValues.MAIL_MX_UPDATE) {
471             company.setMx(mx);
472         }
473 
474         companyPersistence.update(company, false);
475 
476         return company;
477     }
478 
479     public Company updateCompany(
480             long companyId, String virtualHost, String mx, String homeURL,
481             String name, String legalName, String legalId, String legalType,
482             String sicCode, String tickerSymbol, String industry, String type,
483             String size)
484         throws PortalException, SystemException {
485 
486         // Company
487 
488         virtualHost = virtualHost.trim().toLowerCase();
489         Date now = new Date();
490 
491         Company company = companyPersistence.findByPrimaryKey(companyId);
492 
493         validate(company.getWebId(), virtualHost, mx);
494         validate(name);
495 
496         company.setVirtualHost(virtualHost);
497 
498         if (PropsValues.MAIL_MX_UPDATE) {
499             company.setMx(mx);
500         }
501 
502         company.setHomeURL(homeURL);
503 
504         companyPersistence.update(company, false);
505 
506         // Account
507 
508         Account account = accountPersistence.fetchByPrimaryKey(
509             company.getAccountId());
510 
511         if (account == null) {
512             long accountId = counterLocalService.increment();
513 
514             account = accountPersistence.create(accountId);
515 
516             account.setCreateDate(now);
517             account.setCompanyId(companyId);
518             account.setUserId(0);
519             account.setUserName(StringPool.BLANK);
520 
521             company.setAccountId(accountId);
522 
523             companyPersistence.update(company, false);
524         }
525 
526         account.setModifiedDate(now);
527         account.setName(name);
528         account.setLegalName(legalName);
529         account.setLegalId(legalId);
530         account.setLegalType(legalType);
531         account.setSicCode(sicCode);
532         account.setTickerSymbol(tickerSymbol);
533         account.setIndustry(industry);
534         account.setType(type);
535         account.setSize(size);
536 
537         accountPersistence.update(account, false);
538 
539         return company;
540     }
541 
542     public void updateDisplay(
543             long companyId, String languageId, String timeZoneId)
544         throws PortalException, SystemException {
545 
546         User user = userLocalService.getDefaultUser(companyId);
547 
548         user.setLanguageId(languageId);
549         user.setTimeZoneId(timeZoneId);
550 
551         userPersistence.update(user, false);
552     }
553 
554     public void updateLogo(long companyId, byte[] bytes)
555         throws PortalException, SystemException {
556 
557         long logoId = getLogoId(companyId);
558 
559         imageLocalService.updateImage(logoId, bytes);
560     }
561 
562     public void updateLogo(long companyId, File file)
563         throws PortalException, SystemException {
564 
565         long logoId = getLogoId(companyId);
566 
567         imageLocalService.updateImage(logoId, file);
568     }
569 
570     public void updateLogo(long companyId, InputStream is)
571         throws PortalException, SystemException {
572 
573         long logoId = getLogoId(companyId);
574 
575         imageLocalService.updateImage(logoId, is);
576     }
577 
578     public void updateSecurity(
579             long companyId, String authType, boolean autoLogin,
580             boolean sendPassword, boolean strangers, boolean strangersWithMx,
581             boolean strangersVerify, boolean communityLogo)
582         throws SystemException {
583 
584         PortletPreferences preferences = PrefsPropsUtil.getPreferences(
585             companyId);
586 
587         try {
588             preferences.setValue(
589                 PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
590             preferences.setValue(
591                 PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
592                 String.valueOf(autoLogin));
593             preferences.setValue(
594                 PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
595                 String.valueOf(sendPassword));
596             preferences.setValue(
597                 PropsKeys.COMPANY_SECURITY_STRANGERS,
598                 String.valueOf(strangers));
599             preferences.setValue(
600                 PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
601                 String.valueOf(strangersWithMx));
602             preferences.setValue(
603                 PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
604                 String.valueOf(strangersVerify));
605             preferences.setValue(
606                 PropsKeys.COMPANY_SECURITY_COMMUNITY_LOGO,
607                 String.valueOf(communityLogo));
608 
609             preferences.store();
610         }
611         catch (IOException ioe) {
612             throw new SystemException(ioe);
613         }
614         catch (PortletException pe) {
615             throw new SystemException(pe);
616         }
617     }
618 
619     protected long getLogoId(long companyId)
620         throws PortalException, SystemException {
621 
622         Company company = companyPersistence.findByPrimaryKey(companyId);
623 
624         long logoId = company.getLogoId();
625 
626         if (logoId <= 0) {
627             logoId = counterLocalService.increment();
628 
629             company.setLogoId(logoId);
630 
631             companyPersistence.update(company, false);
632         }
633 
634         return logoId;
635     }
636 
637     protected void validate(String name) throws PortalException {
638         if (Validator.isNull(name)) {
639             throw new AccountNameException();
640         }
641     }
642 
643     protected void validate(String webId, String virtualHost, String mx)
644         throws PortalException, SystemException {
645 
646         if (Validator.isNull(virtualHost)) {
647             throw new CompanyVirtualHostException();
648         }
649         else if (virtualHost.equals(_DEFAULT_VIRTUAL_HOST) &&
650                  !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
651 
652             throw new CompanyVirtualHostException();
653         }
654         else if (!Validator.isDomain(virtualHost)) {
655             throw new CompanyVirtualHostException();
656         }
657         else {
658             try {
659                 Company virtualHostCompany = getCompanyByVirtualHost(
660                     virtualHost);
661 
662                 if ((virtualHostCompany != null) &&
663                     (!virtualHostCompany.getWebId().equals(webId))) {
664 
665                     throw new CompanyVirtualHostException();
666                 }
667             }
668             catch (NoSuchCompanyException nsce) {
669             }
670 
671             try {
672                 layoutSetLocalService.getLayoutSet(virtualHost);
673 
674                 throw new CompanyVirtualHostException();
675             }
676             catch (NoSuchLayoutSetException nslse) {
677             }
678         }
679 
680         if (Validator.isNull(mx)) {
681             throw new CompanyMxException();
682         }
683         else if (!Validator.isDomain(mx)) {
684             throw new CompanyMxException();
685         }
686     }
687 
688     private static final String _DEFAULT_VIRTUAL_HOST = "localhost";
689 
690 }