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