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