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