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