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.NoSuchCompanyException;
30  import com.liferay.portal.NoSuchLayoutSetException;
31  import com.liferay.portal.NoSuchUserException;
32  import com.liferay.portal.PortalException;
33  import com.liferay.portal.SystemException;
34  import com.liferay.portal.kernel.language.LanguageUtil;
35  import com.liferay.portal.kernel.search.BooleanClauseOccur;
36  import com.liferay.portal.kernel.search.BooleanQuery;
37  import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
38  import com.liferay.portal.kernel.search.Field;
39  import com.liferay.portal.kernel.search.Hits;
40  import com.liferay.portal.kernel.search.SearchEngineUtil;
41  import com.liferay.portal.kernel.util.StringPool;
42  import com.liferay.portal.kernel.util.Validator;
43  import com.liferay.portal.model.Account;
44  import com.liferay.portal.model.Company;
45  import com.liferay.portal.model.CompanyConstants;
46  import com.liferay.portal.model.Contact;
47  import com.liferay.portal.model.ContactConstants;
48  import com.liferay.portal.model.Group;
49  import com.liferay.portal.model.GroupConstants;
50  import com.liferay.portal.model.Organization;
51  import com.liferay.portal.model.OrganizationConstants;
52  import com.liferay.portal.model.Role;
53  import com.liferay.portal.model.RoleConstants;
54  import com.liferay.portal.model.User;
55  import com.liferay.portal.model.impl.CountryImpl;
56  import com.liferay.portal.model.impl.ListTypeImpl;
57  import com.liferay.portal.model.impl.RegionImpl;
58  import com.liferay.portal.search.lucene.LuceneUtil;
59  import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
60  import com.liferay.portal.util.PortalInstances;
61  import com.liferay.portal.util.PrefsPropsUtil;
62  import com.liferay.portal.util.PropsKeys;
63  import com.liferay.portal.util.PropsValues;
64  import com.liferay.util.Encryptor;
65  import com.liferay.util.EncryptorException;
66  import com.liferay.util.Normalizer;
67  
68  import java.io.File;
69  import java.io.IOException;
70  
71  import java.util.Calendar;
72  import java.util.Date;
73  import java.util.List;
74  import java.util.Locale;
75  
76  import javax.portlet.PortletException;
77  import javax.portlet.PortletPreferences;
78  
79  /**
80   * <a href="CompanyLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
81   *
82   * @author Brian Wing Shun Chan
83   *
84   */
85  public class CompanyLocalServiceImpl extends CompanyLocalServiceBaseImpl {
86  
87      public Company addCompany(String webId, String virtualHost, String mx)
88          throws PortalException, SystemException {
89  
90          // Company
91  
92          virtualHost = getVirtualHost(virtualHost);
93  
94          if ((Validator.isNull(webId)) ||
95              (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) ||
96              (companyPersistence.fetchByWebId(webId) != null)) {
97  
98              throw new CompanyWebIdException();
99          }
100 
101         validate(webId, virtualHost, mx);
102 
103         Company company = checkCompany(webId, mx);
104 
105         company.setVirtualHost(virtualHost);
106         company.setMx(mx);
107 
108         companyPersistence.update(company, false);
109 
110         // Lucene
111 
112         LuceneUtil.checkLuceneDir(company.getCompanyId());
113 
114         return company;
115     }
116 
117     public Company checkCompany(String webId)
118         throws PortalException, SystemException {
119 
120         String mx = webId;
121 
122         return checkCompany(webId, mx);
123     }
124 
125     public Company checkCompany(String webId, String mx)
126         throws PortalException, SystemException {
127 
128         // Company
129 
130         Date now = new Date();
131 
132         Company company = companyPersistence.fetchByWebId(webId);
133 
134         if (company == null) {
135             String virtualHost = webId;
136 
137             if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
138                 virtualHost = PortalInstances.DEFAULT_VIRTUAL_HOST;
139             }
140 
141             String name = webId;
142             String legalName = null;
143             String legalId = null;
144             String legalType = null;
145             String sicCode = null;
146             String tickerSymbol = null;
147             String industry = null;
148             String type = null;
149             String size = null;
150 
151             long companyId = counterLocalService.increment();
152 
153             company = companyPersistence.create(companyId);
154 
155             try {
156                 company.setKeyObj(Encryptor.generateKey());
157             }
158             catch (EncryptorException ee) {
159                 throw new SystemException(ee);
160             }
161 
162             company.setWebId(webId);
163             company.setVirtualHost(virtualHost);
164             company.setMx(mx);
165 
166             companyPersistence.update(company, false);
167 
168             updateCompany(
169                 companyId, virtualHost, mx, name, legalName, legalId, legalType,
170                 sicCode, tickerSymbol, industry, type, size);
171 
172             // Demo settings
173 
174             if (webId.equals("liferay.net")) {
175                 company = companyPersistence.findByWebId(webId);
176 
177                 company.setVirtualHost("demo.liferay.net");
178 
179                 companyPersistence.update(company, false);
180 
181                 updateSecurity(
182                     companyId, CompanyConstants.AUTH_TYPE_EA, true, true, true,
183                     true, false, true);
184 
185                 PortletPreferences prefs =
186                     PrefsPropsUtil.getPreferences(companyId);
187 
188                 try {
189                     prefs.setValue(
190                         PropsKeys.ADMIN_EMAIL_FROM_NAME, "Liferay Demo");
191                     prefs.setValue(
192                         PropsKeys.ADMIN_EMAIL_FROM_ADDRESS, "test@liferay.net");
193 
194                     prefs.store();
195                 }
196                 catch (IOException ioe) {
197                     throw new SystemException(ioe);
198                 }
199                 catch (PortletException pe) {
200                     throw new SystemException(pe);
201                 }
202             }
203         }
204 
205         long companyId = company.getCompanyId();
206 
207         // Key
208 
209         checkCompanyKey(companyId);
210 
211         // Default user
212 
213         User defaultUser = null;
214 
215         try {
216             defaultUser = userLocalService.getDefaultUser(companyId);
217 
218             if (!defaultUser.isAgreedToTermsOfUse()) {
219                 defaultUser.setAgreedToTermsOfUse(true);
220 
221                 userPersistence.update(defaultUser, false);
222             }
223         }
224         catch (NoSuchUserException nsue) {
225             long userId = counterLocalService.increment();
226 
227             defaultUser = userPersistence.create(userId);
228 
229             defaultUser.setCompanyId(companyId);
230             defaultUser.setCreateDate(now);
231             defaultUser.setModifiedDate(now);
232             defaultUser.setDefaultUser(true);
233             defaultUser.setContactId(counterLocalService.increment());
234             defaultUser.setPassword("password");
235             defaultUser.setScreenName(String.valueOf(defaultUser.getUserId()));
236             defaultUser.setEmailAddress("default@" + company.getMx());
237             defaultUser.setLanguageId(null);
238             defaultUser.setTimeZoneId(null);
239             defaultUser.setGreeting(
240                 LanguageUtil.format(
241                     companyId, defaultUser.getLocale(), "welcome-x",
242                     StringPool.BLANK));
243             defaultUser.setLoginDate(now);
244             defaultUser.setFailedLoginAttempts(0);
245             defaultUser.setAgreedToTermsOfUse(true);
246             defaultUser.setActive(true);
247 
248             userPersistence.update(defaultUser, false);
249 
250             // Contact
251 
252             Contact defaultContact = contactPersistence.create(
253                 defaultUser.getContactId());
254 
255             defaultContact.setCompanyId(defaultUser.getCompanyId());
256             defaultContact.setUserId(defaultUser.getUserId());
257             defaultContact.setUserName(StringPool.BLANK);
258             defaultContact.setCreateDate(now);
259             defaultContact.setModifiedDate(now);
260             defaultContact.setAccountId(company.getAccountId());
261             defaultContact.setParentContactId(
262                 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
263             defaultContact.setFirstName(StringPool.BLANK);
264             defaultContact.setMiddleName(StringPool.BLANK);
265             defaultContact.setLastName(StringPool.BLANK);
266             defaultContact.setMale(true);
267             defaultContact.setBirthday(now);
268 
269             contactPersistence.update(defaultContact, false);
270         }
271 
272         // System roles
273 
274         roleLocalService.checkSystemRoles(companyId);
275 
276         // System groups
277 
278         groupLocalService.checkSystemGroups(companyId);
279 
280         // Default password policy
281 
282         passwordPolicyLocalService.checkDefaultPasswordPolicy(companyId);
283 
284         // Default user must have the Guest role
285 
286         Role guestRole = roleLocalService.getRole(
287             companyId, RoleConstants.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, GroupConstants.GUEST);
324 
325             long[] groupIds = new long[] {guestGroup.getGroupId()};
326 
327             groupLocalService.addUserGroups(user.getUserId(), groupIds);
328 
329             Role adminRole = roleLocalService.getRole(
330                 companyId, RoleConstants.ADMINISTRATOR);
331 
332             Role powerUserRole = roleLocalService.getRole(
333                 companyId, RoleConstants.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 = BooleanQueryFactoryUtil.create();
426 
427             contextQuery.addRequiredTerm(Field.COMPANY_ID, companyId);
428 
429             if (Validator.isNotNull(portletId)) {
430                 contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);
431             }
432 
433             if (groupId > 0) {
434                 contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
435             }
436 
437             if (Validator.isNotNull(type)) {
438                 contextQuery.addRequiredTerm(Field.TYPE, type);
439             }
440 
441             BooleanQuery searchQuery = BooleanQueryFactoryUtil.create();
442 
443             if (Validator.isNotNull(keywords)) {
444                 searchQuery.addTerm(Field.TITLE, keywords);
445                 searchQuery.addTerm(Field.CONTENT, keywords);
446                 searchQuery.addTerm(Field.DESCRIPTION, keywords);
447                 searchQuery.addTerm(Field.PROPERTIES, keywords);
448                 searchQuery.addTerm(Field.TAGS_ENTRIES, keywords);
449             }
450 
451             BooleanQuery fullQuery = BooleanQueryFactoryUtil.create();
452 
453             fullQuery.add(contextQuery, BooleanClauseOccur.MUST);
454 
455             if (searchQuery.clauses().size() > 0) {
456                 fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
457             }
458 
459             return SearchEngineUtil.search(companyId, fullQuery, start, end);
460         }
461         catch (Exception e) {
462             throw new SystemException(e);
463         }
464     }
465 
466     public Company updateCompany(long companyId, String virtualHost, String mx)
467         throws PortalException, SystemException {
468 
469         virtualHost = getVirtualHost(virtualHost);
470 
471         Company company = companyPersistence.findByPrimaryKey(companyId);
472 
473         validate(company.getWebId(), virtualHost, mx);
474 
475         company.setVirtualHost(virtualHost);
476 
477         if (PropsValues.MAIL_MX_UPDATE) {
478             company.setMx(mx);
479         }
480 
481         companyPersistence.update(company, false);
482 
483         return company;
484     }
485 
486     public Company updateCompany(
487             long companyId, String virtualHost, String mx, String name,
488             String legalName, String legalId, String legalType, String sicCode,
489             String tickerSymbol, String industry, String type, String size)
490         throws PortalException, SystemException {
491 
492         // Company
493 
494         virtualHost = getVirtualHost(virtualHost);
495         Date now = new Date();
496 
497         Company company = companyPersistence.findByPrimaryKey(companyId);
498 
499         validate(company.getWebId(), virtualHost, mx);
500         validate(name);
501 
502         company.setVirtualHost(virtualHost);
503 
504         if (PropsValues.MAIL_MX_UPDATE) {
505             company.setMx(mx);
506         }
507 
508         companyPersistence.update(company, false);
509 
510         // Account
511 
512         Account account = accountPersistence.fetchByPrimaryKey(
513             company.getAccountId());
514 
515         if (account == null) {
516             long accountId = counterLocalService.increment();
517 
518             account = accountPersistence.create(accountId);
519 
520             account.setCreateDate(now);
521             account.setCompanyId(companyId);
522             account.setUserId(0);
523             account.setUserName(StringPool.BLANK);
524 
525             company.setAccountId(accountId);
526 
527             companyPersistence.update(company, false);
528         }
529 
530         account.setModifiedDate(now);
531         account.setName(name);
532         account.setLegalName(legalName);
533         account.setLegalId(legalId);
534         account.setLegalType(legalType);
535         account.setSicCode(sicCode);
536         account.setTickerSymbol(tickerSymbol);
537         account.setIndustry(industry);
538         account.setType(type);
539         account.setSize(size);
540 
541         accountPersistence.update(account, false);
542 
543         return company;
544     }
545 
546     public void updateDisplay(
547             long companyId, String languageId, String timeZoneId)
548         throws PortalException, SystemException {
549 
550         User user = userLocalService.getDefaultUser(companyId);
551 
552         user.setLanguageId(languageId);
553         user.setTimeZoneId(timeZoneId);
554 
555         userPersistence.update(user, false);
556     }
557 
558     public void updateLogo(long companyId, File file)
559         throws PortalException, SystemException {
560 
561         Company company = companyPersistence.findByPrimaryKey(companyId);
562 
563         long logoId = company.getLogoId();
564 
565         if (logoId <= 0) {
566             logoId = counterLocalService.increment();
567 
568             company.setLogoId(logoId);
569         }
570 
571         imageLocalService.updateImage(logoId, file);
572     }
573 
574     public void updateSecurity(
575             long companyId, String authType, boolean autoLogin,
576             boolean sendPassword, boolean strangers, boolean strangersWithMx,
577             boolean strangersVerify, boolean communityLogo)
578         throws SystemException {
579 
580         PortletPreferences prefs = PrefsPropsUtil.getPreferences(companyId);
581 
582         try {
583             prefs.setValue(PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
584             prefs.setValue(
585                 PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
586                 String.valueOf(autoLogin));
587             prefs.setValue(
588                 PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
589                 String.valueOf(sendPassword));
590             prefs.setValue(
591                 PropsKeys.COMPANY_SECURITY_STRANGERS,
592                 String.valueOf(strangers));
593             prefs.setValue(
594                 PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
595                 String.valueOf(strangersWithMx));
596             prefs.setValue(
597                 PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
598                 String.valueOf(strangersVerify));
599             prefs.setValue(
600                 PropsKeys.COMPANY_SECURITY_COMMUNITY_LOGO,
601                 String.valueOf(communityLogo));
602 
603             prefs.store();
604         }
605         catch (IOException ioe) {
606             throw new SystemException(ioe);
607         }
608         catch (PortletException pe) {
609             throw new SystemException(pe);
610         }
611     }
612 
613     protected String getVirtualHost(String virtualHost) {
614         return Normalizer.normalizeToAscii(virtualHost.trim().toLowerCase());
615     }
616 
617     protected void validate(String name) throws PortalException {
618         if (Validator.isNull(name)) {
619             throw new AccountNameException();
620         }
621     }
622 
623     protected void validate(String webId, String virtualHost, String mx)
624         throws PortalException, SystemException {
625 
626         if (Validator.isNull(virtualHost)) {
627             throw new CompanyVirtualHostException();
628         }
629         else if (virtualHost.equals(PortalInstances.DEFAULT_VIRTUAL_HOST) &&
630                  !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
631 
632             throw new CompanyVirtualHostException();
633         }
634         else if (!Validator.isDomain(virtualHost)) {
635             throw new CompanyVirtualHostException();
636         }
637         else {
638             try {
639                 Company virtualHostCompany = getCompanyByVirtualHost(
640                     virtualHost);
641 
642                 if ((virtualHostCompany != null) &&
643                     (!virtualHostCompany.getWebId().equals(webId))) {
644 
645                     throw new CompanyVirtualHostException();
646                 }
647             }
648             catch (NoSuchCompanyException nsce) {
649             }
650 
651             try {
652                 layoutSetLocalService.getLayoutSet(virtualHost);
653 
654                 throw new CompanyVirtualHostException();
655             }
656             catch (NoSuchLayoutSetException nslse) {
657             }
658         }
659 
660         if (Validator.isNull(mx)) {
661             throw new CompanyMxException();
662         }
663         else if (!Validator.isDomain(mx)) {
664             throw new CompanyMxException();
665         }
666     }
667 
668 }