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.search.Hits;
36  import com.liferay.portal.kernel.util.StringPool;
37  import com.liferay.portal.kernel.util.Validator;
38  import com.liferay.portal.lucene.LuceneFields;
39  import com.liferay.portal.lucene.LuceneUtil;
40  import com.liferay.portal.model.Account;
41  import com.liferay.portal.model.Company;
42  import com.liferay.portal.model.Contact;
43  import com.liferay.portal.model.Group;
44  import com.liferay.portal.model.Organization;
45  import com.liferay.portal.model.Role;
46  import com.liferay.portal.model.User;
47  import com.liferay.portal.model.impl.CompanyImpl;
48  import com.liferay.portal.model.impl.ContactImpl;
49  import com.liferay.portal.model.impl.CountryImpl;
50  import com.liferay.portal.model.impl.GroupImpl;
51  import com.liferay.portal.model.impl.ListTypeImpl;
52  import com.liferay.portal.model.impl.OrganizationImpl;
53  import com.liferay.portal.model.impl.RegionImpl;
54  import com.liferay.portal.model.impl.RoleImpl;
55  import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
56  import com.liferay.portal.util.PortalInstances;
57  import com.liferay.portal.util.PrefsPropsUtil;
58  import com.liferay.portal.util.PropsUtil;
59  import com.liferay.portal.util.PropsValues;
60  import com.liferay.util.Encryptor;
61  import com.liferay.util.EncryptorException;
62  import com.liferay.util.Normalizer;
63  import com.liferay.util.lucene.HitsImpl;
64  
65  import java.io.File;
66  import java.io.IOException;
67  
68  import java.util.Calendar;
69  import java.util.Date;
70  import java.util.List;
71  import java.util.Locale;
72  
73  import javax.portlet.PortletException;
74  import javax.portlet.PortletPreferences;
75  
76  import org.apache.lucene.search.BooleanClause;
77  import org.apache.lucene.search.BooleanQuery;
78  import org.apache.lucene.search.Searcher;
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(CompanyImpl.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);
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(CompanyImpl.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);
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);
181 
182                 updateSecurity(
183                     companyId, CompanyImpl.AUTH_TYPE_EA, true, true, true, true,
184                     false, true);
185 
186                 PortletPreferences prefs =
187                     PrefsPropsUtil.getPreferences(companyId);
188 
189                 try {
190                     prefs.setValue(
191                         PropsUtil.ADMIN_EMAIL_FROM_NAME, "Liferay Demo");
192                     prefs.setValue(
193                         PropsUtil.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);
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("Welcome!");
241             defaultUser.setLoginDate(now);
242             defaultUser.setFailedLoginAttempts(0);
243             defaultUser.setAgreedToTermsOfUse(true);
244             defaultUser.setActive(true);
245 
246             userPersistence.update(defaultUser);
247 
248             // Contact
249 
250             Contact defaultContact = contactPersistence.create(
251                 defaultUser.getContactId());
252 
253             defaultContact.setCompanyId(defaultUser.getCompanyId());
254             defaultContact.setUserId(defaultUser.getUserId());
255             defaultContact.setUserName(StringPool.BLANK);
256             defaultContact.setCreateDate(now);
257             defaultContact.setModifiedDate(now);
258             defaultContact.setAccountId(company.getAccountId());
259             defaultContact.setParentContactId(
260                 ContactImpl.DEFAULT_PARENT_CONTACT_ID);
261             defaultContact.setFirstName(StringPool.BLANK);
262             defaultContact.setMiddleName(StringPool.BLANK);
263             defaultContact.setLastName(StringPool.BLANK);
264             defaultContact.setMale(true);
265             defaultContact.setBirthday(now);
266 
267             contactPersistence.update(defaultContact);
268         }
269 
270         // System groups
271 
272         groupLocalService.checkSystemGroups(companyId);
273 
274         // Default password policy
275 
276         passwordPolicyLocalService.checkDefaultPasswordPolicy(companyId);
277 
278         // System roles
279 
280         roleLocalService.checkSystemRoles(companyId);
281 
282         // Default user must have the Guest role
283 
284         Role guestRole = roleLocalService.getRole(companyId, RoleImpl.GUEST);
285 
286         roleLocalService.setUserRoles(
287             defaultUser.getUserId(), new long[] {guestRole.getRoleId()});
288 
289         // Default admin
290 
291         if (userPersistence.countByCompanyId(companyId) == 1) {
292             long creatorUserId = 0;
293             boolean autoPassword = false;
294             String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
295             String password2 = password1;
296             boolean autoScreenName = false;
297             String screenName = PropsValues.DEFAULT_ADMIN_SCREEN_NAME;
298             String emailAddress =
299                 PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + "@" + mx;
300             Locale locale = defaultUser.getLocale();
301             String firstName = PropsValues.DEFAULT_ADMIN_FIRST_NAME;
302             String middleName = PropsValues.DEFAULT_ADMIN_MIDDLE_NAME;
303             String lastName = PropsValues.DEFAULT_ADMIN_LAST_NAME;
304             int prefixId = 0;
305             int suffixId = 0;
306             boolean male = true;
307             int birthdayMonth = Calendar.JANUARY;
308             int birthdayDay = 1;
309             int birthdayYear = 1970;
310             String jobTitle = StringPool.BLANK;
311             long[] organizationIds = new long[0];
312 
313             User user = userLocalService.addUser(
314                 creatorUserId, companyId, autoPassword, password1, password2,
315                 autoScreenName, screenName, emailAddress, locale, firstName,
316                 middleName, lastName, prefixId, suffixId, male, birthdayMonth,
317                 birthdayDay, birthdayYear, jobTitle, organizationIds, false);
318 
319             Group guestGroup = groupLocalService.getGroup(
320                 companyId, GroupImpl.GUEST);
321 
322             long[] groupIds = new long[] {guestGroup.getGroupId()};
323 
324             groupLocalService.addUserGroups(user.getUserId(), groupIds);
325 
326             Role adminRole = roleLocalService.getRole(
327                 companyId, RoleImpl.ADMINISTRATOR);
328 
329             Role powerUserRole = roleLocalService.getRole(
330                 companyId, RoleImpl.POWER_USER);
331 
332             long[] roleIds = new long[] {
333                 adminRole.getRoleId(), powerUserRole.getRoleId()
334             };
335 
336             roleLocalService.setUserRoles(user.getUserId(), roleIds);
337 
338             Organization organization =
339                 organizationLocalService.addOrganization(
340                     user.getUserId(),
341                     OrganizationImpl.DEFAULT_PARENT_ORGANIZATION_ID,
342                     "Test Organization", OrganizationImpl.TYPE_REGULAR, true,
343                     RegionImpl.DEFAULT_REGION_ID,
344                     CountryImpl.DEFAULT_COUNTRY_ID,
345                     ListTypeImpl.ORGANIZATION_STATUS_DEFAULT, StringPool.BLANK);
346 
347             organizationLocalService.addOrganization(
348                 user.getUserId(), organization.getOrganizationId(),
349                 "Test Location", OrganizationImpl.TYPE_LOCATION, true,
350                 RegionImpl.DEFAULT_REGION_ID, CountryImpl.DEFAULT_COUNTRY_ID,
351                 ListTypeImpl.ORGANIZATION_STATUS_DEFAULT, StringPool.BLANK);
352         }
353 
354         return company;
355     }
356 
357     public void checkCompanyKey(long companyId)
358         throws PortalException, SystemException {
359 
360         Company company = companyPersistence.findByPrimaryKey(companyId);
361 
362         if (company.getKeyObj() == null) {
363             try {
364                 company.setKeyObj(Encryptor.generateKey());
365             }
366             catch (EncryptorException ee) {
367                 throw new SystemException(ee);
368             }
369         }
370 
371         companyPersistence.update(company);
372     }
373 
374     public List getCompanies() throws SystemException {
375         return companyPersistence.findAll();
376     }
377 
378     public Company getCompanyById(long companyId)
379         throws PortalException, SystemException {
380 
381         return companyPersistence.findByPrimaryKey(companyId);
382     }
383 
384     public Company getCompanyByLogoId(long logoId)
385         throws PortalException, SystemException {
386 
387         return companyPersistence.findByLogoId(logoId);
388     }
389 
390     public Company getCompanyByMx(String mx)
391         throws PortalException, SystemException {
392 
393         return companyPersistence.findByMx(mx);
394     }
395 
396     public Company getCompanyByVirtualHost(String virtualHost)
397         throws PortalException, SystemException {
398 
399         virtualHost = getVirtualHost(virtualHost);
400 
401         return companyPersistence.findByVirtualHost(virtualHost);
402     }
403 
404     public Company getCompanyByWebId(String webId)
405         throws PortalException, SystemException {
406 
407         return companyPersistence.findByWebId(webId);
408     }
409 
410     public Hits search(long companyId, String keywords)
411         throws SystemException {
412 
413         return search(companyId, null, 0, null, keywords);
414     }
415 
416     public Hits search(
417             long companyId, String portletId, long groupId, String type,
418             String keywords)
419         throws SystemException {
420 
421         Searcher searcher = null;
422 
423         try {
424             HitsImpl hits = new HitsImpl();
425 
426             BooleanQuery contextQuery = new BooleanQuery();
427 
428             LuceneUtil.addRequiredTerm(
429                 contextQuery, LuceneFields.COMPANY_ID, companyId);
430 
431             if (Validator.isNotNull(portletId)) {
432                 LuceneUtil.addRequiredTerm(
433                     contextQuery, LuceneFields.PORTLET_ID, portletId);
434             }
435 
436             if (groupId > 0) {
437                 LuceneUtil.addRequiredTerm(
438                     contextQuery, LuceneFields.GROUP_ID, groupId);
439             }
440 
441             if (Validator.isNotNull(type)) {
442                 LuceneUtil.addRequiredTerm(
443                     contextQuery, LuceneFields.TYPE, type);
444             }
445 
446             BooleanQuery searchQuery = new BooleanQuery();
447 
448             if (Validator.isNotNull(keywords)) {
449                 LuceneUtil.addTerm(searchQuery, LuceneFields.TITLE, keywords);
450                 LuceneUtil.addTerm(searchQuery, LuceneFields.CONTENT, keywords);
451                 LuceneUtil.addTerm(
452                     searchQuery, LuceneFields.DESCRIPTION, keywords);
453                 LuceneUtil.addTerm(
454                     searchQuery, LuceneFields.PROPERTIES, keywords);
455                 LuceneUtil.addTerm(
456                     searchQuery, LuceneFields.TAG_ENTRY, keywords);
457             }
458 
459             BooleanQuery fullQuery = new BooleanQuery();
460 
461             fullQuery.add(contextQuery, BooleanClause.Occur.MUST);
462 
463             if (searchQuery.clauses().size() > 0) {
464                 fullQuery.add(searchQuery, BooleanClause.Occur.MUST);
465             }
466 
467             searcher = LuceneUtil.getSearcher(companyId);
468 
469             hits.recordHits(searcher.search(fullQuery), searcher);
470 
471             return hits;
472         }
473         catch (Exception e) {
474             return LuceneUtil.closeSearcher(searcher, keywords, e);
475         }
476     }
477 
478     public Company updateCompany(long companyId, String virtualHost, String mx)
479         throws PortalException, SystemException {
480 
481         virtualHost = getVirtualHost(virtualHost);
482 
483         Company company = companyPersistence.findByPrimaryKey(companyId);
484 
485         validate(company.getWebId(), virtualHost, mx);
486 
487         company.setVirtualHost(virtualHost);
488 
489         if (PropsValues.MAIL_MX_UPDATE) {
490             company.setMx(mx);
491         }
492 
493         companyPersistence.update(company);
494 
495         return company;
496     }
497 
498     public Company updateCompany(
499             long companyId, String virtualHost, String mx, String name,
500             String legalName, String legalId, String legalType, String sicCode,
501             String tickerSymbol, String industry, String type, String size)
502         throws PortalException, SystemException {
503 
504         // Company
505 
506         virtualHost = getVirtualHost(virtualHost);
507         Date now = new Date();
508 
509         Company company = companyPersistence.findByPrimaryKey(companyId);
510 
511         validate(company.getWebId(), virtualHost, mx);
512         validate(name);
513 
514         company.setVirtualHost(virtualHost);
515 
516         if (PropsValues.MAIL_MX_UPDATE) {
517             company.setMx(mx);
518         }
519 
520         companyPersistence.update(company);
521 
522         // Account
523 
524         Account account = null;
525 
526         try {
527             account = accountPersistence.findByPrimaryKey(
528                 company.getAccountId());
529         }
530         catch (NoSuchAccountException nsae) {
531             long accountId = counterLocalService.increment();
532 
533             account = accountPersistence.create(accountId);
534 
535             account.setCreateDate(now);
536             account.setCompanyId(companyId);
537             account.setUserId(0);
538             account.setUserName(StringPool.BLANK);
539 
540             company.setAccountId(accountId);
541 
542             companyPersistence.update(company);
543         }
544 
545         account.setModifiedDate(now);
546         account.setName(name);
547         account.setLegalName(legalName);
548         account.setLegalId(legalId);
549         account.setLegalType(legalType);
550         account.setSicCode(sicCode);
551         account.setTickerSymbol(tickerSymbol);
552         account.setIndustry(industry);
553         account.setType(type);
554         account.setSize(size);
555 
556         accountPersistence.update(account);
557 
558         return company;
559     }
560 
561     public void updateDisplay(
562             long companyId, String languageId, String timeZoneId)
563         throws PortalException, SystemException {
564 
565         User user = userLocalService.getDefaultUser(companyId);
566 
567         user.setLanguageId(languageId);
568         user.setTimeZoneId(timeZoneId);
569 
570         userPersistence.update(user);
571     }
572 
573     public void updateLogo(long companyId, File file)
574         throws PortalException, SystemException {
575 
576         Company company = companyPersistence.findByPrimaryKey(companyId);
577 
578         long logoId = company.getLogoId();
579 
580         if (logoId <= 0) {
581             logoId = counterLocalService.increment();
582 
583             company.setLogoId(logoId);
584         }
585 
586         ImageLocalUtil.updateImage(logoId, file);
587     }
588 
589     public void updateSecurity(
590             long companyId, String authType, boolean autoLogin,
591             boolean sendPassword, boolean strangers, boolean strangersWithMx,
592             boolean strangersVerify, boolean communityLogo)
593         throws PortalException, SystemException {
594 
595         PortletPreferences prefs = PrefsPropsUtil.getPreferences(companyId);
596 
597         try {
598             prefs.setValue(PropsUtil.COMPANY_SECURITY_AUTH_TYPE, authType);
599             prefs.setValue(
600                 PropsUtil.COMPANY_SECURITY_AUTO_LOGIN,
601                 String.valueOf(autoLogin));
602             prefs.setValue(
603                 PropsUtil.COMPANY_SECURITY_SEND_PASSWORD,
604                 String.valueOf(sendPassword));
605             prefs.setValue(
606                 PropsUtil.COMPANY_SECURITY_STRANGERS,
607                 String.valueOf(strangers));
608             prefs.setValue(
609                 PropsUtil.COMPANY_SECURITY_STRANGERS_WITH_MX,
610                 String.valueOf(strangersWithMx));
611             prefs.setValue(
612                 PropsUtil.COMPANY_SECURITY_STRANGERS_VERIFY,
613                 String.valueOf(strangersVerify));
614             prefs.setValue(
615                 PropsUtil.COMPANY_SECURITY_COMMUNITY_LOGO,
616                 String.valueOf(communityLogo));
617 
618             prefs.store();
619         }
620         catch (IOException ioe) {
621             throw new SystemException(ioe);
622         }
623         catch (PortletException pe) {
624             throw new SystemException(pe);
625         }
626     }
627 
628     protected String getVirtualHost(String virtualHost) {
629         return Normalizer.normalizeToAscii(virtualHost.trim().toLowerCase());
630     }
631 
632     protected void validate(String name) throws PortalException {
633         if (Validator.isNull(name)) {
634             throw new AccountNameException();
635         }
636     }
637 
638     protected void validate(String webId, String virtualHost, String mx)
639         throws PortalException, SystemException {
640 
641         if (Validator.isNull(virtualHost)) {
642             throw new CompanyVirtualHostException();
643         }
644         else if (virtualHost.equals(PortalInstances.DEFAULT_VIRTUAL_HOST) &&
645                  !webId.equals(CompanyImpl.DEFAULT_WEB_ID)) {
646 
647             throw new CompanyVirtualHostException();
648         }
649         else {
650             try {
651                 Company virtualHostCompany = getCompanyByVirtualHost(
652                     virtualHost);
653 
654                 if (!virtualHostCompany.getWebId().equals(webId)) {
655                     throw new CompanyVirtualHostException();
656                 }
657             }
658             catch (NoSuchCompanyException nsce) {
659             }
660 
661             try {
662                 layoutSetLocalService.getLayoutSet(virtualHost);
663 
664                 throw new CompanyVirtualHostException();
665             }
666             catch (NoSuchLayoutSetException nslse) {
667             }
668         }
669 
670         if (Validator.isNull(mx)) {
671             throw new CompanyMxException();
672         }
673     }
674 
675 }