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