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