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