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