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