001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.impl;
016    
017    import com.liferay.portal.kernel.bean.BeanReference;
018    import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
019    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
020    import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
021    import com.liferay.portal.kernel.dao.orm.Property;
022    import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
023    import com.liferay.portal.kernel.exception.AccountNameException;
024    import com.liferay.portal.kernel.exception.CompanyMxException;
025    import com.liferay.portal.kernel.exception.CompanyVirtualHostException;
026    import com.liferay.portal.kernel.exception.CompanyWebIdException;
027    import com.liferay.portal.kernel.exception.LocaleException;
028    import com.liferay.portal.kernel.exception.NoSuchVirtualHostException;
029    import com.liferay.portal.kernel.exception.PortalException;
030    import com.liferay.portal.kernel.exception.RequiredCompanyException;
031    import com.liferay.portal.kernel.exception.SystemException;
032    import com.liferay.portal.kernel.instance.lifecycle.PortalInstanceLifecycleManager;
033    import com.liferay.portal.kernel.language.LanguageUtil;
034    import com.liferay.portal.kernel.log.Log;
035    import com.liferay.portal.kernel.log.LogFactoryUtil;
036    import com.liferay.portal.kernel.model.Account;
037    import com.liferay.portal.kernel.model.Company;
038    import com.liferay.portal.kernel.model.CompanyConstants;
039    import com.liferay.portal.kernel.model.Contact;
040    import com.liferay.portal.kernel.model.ContactConstants;
041    import com.liferay.portal.kernel.model.Group;
042    import com.liferay.portal.kernel.model.GroupConstants;
043    import com.liferay.portal.kernel.model.LayoutPrototype;
044    import com.liferay.portal.kernel.model.LayoutSetPrototype;
045    import com.liferay.portal.kernel.model.Organization;
046    import com.liferay.portal.kernel.model.OrganizationConstants;
047    import com.liferay.portal.kernel.model.PasswordPolicy;
048    import com.liferay.portal.kernel.model.PortalPreferences;
049    import com.liferay.portal.kernel.model.Portlet;
050    import com.liferay.portal.kernel.model.Role;
051    import com.liferay.portal.kernel.model.RoleConstants;
052    import com.liferay.portal.kernel.model.User;
053    import com.liferay.portal.kernel.model.UserGroup;
054    import com.liferay.portal.kernel.model.VirtualHost;
055    import com.liferay.portal.kernel.search.Hits;
056    import com.liferay.portal.kernel.search.SearchContext;
057    import com.liferay.portal.kernel.search.SearchEngineHelperUtil;
058    import com.liferay.portal.kernel.search.SearchException;
059    import com.liferay.portal.kernel.search.facet.AssetEntriesFacet;
060    import com.liferay.portal.kernel.search.facet.Facet;
061    import com.liferay.portal.kernel.search.facet.ScopeFacet;
062    import com.liferay.portal.kernel.search.facet.faceted.searcher.FacetedSearcher;
063    import com.liferay.portal.kernel.search.facet.faceted.searcher.FacetedSearcherManager;
064    import com.liferay.portal.kernel.search.facet.faceted.searcher.FacetedSearcherManagerUtil;
065    import com.liferay.portal.kernel.security.auth.CompanyThreadLocal;
066    import com.liferay.portal.kernel.service.persistence.CompanyProvider;
067    import com.liferay.portal.kernel.service.persistence.CompanyProviderWrapper;
068    import com.liferay.portal.kernel.transaction.Isolation;
069    import com.liferay.portal.kernel.transaction.TransactionCommitCallbackUtil;
070    import com.liferay.portal.kernel.transaction.Transactional;
071    import com.liferay.portal.kernel.util.ArrayUtil;
072    import com.liferay.portal.kernel.util.LocaleThreadLocal;
073    import com.liferay.portal.kernel.util.LocaleUtil;
074    import com.liferay.portal.kernel.util.Portal;
075    import com.liferay.portal.kernel.util.PortalUtil;
076    import com.liferay.portal.kernel.util.PortletKeys;
077    import com.liferay.portal.kernel.util.PropsKeys;
078    import com.liferay.portal.kernel.util.StringPool;
079    import com.liferay.portal.kernel.util.StringUtil;
080    import com.liferay.portal.kernel.util.TimeZoneUtil;
081    import com.liferay.portal.kernel.util.UnicodeProperties;
082    import com.liferay.portal.kernel.util.Validator;
083    import com.liferay.portal.kernel.workflow.WorkflowConstants;
084    import com.liferay.portal.liveusers.LiveUsers;
085    import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
086    import com.liferay.portal.util.PortalInstances;
087    import com.liferay.portal.util.PrefsPropsUtil;
088    import com.liferay.portal.util.PropsUtil;
089    import com.liferay.portal.util.PropsValues;
090    import com.liferay.registry.Registry;
091    import com.liferay.registry.RegistryUtil;
092    import com.liferay.registry.ServiceReference;
093    import com.liferay.registry.ServiceTracker;
094    import com.liferay.registry.ServiceTrackerCustomizer;
095    import com.liferay.util.Encryptor;
096    import com.liferay.util.EncryptorException;
097    
098    import java.io.File;
099    import java.io.IOException;
100    import java.io.InputStream;
101    
102    import java.util.ArrayList;
103    import java.util.Arrays;
104    import java.util.Date;
105    import java.util.HashSet;
106    import java.util.List;
107    import java.util.Locale;
108    import java.util.Map;
109    import java.util.Objects;
110    import java.util.Set;
111    import java.util.TimeZone;
112    import java.util.concurrent.Callable;
113    
114    import javax.portlet.PortletException;
115    import javax.portlet.PortletPreferences;
116    
117    /**
118     * Provides the local service for adding, checking, and updating companies. Each
119     * company refers to a separate portal instance.
120     *
121     * @author Brian Wing Shun Chan
122     * @author Julio Camarero
123     */
124    public class CompanyLocalServiceImpl extends CompanyLocalServiceBaseImpl {
125    
126            public CompanyLocalServiceImpl() {
127                    Registry registry = RegistryUtil.getRegistry();
128    
129                    _serviceTracker = registry.trackServices(
130                            PortalInstanceLifecycleManager.class,
131                            new PortalInstanceLifecycleManagerServiceTrackerCustomizer());
132    
133                    _serviceTracker.open();
134            }
135    
136            /**
137             * Adds a company.
138             *
139             * @param  webId the the company's web domain
140             * @param  virtualHostname the company's virtual host name
141             * @param  mx the company's mail domain
142             * @param  system whether the company is the very first company (i.e., the
143             *         super company)
144             * @param  maxUsers the max number of company users (optionally
145             *         <code>0</code>)
146             * @param  active whether the company is active
147             * @return the company
148             */
149            @Override
150            public Company addCompany(
151                            String webId, String virtualHostname, String mx, boolean system,
152                            int maxUsers, boolean active)
153                    throws PortalException {
154    
155                    // Company
156    
157                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
158    
159                    if (Validator.isNull(webId) ||
160                            webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID) ||
161                            (companyPersistence.fetchByWebId(webId) != null)) {
162    
163                            throw new CompanyWebIdException();
164                    }
165    
166                    validateVirtualHost(webId, virtualHostname);
167                    validateMx(mx);
168    
169                    Company company = checkCompany(webId, mx);
170    
171                    company = companyPersistence.fetchByPrimaryKey(company.getCompanyId());
172    
173                    company.setMx(mx);
174                    company.setSystem(system);
175                    company.setMaxUsers(maxUsers);
176                    company.setActive(active);
177    
178                    companyPersistence.update(company);
179    
180                    // Virtual host
181    
182                    company = updateVirtualHostname(
183                            company.getCompanyId(), virtualHostname);
184    
185                    return company;
186            }
187    
188            /**
189             * Returns the company with the web domain.
190             *
191             * The method sets mail domain to the web domain to the default name set in
192             * portal.properties
193             *
194             * @param  webId the company's web domain
195             * @return the company with the web domain
196             */
197            @Override
198            public Company checkCompany(String webId) throws PortalException {
199                    String mx = webId;
200    
201                    return companyLocalService.checkCompany(webId, mx);
202            }
203    
204            /**
205             * Returns the company with the web domain and mail domain. If no such
206             * company exits, the method will create a new company.
207             *
208             * The method goes through a series of checks to ensure that the company
209             * contains default users, groups, etc.
210             *
211             * @param  webId the company's web domain
212             * @param  mx the company's mail domain
213             * @return the company with the web domain and mail domain
214             */
215            @Override
216            @Transactional(
217                    isolation = Isolation.PORTAL,
218                    rollbackFor = {PortalException.class, SystemException.class}
219            )
220            public Company checkCompany(String webId, String mx)
221                    throws PortalException {
222    
223                    // Company
224    
225                    Date now = new Date();
226    
227                    Company company = companyPersistence.fetchByWebId(webId);
228    
229                    if (company == null) {
230                            long companyId = counterLocalService.increment();
231    
232                            company = companyPersistence.create(companyId);
233    
234                            try {
235                                    company.setKey(Encryptor.serializeKey(Encryptor.generateKey()));
236                            }
237                            catch (EncryptorException ee) {
238                                    throw new SystemException(ee);
239                            }
240    
241                            company.setWebId(webId);
242                            company.setMx(mx);
243                            company.setActive(true);
244    
245                            company = companyPersistence.update(company);
246    
247                            // Account
248    
249                            String name = webId;
250    
251                            if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
252                                    name = PropsValues.COMPANY_DEFAULT_NAME;
253                            }
254    
255                            String legalName = null;
256                            String legalId = null;
257                            String legalType = null;
258                            String sicCode = null;
259                            String tickerSymbol = null;
260                            String industry = null;
261                            String type = null;
262                            String size = null;
263    
264                            updateAccount(
265                                    company, name, legalName, legalId, legalType, sicCode,
266                                    tickerSymbol, industry, type, size);
267    
268                            // Virtual host
269    
270                            if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
271                                    company = updateVirtualHostname(
272                                            companyId, _DEFAULT_VIRTUAL_HOST);
273                            }
274    
275                            // Demo settings
276    
277                            if (webId.equals("liferay.net")) {
278                                    company = companyPersistence.findByWebId(webId);
279    
280                                    updateVirtualHostname(companyId, "demo.liferay.net");
281    
282                                    updateSecurity(
283                                            companyId, CompanyConstants.AUTH_TYPE_EA, true, true, true,
284                                            true, false, true);
285    
286                                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
287                                            companyId);
288    
289                                    try {
290                                            preferences.setValue(
291                                                    PropsKeys.ADMIN_EMAIL_FROM_NAME, "Liferay Demo");
292                                            preferences.setValue(
293                                                    PropsKeys.ADMIN_EMAIL_FROM_ADDRESS, "test@liferay.net");
294    
295                                            preferences.store();
296                                    }
297                                    catch (IOException ioe) {
298                                            throw new SystemException(ioe);
299                                    }
300                                    catch (PortletException pe) {
301                                            throw new SystemException(pe);
302                                    }
303                            }
304                    }
305    
306                    preregisterCompany(company.getCompanyId());
307    
308                    CompanyProvider currentCompanyProvider =
309                            _companyProviderWrapper.getCompanyProvider();
310    
311                    Locale localeThreadLocalDefaultLocale =
312                            LocaleThreadLocal.getDefaultLocale();
313    
314                    try {
315                            Locale companyDefaultLocale = LocaleUtil.fromLanguageId(
316                                    PropsValues.COMPANY_DEFAULT_LOCALE);
317    
318                            LocaleThreadLocal.setDefaultLocale(companyDefaultLocale);
319    
320                            final long companyId = company.getCompanyId();
321    
322                            _companyProviderWrapper.setCompanyProvider(
323                                    new CustomCompanyProvider(companyId));
324    
325                            // Key
326    
327                            checkCompanyKey(companyId);
328    
329                            // Default user
330    
331                            User defaultUser = userPersistence.fetchByC_DU(companyId, true);
332    
333                            if (defaultUser != null) {
334                                    if (!defaultUser.isAgreedToTermsOfUse()) {
335                                            defaultUser.setAgreedToTermsOfUse(true);
336    
337                                            userPersistence.update(defaultUser);
338                                    }
339                            }
340                            else {
341                                    long userId = counterLocalService.increment();
342    
343                                    defaultUser = userPersistence.create(userId);
344    
345                                    defaultUser.setCompanyId(companyId);
346                                    defaultUser.setDefaultUser(true);
347                                    defaultUser.setContactId(counterLocalService.increment());
348                                    defaultUser.setPassword("password");
349                                    defaultUser.setScreenName(
350                                            String.valueOf(defaultUser.getUserId()));
351                                    defaultUser.setEmailAddress("default@" + company.getMx());
352                                    defaultUser.setLanguageId(
353                                            LocaleUtil.toLanguageId(companyDefaultLocale));
354    
355                                    if (Validator.isNotNull(
356                                                    PropsValues.COMPANY_DEFAULT_TIME_ZONE)) {
357    
358                                            defaultUser.setTimeZoneId(
359                                                    PropsValues.COMPANY_DEFAULT_TIME_ZONE);
360                                    }
361                                    else {
362                                            TimeZone timeZone = TimeZoneUtil.getDefault();
363    
364                                            defaultUser.setTimeZoneId(timeZone.getID());
365                                    }
366    
367                                    String greeting = LanguageUtil.format(
368                                            defaultUser.getLocale(), "welcome", null, false);
369    
370                                    defaultUser.setGreeting(greeting + StringPool.EXCLAMATION);
371                                    defaultUser.setLoginDate(now);
372                                    defaultUser.setFailedLoginAttempts(0);
373                                    defaultUser.setAgreedToTermsOfUse(true);
374                                    defaultUser.setStatus(WorkflowConstants.STATUS_APPROVED);
375    
376                                    userPersistence.update(defaultUser);
377    
378                                    // Contact
379    
380                                    Contact defaultContact = contactPersistence.create(
381                                            defaultUser.getContactId());
382    
383                                    defaultContact.setCompanyId(defaultUser.getCompanyId());
384                                    defaultContact.setUserId(defaultUser.getUserId());
385                                    defaultContact.setUserName(StringPool.BLANK);
386                                    defaultContact.setClassName(User.class.getName());
387                                    defaultContact.setClassPK(defaultUser.getUserId());
388                                    defaultContact.setAccountId(company.getAccountId());
389                                    defaultContact.setParentContactId(
390                                            ContactConstants.DEFAULT_PARENT_CONTACT_ID);
391                                    defaultContact.setEmailAddress(defaultUser.getEmailAddress());
392                                    defaultContact.setFirstName(StringPool.BLANK);
393                                    defaultContact.setMiddleName(StringPool.BLANK);
394                                    defaultContact.setLastName(StringPool.BLANK);
395                                    defaultContact.setMale(true);
396                                    defaultContact.setBirthday(now);
397    
398                                    contactPersistence.update(defaultContact);
399                            }
400    
401                            // System roles
402    
403                            roleLocalService.checkSystemRoles(companyId);
404    
405                            // System groups
406    
407                            groupLocalService.checkSystemGroups(companyId);
408    
409                            // Company group
410    
411                            groupLocalService.checkCompanyGroup(companyId);
412    
413                            // Default password policy
414    
415                            passwordPolicyLocalService.checkDefaultPasswordPolicy(companyId);
416    
417                            // Default user must have the Guest role
418    
419                            Role guestRole = roleLocalService.getRole(
420                                    companyId, RoleConstants.GUEST);
421    
422                            roleLocalService.setUserRoles(
423                                    defaultUser.getUserId(), new long[] {guestRole.getRoleId()});
424    
425                            // Default admin
426    
427                            if (userPersistence.countByCompanyId(companyId) == 1) {
428                                    String emailAddress =
429                                            PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + "@" + mx;
430    
431                                    userLocalService.addDefaultAdminUser(
432                                            companyId, PropsValues.DEFAULT_ADMIN_SCREEN_NAME,
433                                            emailAddress, defaultUser.getLocale(),
434                                            PropsValues.DEFAULT_ADMIN_FIRST_NAME,
435                                            PropsValues.DEFAULT_ADMIN_MIDDLE_NAME,
436                                            PropsValues.DEFAULT_ADMIN_LAST_NAME);
437                            }
438    
439                            // Portlets
440    
441                            portletLocalService.checkPortlets(companyId);
442    
443                            final Company finalCompany = company;
444    
445                            TransactionCommitCallbackUtil.registerCallback(
446                                    new Callable<Void>() {
447    
448                                            @Override
449                                            public Void call() throws Exception {
450                                                    registerCompany(finalCompany);
451    
452                                                    return null;
453                                            }
454    
455                                    });
456                    }
457                    finally {
458                            _companyProviderWrapper.setCompanyProvider(currentCompanyProvider);
459    
460                            LocaleThreadLocal.setDefaultLocale(localeThreadLocalDefaultLocale);
461                    }
462    
463                    return company;
464            }
465    
466            /**
467             * Checks if the company has an encryption key. It will create a key if one
468             * does not exist.
469             *
470             * @param companyId the primary key of the company
471             */
472            @Override
473            public void checkCompanyKey(long companyId) throws PortalException {
474                    Company company = companyPersistence.findByPrimaryKey(companyId);
475    
476                    if (company.getKeyObj() != null) {
477                            return;
478                    }
479    
480                    try {
481                            company.setKey(Encryptor.serializeKey(Encryptor.generateKey()));
482                    }
483                    catch (EncryptorException ee) {
484                            throw new SystemException(ee);
485                    }
486    
487                    companyPersistence.update(company);
488            }
489    
490            @Override
491            public Company deleteCompany(Company company) throws PortalException {
492                    return deleteCompany(company.getCompanyId());
493            }
494    
495            @Override
496            public Company deleteCompany(long companyId) throws PortalException {
497                    if (companyId == PortalInstances.getDefaultCompanyId()) {
498                            throw new RequiredCompanyException();
499                    }
500    
501                    Long currentCompanyId = CompanyThreadLocal.getCompanyId();
502                    boolean deleteInProcess = CompanyThreadLocal.isDeleteInProcess();
503    
504                    try {
505                            CompanyThreadLocal.setCompanyId(companyId);
506                            CompanyThreadLocal.setDeleteInProcess(true);
507    
508                            return doDeleteCompany(companyId);
509                    }
510                    finally {
511                            CompanyThreadLocal.setCompanyId(currentCompanyId);
512                            CompanyThreadLocal.setDeleteInProcess(deleteInProcess);
513                    }
514            }
515    
516            /**
517             * Deletes the company's logo.
518             *
519             * @param  companyId the primary key of the company
520             * @return the deleted logo's company
521             */
522            @Override
523            public Company deleteLogo(long companyId) throws PortalException {
524                    Company company = companyPersistence.findByPrimaryKey(companyId);
525    
526                    PortalUtil.updateImageId(company, false, null, "logoId", 0, 0, 0);
527    
528                    return company;
529            }
530    
531            /**
532             * Returns the company with the primary key.
533             *
534             * @param  companyId the primary key of the company
535             * @return the company with the primary key, <code>null</code> if a company
536             *         with the primary key could not be found
537             */
538            @Override
539            public Company fetchCompanyById(long companyId) {
540                    return companyPersistence.fetchByPrimaryKey(companyId);
541            }
542    
543            /**
544             * Returns the company with the virtual host name.
545             *
546             * @param  virtualHostname the virtual host name
547             * @return the company with the virtual host name, <code>null</code> if a
548             *         company with the virtual host could not be found
549             */
550            @Override
551            public Company fetchCompanyByVirtualHost(String virtualHostname) {
552                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
553    
554                    VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
555                            virtualHostname);
556    
557                    if ((virtualHost == null) || (virtualHost.getLayoutSetId() != 0)) {
558                            return null;
559                    }
560    
561                    return companyPersistence.fetchByPrimaryKey(virtualHost.getCompanyId());
562            }
563    
564            /**
565             * Returns all the companies.
566             *
567             * @return the companies
568             */
569            @Override
570            public List<Company> getCompanies() {
571                    return companyPersistence.findAll();
572            }
573    
574            /**
575             * Returns all the companies used by WSRP.
576             *
577             * @param  system whether the company is the very first company (i.e., the
578             *         super company)
579             * @return the companies used by WSRP
580             */
581            @Override
582            public List<Company> getCompanies(boolean system) {
583                    return companyPersistence.findBySystem(system);
584            }
585    
586            @Override
587            public List<Company> getCompanies(boolean system, int start, int end) {
588                    return companyPersistence.findBySystem(system, start, end);
589            }
590    
591            /**
592             * Returns the number of companies used by WSRP.
593             *
594             * @param  system whether the company is the very first company (i.e., the
595             *         super company)
596             * @return the number of companies used by WSRP
597             */
598            @Override
599            public int getCompaniesCount(boolean system) {
600                    return companyPersistence.countBySystem(system);
601            }
602    
603            /**
604             * Returns the company with the primary key.
605             *
606             * @param  companyId the primary key of the company
607             * @return the company with the primary key
608             */
609            @Override
610            public Company getCompanyById(long companyId) throws PortalException {
611                    return companyPersistence.findByPrimaryKey(companyId);
612            }
613    
614            /**
615             * Returns the company with the logo.
616             *
617             * @param  logoId the ID of the company's logo
618             * @return the company with the logo
619             */
620            @Override
621            public Company getCompanyByLogoId(long logoId) throws PortalException {
622                    return companyPersistence.findByLogoId(logoId);
623            }
624    
625            /**
626             * Returns the company with the mail domain.
627             *
628             * @param  mx the company's mail domain
629             * @return the company with the mail domain
630             */
631            @Override
632            public Company getCompanyByMx(String mx) throws PortalException {
633                    return companyPersistence.findByMx(mx);
634            }
635    
636            /**
637             * Returns the company with the virtual host name.
638             *
639             * @param  virtualHostname the company's virtual host name
640             * @return the company with the virtual host name
641             */
642            @Override
643            public Company getCompanyByVirtualHost(String virtualHostname)
644                    throws PortalException {
645    
646                    try {
647                            virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
648    
649                            VirtualHost virtualHost = virtualHostPersistence.findByHostname(
650                                    virtualHostname);
651    
652                            if (virtualHost.getLayoutSetId() != 0) {
653                                    throw new CompanyVirtualHostException(
654                                            "Virtual host is associated with layout set " +
655                                                    virtualHost.getLayoutSetId());
656                            }
657    
658                            return companyPersistence.findByPrimaryKey(
659                                    virtualHost.getCompanyId());
660                    }
661                    catch (NoSuchVirtualHostException nsvhe) {
662                            throw new CompanyVirtualHostException(nsvhe);
663                    }
664            }
665    
666            /**
667             * Returns the company with the web domain.
668             *
669             * @param  webId the company's web domain
670             * @return the company with the web domain
671             */
672            @Override
673            public Company getCompanyByWebId(String webId) throws PortalException {
674                    return companyPersistence.findByWebId(webId);
675            }
676    
677            /**
678             * Returns the user's company.
679             *
680             * @param  userId the primary key of the user
681             * @return Returns the first company if there is only one company or the
682             *         user's company if there are more than one company; <code>0</code>
683             *         otherwise
684             * @throws Exception if a user with the primary key could not be found
685             */
686            @Override
687            public long getCompanyIdByUserId(long userId) throws Exception {
688                    long[] companyIds = PortalInstances.getCompanyIds();
689    
690                    long companyId = 0;
691    
692                    if (companyIds.length == 1) {
693                            companyId = companyIds[0];
694                    }
695                    else if (companyIds.length > 1) {
696                            try {
697                                    User user = userPersistence.findByPrimaryKey(userId);
698    
699                                    companyId = user.getCompanyId();
700                            }
701                            catch (Exception e) {
702                                    if (_log.isWarnEnabled()) {
703                                            _log.warn(
704                                                    "Unable to get the company id for user " + userId, e);
705                                    }
706                            }
707                    }
708    
709                    return companyId;
710            }
711    
712            /**
713             * Removes the values that match the keys of the company's preferences.
714             *
715             * This method is called by {@link
716             * com.liferay.portlet.portalsettings.action.EditLDAPServerAction} remotely
717             * through {@link com.liferay.portal.kernel.service.CompanyService}.
718             *
719             * @param companyId the primary key of the company
720             * @param keys the company's preferences keys to be remove
721             */
722            @Override
723            public void removePreferences(long companyId, String[] keys) {
724                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
725                            companyId);
726    
727                    try {
728                            for (String key : keys) {
729                                    preferences.reset(key);
730                            }
731    
732                            preferences.store();
733                    }
734                    catch (Exception e) {
735                            throw new SystemException(e);
736                    }
737            }
738    
739            /**
740             * Returns an ordered range of all assets that match the keywords in the
741             * company.
742             *
743             * The method is called in {@link
744             * com.liferay.portal.search.PortalOpenSearchImpl} which is not longer used
745             * by the Search portlet.
746             *
747             * @param  companyId the primary key of the company
748             * @param  userId the primary key of the user
749             * @param  keywords the keywords (space separated),which may occur in assets
750             *         in the company (optionally <code>null</code>)
751             * @param  start the lower bound of the range of assets to return
752             * @param  end the upper bound of the range of assets to return (not
753             *         inclusive)
754             * @return the matching assets in the company
755             */
756            @Override
757            public Hits search(
758                    long companyId, long userId, String keywords, int start, int end) {
759    
760                    return search(companyId, userId, null, 0, null, keywords, start, end);
761            }
762    
763            /**
764             * Returns an ordered range of all assets that match the keywords in the
765             * portlet within the company.
766             *
767             * @param  companyId the primary key of the company
768             * @param  userId the primary key of the user
769             * @param  portletId the primary key of the portlet (optionally
770             *         <code>null</code>)
771             * @param  groupId the primary key of the group (optionally <code>0</code>)
772             * @param  type the mime type of assets to return(optionally
773             *         <code>null</code>)
774             * @param  keywords the keywords (space separated), which may occur in any
775             *         assets in the portlet (optionally <code>null</code>)
776             * @param  start the lower bound of the range of assets to return
777             * @param  end the upper bound of the range of assets to return (not
778             *         inclusive)
779             * @return the matching assets in the portlet within the company
780             */
781            @Override
782            public Hits search(
783                    long companyId, long userId, String portletId, long groupId,
784                    String type, String keywords, int start, int end) {
785    
786                    FacetedSearcherManager facetedSearcherManager =
787                            FacetedSearcherManagerUtil.getFacetedSearcherManager();
788    
789                    FacetedSearcher facetedSearcher =
790                            facetedSearcherManager.createFacetedSearcher();
791    
792                    SearchContext searchContext = createSearchContext(
793                            companyId, userId, portletId, groupId, keywords, start, end);
794    
795                    addAssetEntriesFacet(searchContext);
796    
797                    addScopeFacet(searchContext);
798    
799                    try {
800                            return facetedSearcher.search(searchContext);
801                    }
802                    catch (SearchException se) {
803                            throw new SystemException(se);
804                    }
805            }
806    
807            /**
808             * Updates the company.
809             *
810             * @param  companyId the primary key of the company
811             * @param  virtualHostname the company's virtual host name
812             * @param  mx the company's mail domain
813             * @param  maxUsers the max number of company users (optionally
814             *         <code>0</code>)
815             * @param  active whether the company is active
816             * @return the company with the primary key
817             */
818            @Override
819            public Company updateCompany(
820                            long companyId, String virtualHostname, String mx, int maxUsers,
821                            boolean active)
822                    throws PortalException {
823    
824                    // Company
825    
826                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
827    
828                    if (!active) {
829                            if (companyId == PortalInstances.getDefaultCompanyId()) {
830                                    active = true;
831                            }
832                    }
833    
834                    Company company = companyPersistence.findByPrimaryKey(companyId);
835    
836                    validateVirtualHost(company.getWebId(), virtualHostname);
837    
838                    if (PropsValues.MAIL_MX_UPDATE) {
839                            validateMx(mx);
840    
841                            company.setMx(mx);
842                    }
843    
844                    company.setMaxUsers(maxUsers);
845                    company.setActive(active);
846    
847                    companyPersistence.update(company);
848    
849                    // Virtual host
850    
851                    company = updateVirtualHostname(companyId, virtualHostname);
852    
853                    return company;
854            }
855    
856            /**
857             * Update the company with additional account information.
858             *
859             * @param  companyId the primary key of the company
860             * @param  virtualHostname the company's virtual host name
861             * @param  mx the company's mail domain
862             * @param  homeURL the company's home URL (optionally <code>null</code>)
863             * @param  logo whether to update the company's logo
864             * @param  logoBytes the new logo image data
865             * @param  name the company's account name(optionally <code>null</code>)
866             * @param  legalName the company's account legal name (optionally
867             *         <code>null</code>)
868             * @param  legalId the company's account legal ID (optionally
869             *         <code>null</code>)
870             * @param  legalType the company's account legal type (optionally
871             *         <code>null</code>)
872             * @param  sicCode the company's account SIC code (optionally
873             *         <code>null</code>)
874             * @param  tickerSymbol the company's account ticker symbol (optionally
875             *         <code>null</code>)
876             * @param  industry the company's account industry (optionally
877             *         <code>null</code>)
878             * @param  type the company's account type (optionally <code>null</code>)
879             * @param  size the company's account size (optionally <code>null</code>)
880             * @return the company with the primary key
881             */
882            @Override
883            public Company updateCompany(
884                            long companyId, String virtualHostname, String mx, String homeURL,
885                            boolean logo, byte[] logoBytes, String name, String legalName,
886                            String legalId, String legalType, String sicCode,
887                            String tickerSymbol, String industry, String type, String size)
888                    throws PortalException {
889    
890                    // Company
891    
892                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
893    
894                    Company company = companyPersistence.findByPrimaryKey(companyId);
895    
896                    validateVirtualHost(company.getWebId(), virtualHostname);
897    
898                    if (PropsValues.MAIL_MX_UPDATE) {
899                            validateMx(mx);
900                    }
901    
902                    validateName(companyId, name);
903    
904                    if (PropsValues.MAIL_MX_UPDATE) {
905                            company.setMx(mx);
906                    }
907    
908                    company.setHomeURL(homeURL);
909    
910                    PortalUtil.updateImageId(company, logo, logoBytes, "logoId", 0, 0, 0);
911    
912                    companyPersistence.update(company);
913    
914                    // Account
915    
916                    updateAccount(
917                            company, name, legalName, legalId, legalType, sicCode, tickerSymbol,
918                            industry, type, size);
919    
920                    // Virtual host
921    
922                    company = updateVirtualHostname(companyId, virtualHostname);
923    
924                    return company;
925            }
926    
927            /**
928             * Update the company with additional account information.
929             *
930             * @param      companyId the primary key of the company
931             * @param      virtualHostname the company's virtual host name
932             * @param      mx the company's mail domain
933             * @param      homeURL the company's home URL (optionally <code>null</code>)
934             * @param      name the company's account name(optionally <code>null</code>)
935             * @param      legalName the company's account legal name (optionally
936             *             <code>null</code>)
937             * @param      legalId the company's account legal ID (optionally
938             *             <code>null</code>)
939             * @param      legalType the company's account legal type (optionally
940             *             <code>null</code>)
941             * @param      sicCode the company's account SIC code (optionally
942             *             <code>null</code>)
943             * @param      tickerSymbol the company's account ticker symbol (optionally
944             *             <code>null</code>)
945             * @param      industry the company's account industry (optionally
946             *             <code>null</code>)
947             * @param      type the company's account type (optionally
948             *             <code>null</code>)
949             * @param      size the company's account size (optionally
950             *             <code>null</code>)
951             * @return     the company with the primary key
952             * @deprecated As of 7.0.0, replaced by {@link #updateCompany(long, String,
953             *             String, String, boolean, byte[], String, String, String,
954             *             String, String, String, String, String, String)}
955             */
956            @Deprecated
957            @Override
958            public Company updateCompany(
959                            long companyId, String virtualHostname, String mx, String homeURL,
960                            String name, String legalName, String legalId, String legalType,
961                            String sicCode, String tickerSymbol, String industry, String type,
962                            String size)
963                    throws PortalException {
964    
965                    return updateCompany(
966                            companyId, virtualHostname, mx, homeURL, true, null, name,
967                            legalName, legalId, legalType, sicCode, tickerSymbol, industry,
968                            type, size);
969            }
970    
971            /**
972             * Update the company's display.
973             *
974             * @param companyId the primary key of the company
975             * @param languageId the ID of the company's default user's language
976             * @param timeZoneId the ID of the company's default user's time zone
977             */
978            @Override
979            public void updateDisplay(
980                            long companyId, String languageId, String timeZoneId)
981                    throws PortalException {
982    
983                    User user = userLocalService.getDefaultUser(companyId);
984    
985                    user.setLanguageId(languageId);
986                    user.setTimeZoneId(timeZoneId);
987    
988                    userPersistence.update(user);
989            }
990    
991            /**
992             * Updates the company's logo.
993             *
994             * @param  companyId the primary key of the company
995             * @param  bytes the bytes of the company's logo image
996             * @return the company with the primary key
997             */
998            @Override
999            public Company updateLogo(long companyId, byte[] bytes)
1000                    throws PortalException {
1001    
1002                    Company company = checkLogo(companyId);
1003    
1004                    imageLocalService.updateImage(company.getLogoId(), bytes);
1005    
1006                    return company;
1007            }
1008    
1009            /**
1010             * Updates the company's logo.
1011             *
1012             * @param  companyId the primary key of the company
1013             * @param  file the file of the company's logo image
1014             * @return the company with the primary key
1015             */
1016            @Override
1017            public Company updateLogo(long companyId, File file)
1018                    throws PortalException {
1019    
1020                    Company company = checkLogo(companyId);
1021    
1022                    imageLocalService.updateImage(company.getLogoId(), file);
1023    
1024                    return company;
1025            }
1026    
1027            /**
1028             * Update the company's logo.
1029             *
1030             * @param  companyId the primary key of the company
1031             * @param  is the input stream of the company's logo image
1032             * @return the company with the primary key
1033             */
1034            @Override
1035            public Company updateLogo(long companyId, InputStream is)
1036                    throws PortalException {
1037    
1038                    Company company = checkLogo(companyId);
1039    
1040                    imageLocalService.updateImage(company.getLogoId(), is);
1041    
1042                    return company;
1043            }
1044    
1045            /**
1046             * Updates the company's preferences. The company's default properties are
1047             * found in portal.properties.
1048             *
1049             * @param companyId the primary key of the company
1050             * @param properties the company's properties. See {@link UnicodeProperties}
1051             */
1052            @Override
1053            public void updatePreferences(long companyId, UnicodeProperties properties)
1054                    throws PortalException {
1055    
1056                    PortletPreferences portletPreferences = PrefsPropsUtil.getPreferences(
1057                            companyId);
1058    
1059                    try {
1060                            String newLanguageIds = properties.getProperty(PropsKeys.LOCALES);
1061    
1062                            if (Validator.isNotNull(newLanguageIds)) {
1063                                    String oldLanguageIds = portletPreferences.getValue(
1064                                            PropsKeys.LOCALES, StringPool.BLANK);
1065    
1066                                    if (!Objects.equals(oldLanguageIds, newLanguageIds)) {
1067                                            validateLanguageIds(newLanguageIds);
1068    
1069                                            LanguageUtil.resetAvailableLocales(companyId);
1070    
1071                                            // Invalidate cache of all layout set prototypes that belong
1072                                            // to this company. See LPS-36403.
1073    
1074                                            Date now = new Date();
1075    
1076                                            for (LayoutSetPrototype layoutSetPrototype :
1077                                                            layoutSetPrototypeLocalService.
1078                                                                    getLayoutSetPrototypes(companyId)) {
1079    
1080                                                    layoutSetPrototype.setModifiedDate(now);
1081    
1082                                                    layoutSetPrototypeLocalService.updateLayoutSetPrototype(
1083                                                            layoutSetPrototype);
1084                                            }
1085                                    }
1086                            }
1087    
1088                            List<String> resetKeys = new ArrayList<>();
1089    
1090                            for (Map.Entry<String, String> entry : properties.entrySet()) {
1091                                    String key = entry.getKey();
1092                                    String value = entry.getValue();
1093    
1094                                    if (value.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
1095                                            continue;
1096                                    }
1097    
1098                                    String propsUtilValue = PropsUtil.get(key);
1099    
1100                                    if (!value.equals(propsUtilValue)) {
1101                                            portletPreferences.setValue(key, value);
1102                                    }
1103                                    else {
1104                                            String portletPreferencesValue =
1105                                                    portletPreferences.getValue(key, null);
1106    
1107                                            if (portletPreferencesValue != null) {
1108                                                    resetKeys.add(key);
1109                                            }
1110                                    }
1111                            }
1112    
1113                            for (String key : resetKeys) {
1114                                    portletPreferences.reset(key);
1115                            }
1116    
1117                            portletPreferences.store();
1118                    }
1119                    catch (LocaleException le) {
1120                            throw le;
1121                    }
1122                    catch (Exception e) {
1123                            throw new SystemException(e);
1124                    }
1125    
1126                    _clearCompanyCache(companyId);
1127            }
1128    
1129            /**
1130             * Updates the company's security properties.
1131             *
1132             * @param companyId the primary key of the company
1133             * @param authType the company's method of authenticating users
1134             * @param autoLogin whether to allow users to select the "remember me"
1135             *        feature
1136             * @param sendPassword whether to allow users to ask the company to send
1137             *        their password
1138             * @param strangers whether to allow strangers to create accounts register
1139             *        themselves in the company
1140             * @param strangersWithMx whether to allow strangers to create accounts with
1141             *        email addresses that match the company mail suffix
1142             * @param strangersVerify whether to require strangers who create accounts
1143             *        to be verified via email
1144             * @param siteLogo whether to allow site administrators to use their own
1145             *        logo instead of the enterprise logo
1146             */
1147            @Override
1148            public void updateSecurity(
1149                    long companyId, String authType, boolean autoLogin,
1150                    boolean sendPassword, boolean strangers, boolean strangersWithMx,
1151                    boolean strangersVerify, boolean siteLogo) {
1152    
1153                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1154                            companyId);
1155    
1156                    try {
1157                            preferences.setValue(
1158                                    PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
1159                            preferences.setValue(
1160                                    PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
1161                                    String.valueOf(autoLogin));
1162                            preferences.setValue(
1163                                    PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
1164                                    String.valueOf(sendPassword));
1165                            preferences.setValue(
1166                                    PropsKeys.COMPANY_SECURITY_STRANGERS,
1167                                    String.valueOf(strangers));
1168                            preferences.setValue(
1169                                    PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
1170                                    String.valueOf(strangersWithMx));
1171                            preferences.setValue(
1172                                    PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
1173                                    String.valueOf(strangersVerify));
1174                            preferences.setValue(
1175                                    PropsKeys.COMPANY_SECURITY_SITE_LOGO, String.valueOf(siteLogo));
1176    
1177                            preferences.store();
1178                    }
1179                    catch (IOException | PortletException e) {
1180                            throw new SystemException(e);
1181                    }
1182    
1183                    _clearCompanyCache(companyId);
1184            }
1185    
1186            protected void addAssetEntriesFacet(SearchContext searchContext) {
1187                    Facet assetEntriesFacet = new AssetEntriesFacet(searchContext);
1188    
1189                    assetEntriesFacet.setStatic(true);
1190    
1191                    searchContext.addFacet(assetEntriesFacet);
1192            }
1193    
1194            protected void addScopeFacet(SearchContext searchContext) {
1195                    Facet scopeFacet = new ScopeFacet(searchContext);
1196    
1197                    scopeFacet.setStatic(true);
1198    
1199                    searchContext.addFacet(scopeFacet);
1200            }
1201    
1202            protected Company checkLogo(long companyId) throws PortalException {
1203                    Company company = companyPersistence.findByPrimaryKey(companyId);
1204    
1205                    long logoId = company.getLogoId();
1206    
1207                    if (logoId <= 0) {
1208                            logoId = counterLocalService.increment();
1209    
1210                            company.setLogoId(logoId);
1211    
1212                            company = companyPersistence.update(company);
1213                    }
1214    
1215                    return company;
1216            }
1217    
1218            protected SearchContext createSearchContext(
1219                    long companyId, long userId, String portletId, long groupId,
1220                    String keywords, int start, int end) {
1221    
1222                    SearchContext searchContext = new SearchContext();
1223    
1224                    searchContext.setCompanyId(companyId);
1225                    searchContext.setEnd(end);
1226                    searchContext.setEntryClassNames(
1227                            SearchEngineHelperUtil.getEntryClassNames());
1228    
1229                    if (groupId > 0) {
1230                            searchContext.setGroupIds(new long[] {groupId});
1231                    }
1232    
1233                    searchContext.setKeywords(keywords);
1234    
1235                    if (Validator.isNotNull(portletId)) {
1236                            searchContext.setPortletIds(new String[] {portletId});
1237                    }
1238    
1239                    searchContext.setStart(start);
1240                    searchContext.setUserId(userId);
1241    
1242                    return searchContext;
1243            }
1244    
1245            protected Company doDeleteCompany(final long companyId)
1246                    throws PortalException {
1247    
1248                    // Company
1249    
1250                    final Company company = companyPersistence.remove(companyId);
1251    
1252                    // Account
1253    
1254                    accountLocalService.deleteAccount(company.getAccountId());
1255    
1256                    // Organizations
1257    
1258                    DeleteOrganizationActionableDynamicQuery
1259                            deleteOrganizationActionableDynamicQuery =
1260                                    new DeleteOrganizationActionableDynamicQuery();
1261    
1262                    deleteOrganizationActionableDynamicQuery.setCompanyId(companyId);
1263    
1264                    deleteOrganizationActionableDynamicQuery.performActions();
1265    
1266                    // Groups
1267    
1268                    DeleteGroupActionableDynamicQuery deleteGroupActionableDynamicQuery =
1269                            new DeleteGroupActionableDynamicQuery();
1270    
1271                    deleteGroupActionableDynamicQuery.setCompanyId(companyId);
1272    
1273                    deleteGroupActionableDynamicQuery.performActions();
1274    
1275                    String[] systemGroups = PortalUtil.getSystemGroups();
1276    
1277                    for (String groupName : systemGroups) {
1278                            Group group = groupLocalService.getGroup(companyId, groupName);
1279    
1280                            deleteGroupActionableDynamicQuery.deleteGroup(group);
1281                    }
1282    
1283                    Group companyGroup = groupLocalService.getCompanyGroup(companyId);
1284    
1285                    deleteGroupActionableDynamicQuery.deleteGroup(companyGroup);
1286    
1287                    // Layout prototype
1288    
1289                    ActionableDynamicQuery layoutPrototypeActionableDynamicQuery =
1290                            layoutPrototypeLocalService.getActionableDynamicQuery();
1291    
1292                    layoutPrototypeActionableDynamicQuery.setCompanyId(companyId);
1293                    layoutPrototypeActionableDynamicQuery.setPerformActionMethod(
1294                            new ActionableDynamicQuery.PerformActionMethod<LayoutPrototype>() {
1295    
1296                                    @Override
1297                                    public void performAction(LayoutPrototype layoutPrototype)
1298                                            throws PortalException {
1299    
1300                                            layoutPrototypeLocalService.deleteLayoutPrototype(
1301                                                    layoutPrototype);
1302                                    }
1303    
1304                            });
1305    
1306                    layoutPrototypeActionableDynamicQuery.performActions();
1307    
1308                    // Layout set prototype
1309    
1310                    ActionableDynamicQuery layoutSetPrototypeActionableDynamicQuery =
1311                            layoutSetPrototypeLocalService.getActionableDynamicQuery();
1312    
1313                    layoutSetPrototypeActionableDynamicQuery.setCompanyId(companyId);
1314                    layoutSetPrototypeActionableDynamicQuery.setPerformActionMethod(
1315                            new ActionableDynamicQuery.
1316                                    PerformActionMethod<LayoutSetPrototype>() {
1317    
1318                                    @Override
1319                                    public void performAction(LayoutSetPrototype layoutSetPrototype)
1320                                            throws PortalException {
1321    
1322                                            layoutSetPrototypeLocalService.deleteLayoutSetPrototype(
1323                                                    layoutSetPrototype);
1324                                    }
1325    
1326                            });
1327    
1328                    layoutSetPrototypeActionableDynamicQuery.performActions();
1329    
1330                    // Roles
1331    
1332                    ActionableDynamicQuery roleActionableDynamicQuery =
1333                            roleLocalService.getActionableDynamicQuery();
1334    
1335                    roleActionableDynamicQuery.setCompanyId(companyId);
1336                    roleActionableDynamicQuery.setPerformActionMethod(
1337                            new ActionableDynamicQuery.PerformActionMethod<Role>() {
1338    
1339                                    @Override
1340                                    public void performAction(Role role) throws PortalException {
1341                                            roleLocalService.deleteRole(role);
1342                                    }
1343    
1344                            });
1345    
1346                    roleActionableDynamicQuery.performActions();
1347    
1348                    // User groups
1349    
1350                    DeleteUserGroupActionableDynamicQuery
1351                            deleteUserGroupActionableDynamicQuery =
1352                                    new DeleteUserGroupActionableDynamicQuery(
1353                                            company.getCompanyId());
1354    
1355                    deleteUserGroupActionableDynamicQuery.performActions();
1356    
1357                    // Password policy
1358    
1359                    passwordPolicyLocalService.deleteNondefaultPasswordPolicies(companyId);
1360    
1361                    PasswordPolicy defaultPasswordPolicy =
1362                            passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
1363    
1364                    if (defaultPasswordPolicy != null) {
1365                            passwordPolicyLocalService.deletePasswordPolicy(
1366                                    defaultPasswordPolicy);
1367                    }
1368    
1369                    // Portal preferences
1370    
1371                    PortalPreferences portalPreferences =
1372                            portalPreferencesPersistence.findByO_O(
1373                                    companyId, PortletKeys.PREFS_OWNER_TYPE_COMPANY);
1374    
1375                    portalPreferencesLocalService.deletePortalPreferences(
1376                            portalPreferences);
1377    
1378                    // Portlets
1379    
1380                    List<Portlet> portlets = portletPersistence.findByCompanyId(companyId);
1381    
1382                    for (Portlet portlet : portlets) {
1383                            portletLocalService.deletePortlet(portlet.getId());
1384                    }
1385    
1386                    portletLocalService.removeCompanyPortletsPool(companyId);
1387    
1388                    // Users
1389    
1390                    ActionableDynamicQuery userActionableDynamicQuery =
1391                            userLocalService.getActionableDynamicQuery();
1392    
1393                    userActionableDynamicQuery.setCompanyId(companyId);
1394                    userActionableDynamicQuery.setPerformActionMethod(
1395                            new ActionableDynamicQuery.PerformActionMethod<User>() {
1396    
1397                                    @Override
1398                                    public void performAction(User user) throws PortalException {
1399                                            if (!user.isDefaultUser()) {
1400                                                    userLocalService.deleteUser(user.getUserId());
1401                                            }
1402                                    }
1403    
1404                            });
1405    
1406                    userActionableDynamicQuery.performActions();
1407    
1408                    User defaultUser = userLocalService.getDefaultUser(companyId);
1409    
1410                    userLocalService.deleteUser(defaultUser);
1411    
1412                    // Virtual host
1413    
1414                    VirtualHost companyVirtualHost =
1415                            virtualHostLocalService.fetchVirtualHost(companyId, 0);
1416    
1417                    virtualHostLocalService.deleteVirtualHost(companyVirtualHost);
1418    
1419                    // Portal instance
1420    
1421                    Callable<Void> callable = new Callable<Void>() {
1422    
1423                            @Override
1424                            public Void call() throws Exception {
1425                                    PortalInstances.removeCompany(companyId);
1426    
1427                                    unregisterCompany(company);
1428    
1429                                    return null;
1430                            }
1431    
1432                    };
1433    
1434                    TransactionCommitCallbackUtil.registerCallback(callable);
1435    
1436                    return company;
1437            }
1438    
1439            protected void preregisterCompany(long companyId) {
1440                    PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1441                            _serviceTracker.getService();
1442    
1443                    if (portalInstanceLifecycleManager != null) {
1444                            portalInstanceLifecycleManager.preregisterCompany(companyId);
1445                    }
1446            }
1447    
1448            protected void registerCompany(Company company) {
1449                    PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1450                            _serviceTracker.getService();
1451    
1452                    if (portalInstanceLifecycleManager != null) {
1453                            portalInstanceLifecycleManager.registerCompany(company);
1454                    }
1455                    else {
1456                            synchronized (_pendingCompanies) {
1457                                    _pendingCompanies.add(company);
1458                            }
1459                    }
1460            }
1461    
1462            protected void unregisterCompany(Company company) {
1463                    PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1464                            _serviceTracker.getService();
1465    
1466                    if (portalInstanceLifecycleManager != null) {
1467                            portalInstanceLifecycleManager.unregisterCompany(company);
1468                    }
1469            }
1470    
1471            protected void updateAccount(
1472                    Company company, String name, String legalName, String legalId,
1473                    String legalType, String sicCode, String tickerSymbol, String industry,
1474                    String type, String size) {
1475    
1476                    Account account = accountPersistence.fetchByPrimaryKey(
1477                            company.getAccountId());
1478    
1479                    if (account == null) {
1480                            long accountId = counterLocalService.increment();
1481    
1482                            account = accountPersistence.create(accountId);
1483    
1484                            account.setCompanyId(company.getCompanyId());
1485                            account.setUserId(0);
1486                            account.setUserName(StringPool.BLANK);
1487    
1488                            company.setAccountId(accountId);
1489    
1490                            companyPersistence.update(company);
1491                    }
1492    
1493                    account.setName(name);
1494                    account.setLegalName(legalName);
1495                    account.setLegalId(legalId);
1496                    account.setLegalType(legalType);
1497                    account.setSicCode(sicCode);
1498                    account.setTickerSymbol(tickerSymbol);
1499                    account.setIndustry(industry);
1500                    account.setType(type);
1501                    account.setSize(size);
1502    
1503                    accountPersistence.update(account);
1504            }
1505    
1506            protected Company updateVirtualHostname(
1507                            long companyId, String virtualHostname)
1508                    throws CompanyVirtualHostException {
1509    
1510                    if (Validator.isNotNull(virtualHostname)) {
1511                            VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
1512                                    virtualHostname);
1513    
1514                            if (virtualHost == null) {
1515                                    virtualHostLocalService.updateVirtualHost(
1516                                            companyId, 0, virtualHostname);
1517                            }
1518                            else {
1519                                    if ((virtualHost.getCompanyId() != companyId) ||
1520                                            (virtualHost.getLayoutSetId() != 0)) {
1521    
1522                                            throw new CompanyVirtualHostException();
1523                                    }
1524                            }
1525                    }
1526                    else {
1527                            VirtualHost virtualHost = virtualHostPersistence.fetchByC_L(
1528                                    companyId, 0);
1529    
1530                            if (virtualHost != null) {
1531                                    virtualHostPersistence.remove(virtualHost);
1532                            }
1533                    }
1534    
1535                    return companyPersistence.fetchByPrimaryKey(companyId);
1536            }
1537    
1538            protected void validateLanguageIds(String languageIds)
1539                    throws PortalException {
1540    
1541                    String[] languageIdsArray = StringUtil.split(
1542                            languageIds, StringPool.COMMA);
1543    
1544                    for (String languageId : languageIdsArray) {
1545                            if (!ArrayUtil.contains(PropsValues.LOCALES, languageId)) {
1546                                    LocaleException le = new LocaleException(
1547                                            LocaleException.TYPE_DISPLAY_SETTINGS);
1548    
1549                                    le.setSourceAvailableLocales(
1550                                            Arrays.asList(
1551                                                    LocaleUtil.fromLanguageIds(PropsValues.LOCALES)));
1552                                    le.setTargetAvailableLocales(
1553                                            Arrays.asList(
1554                                                    LocaleUtil.fromLanguageIds(languageIdsArray)));
1555    
1556                                    throw le;
1557                            }
1558                    }
1559            }
1560    
1561            protected void validateMx(String mx) throws PortalException {
1562                    if (Validator.isNull(mx) || !Validator.isDomain(mx)) {
1563                            throw new CompanyMxException();
1564                    }
1565            }
1566    
1567            protected void validateName(long companyId, String name)
1568                    throws PortalException {
1569    
1570                    Group group = groupLocalService.fetchGroup(companyId, name);
1571    
1572                    if ((group != null) || Validator.isNull(name)) {
1573                            throw new AccountNameException();
1574                    }
1575            }
1576    
1577            protected void validateVirtualHost(String webId, String virtualHostname)
1578                    throws PortalException {
1579    
1580                    if (Validator.isNull(virtualHostname)) {
1581                            throw new CompanyVirtualHostException();
1582                    }
1583                    else if (virtualHostname.equals(_DEFAULT_VIRTUAL_HOST) &&
1584                                     !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
1585    
1586                            throw new CompanyVirtualHostException();
1587                    }
1588                    else if (!Validator.isDomain(virtualHostname)) {
1589                            throw new CompanyVirtualHostException();
1590                    }
1591                    else {
1592                            try {
1593                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1594                                            virtualHostname);
1595    
1596                                    long companyId = virtualHost.getCompanyId();
1597    
1598                                    Company virtualHostnameCompany =
1599                                            companyPersistence.findByPrimaryKey(companyId);
1600    
1601                                    if (!webId.equals(virtualHostnameCompany.getWebId())) {
1602                                            throw new CompanyVirtualHostException();
1603                                    }
1604                            }
1605                            catch (NoSuchVirtualHostException nsvhe) {
1606                            }
1607                    }
1608            }
1609    
1610            protected class DeleteGroupActionableDynamicQuery {
1611    
1612                    protected DeleteGroupActionableDynamicQuery() {
1613                            _actionableDynamicQuery =
1614                                    groupLocalService.getActionableDynamicQuery();
1615    
1616                            _actionableDynamicQuery.setAddCriteriaMethod(
1617                                    new ActionableDynamicQuery.AddCriteriaMethod() {
1618    
1619                                            @Override
1620                                            public void addCriteria(DynamicQuery dynamicQuery) {
1621                                                    Property parentGroupIdProperty =
1622                                                            PropertyFactoryUtil.forName("parentGroupId");
1623    
1624                                                    dynamicQuery.add(
1625                                                            parentGroupIdProperty.eq(_parentGroupId));
1626    
1627                                                    Property siteProperty = PropertyFactoryUtil.forName(
1628                                                            "site");
1629    
1630                                                    dynamicQuery.add(siteProperty.eq(Boolean.TRUE));
1631                                            }
1632    
1633                                    });
1634                            _actionableDynamicQuery.setPerformActionMethod(
1635                                    new ActionableDynamicQuery.PerformActionMethod<Group>() {
1636    
1637                                            @Override
1638                                            public void performAction(Group group)
1639                                                    throws PortalException {
1640    
1641                                                    if (!PortalUtil.isSystemGroup(group.getGroupKey()) &&
1642                                                            !group.isCompany()) {
1643    
1644                                                            deleteGroup(group);
1645                                                    }
1646                                            }
1647    
1648                                    });
1649                    }
1650    
1651                    protected void deleteGroup(Group group) throws PortalException {
1652                            DeleteGroupActionableDynamicQuery
1653                                    deleteGroupActionableDynamicQuery =
1654                                            new DeleteGroupActionableDynamicQuery();
1655    
1656                            deleteGroupActionableDynamicQuery.setCompanyId(
1657                                    group.getCompanyId());
1658                            deleteGroupActionableDynamicQuery.setParentGroupId(
1659                                    group.getGroupId());
1660    
1661                            deleteGroupActionableDynamicQuery.performActions();
1662    
1663                            groupLocalService.deleteGroup(group);
1664    
1665                            LiveUsers.deleteGroup(group.getCompanyId(), group.getGroupId());
1666                    }
1667    
1668                    protected void performActions() throws PortalException {
1669                            _actionableDynamicQuery.performActions();
1670                    }
1671    
1672                    protected void setCompanyId(long companyId) {
1673                            _actionableDynamicQuery.setCompanyId(companyId);
1674                    }
1675    
1676                    protected void setParentGroupId(long parentGroupId) {
1677                            _parentGroupId = parentGroupId;
1678                    }
1679    
1680                    private ActionableDynamicQuery _actionableDynamicQuery;
1681                    private long _parentGroupId = GroupConstants.DEFAULT_PARENT_GROUP_ID;
1682    
1683            }
1684    
1685            protected class DeleteOrganizationActionableDynamicQuery {
1686    
1687                    public void setParentOrganizationId(long parentOrganizationId) {
1688                            _parentOrganizationId = parentOrganizationId;
1689                    }
1690    
1691                    protected DeleteOrganizationActionableDynamicQuery() {
1692                            _actionableDynamicQuery =
1693                                    organizationLocalService.getActionableDynamicQuery();
1694    
1695                            _actionableDynamicQuery.setAddCriteriaMethod(
1696                                    new ActionableDynamicQuery.AddCriteriaMethod() {
1697    
1698                                            @Override
1699                                            public void addCriteria(DynamicQuery dynamicQuery) {
1700                                                    Property property = PropertyFactoryUtil.forName(
1701                                                            "parentOrganizationId");
1702    
1703                                                    dynamicQuery.add(property.eq(_parentOrganizationId));
1704                                            }
1705    
1706                                    });
1707                            _actionableDynamicQuery.setPerformActionMethod(
1708                                    new ActionableDynamicQuery.PerformActionMethod<Organization>() {
1709    
1710                                            @Override
1711                                            public void performAction(Organization organization)
1712                                                    throws PortalException {
1713    
1714                                                    deleteOrganization(organization);
1715                                            }
1716    
1717                                    });
1718                    }
1719    
1720                    protected void deleteOrganization(Organization organization)
1721                            throws PortalException {
1722    
1723                            DeleteOrganizationActionableDynamicQuery
1724                                    deleteOrganizationActionableDynamicQuery =
1725                                            new DeleteOrganizationActionableDynamicQuery();
1726    
1727                            deleteOrganizationActionableDynamicQuery.setCompanyId(
1728                                    organization.getCompanyId());
1729                            deleteOrganizationActionableDynamicQuery.setParentOrganizationId(
1730                                    organization.getOrganizationId());
1731    
1732                            deleteOrganizationActionableDynamicQuery.performActions();
1733    
1734                            organizationLocalService.deleteOrganization(organization);
1735                    }
1736    
1737                    protected void performActions() throws PortalException {
1738                            _actionableDynamicQuery.performActions();
1739                    }
1740    
1741                    protected void setCompanyId(long companyId) {
1742                            _actionableDynamicQuery.setCompanyId(companyId);
1743                    }
1744    
1745                    private ActionableDynamicQuery _actionableDynamicQuery;
1746                    private long _parentOrganizationId =
1747                            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;
1748    
1749            }
1750    
1751            protected class DeleteUserGroupActionableDynamicQuery {
1752    
1753                    protected DeleteUserGroupActionableDynamicQuery(long companyId) {
1754                            _actionableDynamicQuery =
1755                                    userGroupLocalService.getActionableDynamicQuery();
1756    
1757                            _actionableDynamicQuery.setCompanyId(companyId);
1758                            _actionableDynamicQuery.setPerformActionMethod(
1759                                    new ActionableDynamicQuery.PerformActionMethod<UserGroup>() {
1760    
1761                                            @Override
1762                                            public void performAction(UserGroup userGroup)
1763                                                    throws PortalException {
1764    
1765                                                    userGroupLocalService.deleteUserGroup(userGroup);
1766                                            }
1767    
1768                                    });
1769                    }
1770    
1771                    protected void performActions() throws PortalException {
1772                            _actionableDynamicQuery.performActions();
1773                    }
1774    
1775                    private ActionableDynamicQuery _actionableDynamicQuery;
1776    
1777            }
1778    
1779            private void _clearCompanyCache(long companyId) {
1780                    final Company company = companyPersistence.fetchByPrimaryKey(companyId);
1781    
1782                    if (company != null) {
1783                            TransactionCommitCallbackUtil.registerCallback(
1784                                    new Callable<Void>() {
1785    
1786                                            @Override
1787                                            public Void call() throws Exception {
1788                                                    EntityCacheUtil.removeResult(
1789                                                            company.isEntityCacheEnabled(), company.getClass(),
1790                                                            company.getPrimaryKeyObj());
1791    
1792                                                    return null;
1793                                            }
1794    
1795                                    });
1796    
1797                            companyPersistence.clearCache(company);
1798                    }
1799            }
1800    
1801            private static final String _DEFAULT_VIRTUAL_HOST = "localhost";
1802    
1803            private static final Log _log = LogFactoryUtil.getLog(
1804                    CompanyLocalServiceImpl.class);
1805    
1806            @BeanReference(type = CompanyProviderWrapper.class)
1807            private CompanyProviderWrapper _companyProviderWrapper;
1808    
1809            private final Set<Company> _pendingCompanies = new HashSet<>();
1810            private final ServiceTracker
1811                    <PortalInstanceLifecycleManager, PortalInstanceLifecycleManager>
1812                            _serviceTracker;
1813    
1814            private static class CustomCompanyProvider implements CompanyProvider {
1815    
1816                    public CustomCompanyProvider(long companyId) {
1817                            _companyId = companyId;
1818                    }
1819    
1820                    @Override
1821                    public long getCompanyId() {
1822                            return _companyId;
1823                    }
1824    
1825                    @Override
1826                    public String getCompanyIdName() {
1827                            return "companyId";
1828                    }
1829    
1830                    private final long _companyId;
1831    
1832            }
1833    
1834            private class PortalInstanceLifecycleManagerServiceTrackerCustomizer
1835                    implements ServiceTrackerCustomizer
1836                            <PortalInstanceLifecycleManager, PortalInstanceLifecycleManager> {
1837    
1838                    @Override
1839                    public PortalInstanceLifecycleManager addingService(
1840                            ServiceReference<PortalInstanceLifecycleManager> serviceReference) {
1841    
1842                            Registry registry = RegistryUtil.getRegistry();
1843    
1844                            PortalInstanceLifecycleManager portalInstanceLifecycleManager =
1845                                    registry.getService(serviceReference);
1846    
1847                            synchronized (_pendingCompanies) {
1848                                    for (Company company : _pendingCompanies) {
1849                                            portalInstanceLifecycleManager.registerCompany(company);
1850                                    }
1851    
1852                                    _pendingCompanies.clear();
1853                            }
1854    
1855                            return portalInstanceLifecycleManager;
1856                    }
1857    
1858                    @Override
1859                    public void modifiedService(
1860                            ServiceReference<PortalInstanceLifecycleManager> serviceReference,
1861                            PortalInstanceLifecycleManager portalInstanceLifecycleManager) {
1862    
1863                            removedService(serviceReference, portalInstanceLifecycleManager);
1864    
1865                            addingService(serviceReference);
1866                    }
1867    
1868                    @Override
1869                    public void removedService(
1870                            ServiceReference<PortalInstanceLifecycleManager> serviceReference,
1871                            PortalInstanceLifecycleManager portalInstanceLifecycleManager) {
1872                    }
1873    
1874            }
1875    
1876    }