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