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