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