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