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.BooleanClauseOccur;
37  import com.liferay.portal.kernel.search.BooleanQuery;
38  import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
39  import com.liferay.portal.kernel.search.Field;
40  import com.liferay.portal.kernel.search.Hits;
41  import com.liferay.portal.kernel.search.SearchEngineUtil;
42  import com.liferay.portal.kernel.util.StringPool;
43  import com.liferay.portal.kernel.util.Validator;
44  import com.liferay.portal.model.Account;
45  import com.liferay.portal.model.Company;
46  import com.liferay.portal.model.CompanyConstants;
47  import com.liferay.portal.model.Contact;
48  import com.liferay.portal.model.ContactConstants;
49  import com.liferay.portal.model.Group;
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.User;
54  import com.liferay.portal.model.impl.CountryImpl;
55  import com.liferay.portal.model.impl.GroupImpl;
56  import com.liferay.portal.model.impl.ListTypeImpl;
57  import com.liferay.portal.model.impl.RegionImpl;
58  import com.liferay.portal.model.impl.RoleImpl;
59  import com.liferay.portal.search.lucene.LuceneUtil;
60  import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
61  import com.liferay.portal.util.PortalInstances;
62  import com.liferay.portal.util.PrefsPropsUtil;
63  import com.liferay.portal.util.PropsKeys;
64  import com.liferay.portal.util.PropsValues;
65  import com.liferay.util.Encryptor;
66  import com.liferay.util.EncryptorException;
67  import com.liferay.util.Normalizer;
68  
69  import java.io.File;
70  import java.io.IOException;
71  
72  import java.util.Calendar;
73  import java.util.Date;
74  import java.util.List;
75  import java.util.Locale;
76  
77  import javax.portlet.PortletException;
78  import javax.portlet.PortletPreferences;
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 = 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 = null;
513 
514         try {
515             account = accountPersistence.findByPrimaryKey(
516                 company.getAccountId());
517         }
518         catch (NoSuchAccountException nsae) {
519             long accountId = counterLocalService.increment();
520 
521             account = accountPersistence.create(accountId);
522 
523             account.setCreateDate(now);
524             account.setCompanyId(companyId);
525             account.setUserId(0);
526             account.setUserName(StringPool.BLANK);
527 
528             company.setAccountId(accountId);
529 
530             companyPersistence.update(company, false);
531         }
532 
533         account.setModifiedDate(now);
534         account.setName(name);
535         account.setLegalName(legalName);
536         account.setLegalId(legalId);
537         account.setLegalType(legalType);
538         account.setSicCode(sicCode);
539         account.setTickerSymbol(tickerSymbol);
540         account.setIndustry(industry);
541         account.setType(type);
542         account.setSize(size);
543 
544         accountPersistence.update(account, false);
545 
546         return company;
547     }
548 
549     public void updateDisplay(
550             long companyId, String languageId, String timeZoneId)
551         throws PortalException, SystemException {
552 
553         User user = userLocalService.getDefaultUser(companyId);
554 
555         user.setLanguageId(languageId);
556         user.setTimeZoneId(timeZoneId);
557 
558         userPersistence.update(user, false);
559     }
560 
561     public void updateLogo(long companyId, File file)
562         throws PortalException, SystemException {
563 
564         Company company = companyPersistence.findByPrimaryKey(companyId);
565 
566         long logoId = company.getLogoId();
567 
568         if (logoId <= 0) {
569             logoId = counterLocalService.increment();
570 
571             company.setLogoId(logoId);
572         }
573 
574         imageLocalService.updateImage(logoId, file);
575     }
576 
577     public void updateSecurity(
578             long companyId, String authType, boolean autoLogin,
579             boolean sendPassword, boolean strangers, boolean strangersWithMx,
580             boolean strangersVerify, boolean communityLogo)
581         throws PortalException, SystemException {
582 
583         PortletPreferences prefs = PrefsPropsUtil.getPreferences(companyId);
584 
585         try {
586             prefs.setValue(PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
587             prefs.setValue(
588                 PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
589                 String.valueOf(autoLogin));
590             prefs.setValue(
591                 PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
592                 String.valueOf(sendPassword));
593             prefs.setValue(
594                 PropsKeys.COMPANY_SECURITY_STRANGERS,
595                 String.valueOf(strangers));
596             prefs.setValue(
597                 PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
598                 String.valueOf(strangersWithMx));
599             prefs.setValue(
600                 PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
601                 String.valueOf(strangersVerify));
602             prefs.setValue(
603                 PropsKeys.COMPANY_SECURITY_COMMUNITY_LOGO,
604                 String.valueOf(communityLogo));
605 
606             prefs.store();
607         }
608         catch (IOException ioe) {
609             throw new SystemException(ioe);
610         }
611         catch (PortletException pe) {
612             throw new SystemException(pe);
613         }
614     }
615 
616     protected String getVirtualHost(String virtualHost) {
617         return Normalizer.normalizeToAscii(virtualHost.trim().toLowerCase());
618     }
619 
620     protected void validate(String name) throws PortalException {
621         if (Validator.isNull(name)) {
622             throw new AccountNameException();
623         }
624     }
625 
626     protected void validate(String webId, String virtualHost, String mx)
627         throws PortalException, SystemException {
628 
629         if (Validator.isNull(virtualHost)) {
630             throw new CompanyVirtualHostException();
631         }
632         else if (virtualHost.equals(PortalInstances.DEFAULT_VIRTUAL_HOST) &&
633                  !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
634 
635             throw new CompanyVirtualHostException();
636         }
637         else if (!Validator.isDomain(virtualHost)) {
638             throw new CompanyVirtualHostException();
639         }
640         else {
641             try {
642                 Company virtualHostCompany = getCompanyByVirtualHost(
643                     virtualHost);
644 
645                 if ((virtualHostCompany != null) &&
646                     (!virtualHostCompany.getWebId().equals(webId))) {
647 
648                     throw new CompanyVirtualHostException();
649                 }
650             }
651             catch (NoSuchCompanyException nsce) {
652             }
653 
654             try {
655                 layoutSetLocalService.getLayoutSet(virtualHost);
656 
657                 throw new CompanyVirtualHostException();
658             }
659             catch (NoSuchLayoutSetException nslse) {
660             }
661         }
662 
663         if (Validator.isNull(mx)) {
664             throw new CompanyMxException();
665         }
666         else if (!Validator.isDomain(mx)) {
667             throw new CompanyMxException();
668         }
669     }
670 
671 }