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