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