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