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