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