001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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 (company.getKeyObj() != null) {
450                            return;
451                    }
452    
453                    try {
454                            company.setKey(Base64.objectToString(Encryptor.generateKey()));
455                    }
456                    catch (EncryptorException ee) {
457                            throw new SystemException(ee);
458                    }
459    
460                    companyPersistence.update(company);
461            }
462    
463            @Override
464            public Company deleteCompany(Company company)
465                    throws PortalException, SystemException {
466    
467                    return deleteCompany(company.getCompanyId());
468            }
469    
470            @Override
471            public Company deleteCompany(long companyId)
472                    throws PortalException, SystemException {
473    
474                    if (companyId == PortalInstances.getDefaultCompanyId()) {
475                            throw new RequiredCompanyException();
476                    }
477    
478                    Long currentCompanyId = CompanyThreadLocal.getCompanyId();
479                    boolean deleteInProcess = CompanyThreadLocal.isDeleteInProcess();
480    
481                    try {
482                            CompanyThreadLocal.setCompanyId(companyId);
483                            CompanyThreadLocal.setDeleteInProcess(true);
484    
485                            return doDeleteCompany(companyId);
486                    }
487                    finally {
488                            CompanyThreadLocal.setCompanyId(currentCompanyId);
489                            CompanyThreadLocal.setDeleteInProcess(deleteInProcess);
490                    }
491            }
492    
493            /**
494             * Deletes the company's logo.
495             *
496             * @param  companyId the primary key of the company
497             * @throws PortalException if the company with the primary key could not be
498             *         found or if the company's logo could not be found
499             * @throws SystemException if a system exception occurred
500             */
501            @Override
502            public void deleteLogo(long companyId)
503                    throws PortalException, SystemException {
504    
505                    Company company = companyPersistence.findByPrimaryKey(companyId);
506    
507                    long logoId = company.getLogoId();
508    
509                    if (logoId > 0) {
510                            company.setLogoId(0);
511    
512                            companyPersistence.update(company);
513    
514                            imageLocalService.deleteImage(logoId);
515                    }
516            }
517    
518            /**
519             * Returns the company with the primary key.
520             *
521             * @param  companyId the primary key of the company
522             * @return the company with the primary key, <code>null</code> if a company
523             *         with the primary key could not be found
524             * @throws SystemException if a system exception occurred
525             */
526            @Override
527            public Company fetchCompanyById(long companyId) throws SystemException {
528                    return companyPersistence.fetchByPrimaryKey(companyId);
529            }
530    
531            /**
532             * Returns the company with the virtual host name.
533             *
534             * @param  virtualHostname the virtual host name
535             * @return the company with the virtual host name, <code>null</code> if a
536             *         company with the virtual host could not be found
537             * @throws SystemException if a system exception occurred
538             */
539            @Override
540            public Company fetchCompanyByVirtualHost(String virtualHostname)
541                    throws SystemException {
542    
543                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
544    
545                    VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
546                            virtualHostname);
547    
548                    if ((virtualHost == null) || (virtualHost.getLayoutSetId() != 0)) {
549                            return null;
550                    }
551    
552                    return companyPersistence.fetchByPrimaryKey(virtualHost.getCompanyId());
553            }
554    
555            /**
556             * Returns all the companies.
557             *
558             * @return the companies
559             * @throws SystemException if a system exception occurred
560             */
561            @Override
562            public List<Company> getCompanies() throws SystemException {
563                    return companyPersistence.findAll();
564            }
565    
566            /**
567             * Returns all the companies used by WSRP.
568             *
569             * @param  system whether the company is the very first company (i.e., the
570             *         super company)
571             * @return the companies used by WSRP
572             * @throws SystemException if a system exception occurred
573             */
574            @Override
575            public List<Company> getCompanies(boolean system) throws SystemException {
576                    return companyPersistence.findBySystem(system);
577            }
578    
579            /**
580             * Returns the number of companies used by WSRP.
581             *
582             * @param  system whether the company is the very first company (i.e., the
583             *         super company)
584             * @return the number of companies used by WSRP
585             * @throws SystemException if a system exception occurred
586             */
587            @Override
588            public int getCompaniesCount(boolean system) throws SystemException {
589                    return companyPersistence.countBySystem(system);
590            }
591    
592            /**
593             * Returns the company with the primary key.
594             *
595             * @param  companyId the primary key of the company
596             * @return the company with the primary key
597             * @throws PortalException if a company with the primary key could not be
598             *         found
599             * @throws SystemException if a system exception occurred
600             */
601            @Override
602            public Company getCompanyById(long companyId)
603                    throws PortalException, SystemException {
604    
605                    return companyPersistence.findByPrimaryKey(companyId);
606            }
607    
608            /**
609             * Returns the company with the logo.
610             *
611             * @param  logoId the ID of the company's logo
612             * @return the company with the logo
613             * @throws PortalException if the company with the logo could not be found
614             * @throws SystemException if a system exception occurred
615             */
616            @Override
617            public Company getCompanyByLogoId(long logoId)
618                    throws PortalException, SystemException {
619    
620                    return companyPersistence.findByLogoId(logoId);
621            }
622    
623            /**
624             * Returns the company with the mail domain.
625             *
626             * @param  mx the company's mail domain
627             * @return the company with the mail domain
628             * @throws PortalException if the company with the mail domain could not be
629             *         found
630             * @throws SystemException if a system exception occurred
631             */
632            @Override
633            public Company getCompanyByMx(String mx)
634                    throws PortalException, SystemException {
635    
636                    return companyPersistence.findByMx(mx);
637            }
638    
639            /**
640             * Returns the company with the virtual host name.
641             *
642             * @param  virtualHostname the company's virtual host name
643             * @return the company with the virtual host name
644             * @throws PortalException if the company with the virtual host name could
645             *         not be found or if the virtual host was not associated with a
646             *         company
647             * @throws SystemException if a system exception occurred
648             */
649            @Override
650            public Company getCompanyByVirtualHost(String virtualHostname)
651                    throws PortalException, SystemException {
652    
653                    try {
654                            virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
655    
656                            VirtualHost virtualHost = virtualHostPersistence.findByHostname(
657                                    virtualHostname);
658    
659                            if (virtualHost.getLayoutSetId() != 0) {
660                                    throw new CompanyVirtualHostException(
661                                            "Virtual host is associated with layout set " +
662                                                    virtualHost.getLayoutSetId());
663                            }
664    
665                            return companyPersistence.findByPrimaryKey(
666                                    virtualHost.getCompanyId());
667                    }
668                    catch (NoSuchVirtualHostException nsvhe) {
669                            throw new CompanyVirtualHostException(nsvhe);
670                    }
671            }
672    
673            /**
674             * Returns the company with the web domain.
675             *
676             * @param  webId the company's web domain
677             * @return the company with the web domain
678             * @throws PortalException if the company with the web domain could not be
679             *         found
680             * @throws SystemException if a system exception occurred
681             */
682            @Override
683            public Company getCompanyByWebId(String webId)
684                    throws PortalException, SystemException {
685    
686                    return companyPersistence.findByWebId(webId);
687            }
688    
689            /**
690             * Returns the user's company.
691             *
692             * @param  userId the primary key of the user
693             * @return Returns the first company if there is only one company or the
694             *         user's company if there are more than one company; <code>0</code>
695             *         otherwise
696             * @throws Exception if a user with the primary key could not be found
697             */
698            @Override
699            public long getCompanyIdByUserId(long userId) throws Exception {
700                    long[] companyIds = PortalInstances.getCompanyIds();
701    
702                    long companyId = 0;
703    
704                    if (companyIds.length == 1) {
705                            companyId = companyIds[0];
706                    }
707                    else if (companyIds.length > 1) {
708                            try {
709                                    User user = userPersistence.findByPrimaryKey(userId);
710    
711                                    companyId = user.getCompanyId();
712                            }
713                            catch (Exception e) {
714                                    if (_log.isWarnEnabled()) {
715                                            _log.warn(
716                                                    "Unable to get the company id for user " + userId, e);
717                                    }
718                            }
719                    }
720    
721                    return companyId;
722            }
723    
724            /**
725             * Removes the values that match the keys of the company's preferences.
726             *
727             * This method is called by {@link
728             * com.liferay.portlet.portalsettings.action.EditLDAPServerAction} remotely
729             * through {@link com.liferay.portal.service.CompanyService}.
730             *
731             * @param  companyId the primary key of the company
732             * @param  keys the company's preferences keys to be remove
733             * @throws SystemException if a system exception occurred
734             */
735            @Override
736            public void removePreferences(long companyId, String[] keys)
737                    throws SystemException {
738    
739                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
740                            companyId);
741    
742                    try {
743                            for (String key : keys) {
744                                    preferences.reset(key);
745                            }
746    
747                            preferences.store();
748                    }
749                    catch (Exception e) {
750                            throw new SystemException(e);
751                    }
752            }
753    
754            /**
755             * Returns an ordered range of all assets that match the keywords in the
756             * company.
757             *
758             * The method is called in {@link
759             * com.liferay.portal.search.PortalOpenSearchImpl} which is not longer used
760             * by the Search portlet.
761             *
762             * @param  companyId the primary key of the company
763             * @param  userId the primary key of the user
764             * @param  keywords the keywords (space separated),which may occur in assets
765             *         in the company (optionally <code>null</code>)
766             * @param  start the lower bound of the range of assets to return
767             * @param  end the upper bound of the range of assets to return (not
768             *         inclusive)
769             * @return the matching assets in the company
770             * @throws SystemException if a system exception occurred
771             */
772            @Override
773            public Hits search(
774                            long companyId, long userId, String keywords, int start, int end)
775                    throws SystemException {
776    
777                    return search(companyId, userId, null, 0, null, keywords, start, end);
778            }
779    
780            /**
781             * Returns an ordered range of all assets that match the keywords in the
782             * portlet within the company.
783             *
784             * @param  companyId the primary key of the company
785             * @param  userId the primary key of the user
786             * @param  portletId the primary key of the portlet (optionally
787             *         <code>null</code>)
788             * @param  groupId the primary key of the group (optionally <code>0</code>)
789             * @param  type the mime type of assets to return(optionally
790             *         <code>null</code>)
791             * @param  keywords the keywords (space separated), which may occur in any
792             *         assets in the portlet (optionally <code>null</code>)
793             * @param  start the lower bound of the range of assets to return
794             * @param  end the upper bound of the range of assets to return (not
795             *         inclusive)
796             * @return the matching assets in the portlet within the company
797             * @throws SystemException if a system exception occurred
798             */
799            @Override
800            public Hits search(
801                            long companyId, long userId, String portletId, long groupId,
802                            String type, String keywords, int start, int end)
803                    throws SystemException {
804    
805                    try {
806    
807                            // Search context
808    
809                            SearchContext searchContext = new SearchContext();
810    
811                            searchContext.setCompanyId(companyId);
812                            searchContext.setEnd(end);
813                            searchContext.setEntryClassNames(
814                                    SearchEngineUtil.getEntryClassNames());
815    
816                            if (groupId > 0) {
817                                    searchContext.setGroupIds(new long[] {groupId});
818                            }
819    
820                            searchContext.setKeywords(keywords);
821    
822                            if (Validator.isNotNull(portletId)) {
823                                    searchContext.setPortletIds(new String[] {portletId});
824                            }
825    
826                            searchContext.setStart(start);
827                            searchContext.setUserId(userId);
828    
829                            // Always add facets as late as possible so that the search context
830                            // fields can be considered by the facets
831    
832                            Facet assetEntriesFacet = new AssetEntriesFacet(searchContext);
833    
834                            assetEntriesFacet.setStatic(true);
835    
836                            searchContext.addFacet(assetEntriesFacet);
837    
838                            Facet scopeFacet = new ScopeFacet(searchContext);
839    
840                            scopeFacet.setStatic(true);
841    
842                            searchContext.addFacet(scopeFacet);
843    
844                            // Search
845    
846                            Indexer indexer = FacetedSearcher.getInstance();
847    
848                            return indexer.search(searchContext);
849                    }
850                    catch (Exception e) {
851                            throw new SystemException(e);
852                    }
853            }
854    
855            /**
856             * Updates the company.
857             *
858             * @param  companyId the primary key of the company
859             * @param  virtualHostname the company's virtual host name
860             * @param  mx the company's mail domain
861             * @param  maxUsers the max number of company users (optionally
862             *         <code>0</code>)
863             * @param  active whether the company is active
864             * @return the company with the primary key
865             * @throws PortalException if a company with primary key could not be found
866             *         or if the new information was invalid
867             * @throws SystemException if a system exception occurred
868             */
869            @Override
870            public Company updateCompany(
871                            long companyId, String virtualHostname, String mx, int maxUsers,
872                            boolean active)
873                    throws PortalException, SystemException {
874    
875                    // Company
876    
877                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
878    
879                    if (!active) {
880                            if (companyId == PortalInstances.getDefaultCompanyId()) {
881                                    active = true;
882                            }
883                    }
884    
885                    Company company = companyPersistence.findByPrimaryKey(companyId);
886    
887                    validateVirtualHost(company.getWebId(), virtualHostname);
888    
889                    if (PropsValues.MAIL_MX_UPDATE) {
890                            validateMx(mx);
891    
892                            company.setMx(mx);
893                    }
894    
895                    company.setMaxUsers(maxUsers);
896                    company.setActive(active);
897    
898                    companyPersistence.update(company);
899    
900                    // Virtual host
901    
902                    updateVirtualHostname(companyId, virtualHostname);
903    
904                    return company;
905            }
906    
907            /**
908             * Update the company with additional account information.
909             *
910             * @param  companyId the primary key of the company
911             * @param  virtualHostname the company's virtual host name
912             * @param  mx the company's mail domain
913             * @param  homeURL the company's home URL (optionally <code>null</code>)
914             * @param  name the company's account name(optionally <code>null</code>)
915             * @param  legalName the company's account legal name (optionally
916             *         <code>null</code>)
917             * @param  legalId the company's account legal ID (optionally
918             *         <code>null</code>)
919             * @param  legalType the company's account legal type (optionally
920             *         <code>null</code>)
921             * @param  sicCode the company's account SIC code (optionally
922             *         <code>null</code>)
923             * @param  tickerSymbol the company's account ticker symbol (optionally
924             *         <code>null</code>)
925             * @param  industry the company's account industry (optionally
926             *         <code>null</code>)
927             * @param  type the company's account type (optionally <code>null</code>)
928             * @param  size the company's account size (optionally <code>null</code>)
929             * @return the company with the primary key
930             * @throws PortalException if a company with the primary key could not be
931             *         found or if the new information was invalid
932             * @throws SystemException if a system exception occurred
933             */
934            @Override
935            public Company updateCompany(
936                            long companyId, String virtualHostname, String mx, String homeURL,
937                            String name, String legalName, String legalId, String legalType,
938                            String sicCode, String tickerSymbol, String industry, String type,
939                            String size)
940                    throws PortalException, SystemException {
941    
942                    // Company
943    
944                    virtualHostname = StringUtil.toLowerCase(virtualHostname.trim());
945    
946                    Company company = companyPersistence.findByPrimaryKey(companyId);
947    
948                    validateVirtualHost(company.getWebId(), virtualHostname);
949    
950                    if (PropsValues.MAIL_MX_UPDATE) {
951                            validateMx(mx);
952                    }
953    
954                    validateName(companyId, name);
955    
956                    if (PropsValues.MAIL_MX_UPDATE) {
957                            company.setMx(mx);
958                    }
959    
960                    company.setHomeURL(homeURL);
961    
962                    companyPersistence.update(company);
963    
964                    // Account
965    
966                    updateAccount(
967                            company, name, legalName, legalId, legalType, sicCode, tickerSymbol,
968                            industry, type, size);
969    
970                    // Virtual host
971    
972                    updateVirtualHostname(companyId, virtualHostname);
973    
974                    return company;
975            }
976    
977            /**
978             * Update the company's display.
979             *
980             * @param  companyId the primary key of the company
981             * @param  languageId the ID of the company's default user's language
982             * @param  timeZoneId the ID of the company's default user's time zone
983             * @throws PortalException if the company's default user could not be found
984             * @throws SystemException if a system exception occurred
985             */
986            @Override
987            public void updateDisplay(
988                            long companyId, String languageId, String timeZoneId)
989                    throws PortalException, SystemException {
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             * @throws SystemException if a system exception occurred
1008             */
1009            @Override
1010            public Company updateLogo(long companyId, byte[] bytes)
1011                    throws PortalException, SystemException {
1012    
1013                    Company company = checkLogo(companyId);
1014    
1015                    imageLocalService.updateImage(company.getLogoId(), bytes);
1016    
1017                    return company;
1018            }
1019    
1020            /**
1021             * Updates the company's logo.
1022             *
1023             * @param  companyId the primary key of the company
1024             * @param  file the file of the company's logo image
1025             * @return the company with the primary key
1026             * @throws PortalException the company's logo ID could not be found or if
1027             *         the logo's image was corrupted
1028             * @throws SystemException if a system exception occurred
1029             */
1030            @Override
1031            public Company updateLogo(long companyId, File file)
1032                    throws PortalException, SystemException {
1033    
1034                    Company company = checkLogo(companyId);
1035    
1036                    imageLocalService.updateImage(company.getLogoId(), file);
1037    
1038                    return company;
1039            }
1040    
1041            /**
1042             * Update the company's logo.
1043             *
1044             * @param  companyId the primary key of the company
1045             * @param  is the input stream of the company's logo image
1046             * @return the company with the primary key
1047             * @throws PortalException if the company's logo ID could not be found or if
1048             *         the company's logo image was corrupted
1049             * @throws SystemException if a system exception occurred
1050             */
1051            @Override
1052            public Company updateLogo(long companyId, InputStream is)
1053                    throws PortalException, SystemException {
1054    
1055                    Company company = checkLogo(companyId);
1056    
1057                    imageLocalService.updateImage(company.getLogoId(), is);
1058    
1059                    return company;
1060            }
1061    
1062            /**
1063             * Updates the company's preferences. The company's default properties are
1064             * found in portal.properties.
1065             *
1066             * @param  companyId the primary key of the company
1067             * @param  properties the company's properties. See {@link
1068             *         com.liferay.portal.kernel.util.UnicodeProperties}
1069             * @throws PortalException if the properties contained new locales that were
1070             *         not supported
1071             * @throws SystemException if a system exception occurred
1072             */
1073            @Override
1074            public void updatePreferences(long companyId, UnicodeProperties properties)
1075                    throws PortalException, SystemException {
1076    
1077                    PortletPreferences portletPreferences = PrefsPropsUtil.getPreferences(
1078                            companyId);
1079    
1080                    try {
1081                            String newLanguageIds = properties.getProperty(PropsKeys.LOCALES);
1082    
1083                            if (Validator.isNotNull(newLanguageIds)) {
1084                                    String oldLanguageIds = portletPreferences.getValue(
1085                                            PropsKeys.LOCALES, StringPool.BLANK);
1086    
1087                                    if (!Validator.equals(oldLanguageIds, newLanguageIds)) {
1088                                            validateLanguageIds(newLanguageIds);
1089    
1090                                            LanguageUtil.resetAvailableLocales(companyId);
1091    
1092                                            // Invalidate cache of all layout set prototypes that belong
1093                                            // to this company. See LPS-36403.
1094    
1095                                            Date now = new Date();
1096    
1097                                            for (LayoutSetPrototype layoutSetPrototype :
1098                                                            layoutSetPrototypeLocalService.
1099                                                                    getLayoutSetPrototypes(companyId)) {
1100    
1101                                                    layoutSetPrototype.setModifiedDate(now);
1102    
1103                                                    layoutSetPrototypeLocalService.updateLayoutSetPrototype(
1104                                                            layoutSetPrototype);
1105                                            }
1106                                    }
1107                            }
1108    
1109                            List<String> resetKeys = new ArrayList<String>();
1110    
1111                            for (Map.Entry<String, String> entry : properties.entrySet()) {
1112                                    String key = entry.getKey();
1113                                    String value = entry.getValue();
1114    
1115                                    if (value.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
1116                                            continue;
1117                                    }
1118    
1119                                    String propsUtilValue = PropsUtil.get(key);
1120    
1121                                    if (!value.equals(propsUtilValue)) {
1122                                            portletPreferences.setValue(key, value);
1123                                    }
1124                                    else {
1125                                            String portletPreferencesValue =
1126                                                    portletPreferences.getValue(key, null);
1127    
1128                                            if (portletPreferencesValue != null) {
1129                                                    resetKeys.add(key);
1130                                            }
1131                                    }
1132                            }
1133    
1134                            for (String key : resetKeys) {
1135                                    portletPreferences.reset(key);
1136                            }
1137    
1138                            portletPreferences.store();
1139                    }
1140                    catch (LocaleException le) {
1141                            throw le;
1142                    }
1143                    catch (Exception e) {
1144                            throw new SystemException(e);
1145                    }
1146            }
1147    
1148            /**
1149             * Updates the company's security properties.
1150             *
1151             * @param  companyId the primary key of the company
1152             * @param  authType the company's method of authenticating users
1153             * @param  autoLogin whether to allow users to select the "remember me"
1154             *         feature
1155             * @param  sendPassword whether to allow users to ask the company to send
1156             *         their password
1157             * @param  strangers whether to allow strangers to create accounts register
1158             *         themselves in the company
1159             * @param  strangersWithMx whether to allow strangers to create accounts
1160             *         with email addresses that match the company mail suffix
1161             * @param  strangersVerify whether to require strangers who create accounts
1162             *         to be verified via email
1163             * @param  siteLogo whether to allow site administrators to use their own
1164             *         logo instead of the enterprise logo
1165             * @throws SystemException if a system exception occurred
1166             */
1167            @Override
1168            public void updateSecurity(
1169                            long companyId, String authType, boolean autoLogin,
1170                            boolean sendPassword, boolean strangers, boolean strangersWithMx,
1171                            boolean strangersVerify, boolean siteLogo)
1172                    throws SystemException {
1173    
1174                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1175                            companyId);
1176    
1177                    try {
1178                            preferences.setValue(
1179                                    PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
1180                            preferences.setValue(
1181                                    PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
1182                                    String.valueOf(autoLogin));
1183                            preferences.setValue(
1184                                    PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
1185                                    String.valueOf(sendPassword));
1186                            preferences.setValue(
1187                                    PropsKeys.COMPANY_SECURITY_STRANGERS,
1188                                    String.valueOf(strangers));
1189                            preferences.setValue(
1190                                    PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
1191                                    String.valueOf(strangersWithMx));
1192                            preferences.setValue(
1193                                    PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
1194                                    String.valueOf(strangersVerify));
1195                            preferences.setValue(
1196                                    PropsKeys.COMPANY_SECURITY_SITE_LOGO, String.valueOf(siteLogo));
1197    
1198                            preferences.store();
1199                    }
1200                    catch (IOException ioe) {
1201                            throw new SystemException(ioe);
1202                    }
1203                    catch (PortletException pe) {
1204                            throw new SystemException(pe);
1205                    }
1206            }
1207    
1208            protected Company checkLogo(long companyId)
1209                    throws PortalException, SystemException {
1210    
1211                    Company company = companyPersistence.findByPrimaryKey(companyId);
1212    
1213                    long logoId = company.getLogoId();
1214    
1215                    if (logoId <= 0) {
1216                            logoId = counterLocalService.increment();
1217    
1218                            company.setLogoId(logoId);
1219    
1220                            company = companyPersistence.update(company);
1221                    }
1222    
1223                    return company;
1224            }
1225    
1226            protected Company doDeleteCompany(final long companyId)
1227                    throws PortalException, SystemException {
1228    
1229                    // Company
1230    
1231                    Company company = companyPersistence.remove(companyId);
1232    
1233                    // Account
1234    
1235                    accountLocalService.deleteAccount(company.getAccountId());
1236    
1237                    // Groups
1238    
1239                    DeleteGroupActionableDynamicQuery deleteGroupActionableDynamicQuery =
1240                            new DeleteGroupActionableDynamicQuery();
1241    
1242                    deleteGroupActionableDynamicQuery.setCompanyId(companyId);
1243    
1244                    deleteGroupActionableDynamicQuery.performActions();
1245    
1246                    String[] systemGroups = PortalUtil.getSystemGroups();
1247    
1248                    for (String groupName : systemGroups) {
1249                            Group group = groupLocalService.getGroup(companyId, groupName);
1250    
1251                            deleteGroupActionableDynamicQuery.deleteGroup(group);
1252                    }
1253    
1254                    Group companyGroup = groupLocalService.getCompanyGroup(companyId);
1255    
1256                    deleteGroupActionableDynamicQuery.deleteGroup(companyGroup);
1257    
1258                    // Layout prototype
1259    
1260                    ActionableDynamicQuery layoutPrototypeActionableDynamicQuery =
1261                            new LayoutPrototypeActionableDynamicQuery() {
1262    
1263                            @Override
1264                            protected void performAction(Object object)
1265                                    throws PortalException, SystemException {
1266    
1267                                    LayoutPrototype layoutPrototype = (LayoutPrototype)object;
1268    
1269                                    layoutPrototypeLocalService.deleteLayoutPrototype(
1270                                            layoutPrototype);
1271                            }
1272    
1273                    };
1274    
1275                    layoutPrototypeActionableDynamicQuery.setCompanyId(companyId);
1276    
1277                    layoutPrototypeActionableDynamicQuery.performActions();
1278    
1279                    // Layout set prototype
1280    
1281                    ActionableDynamicQuery layoutSetPrototypeActionableDynamicQuery =
1282                            new LayoutSetPrototypeActionableDynamicQuery() {
1283    
1284                            @Override
1285                            protected void performAction(Object object)
1286                                    throws PortalException, SystemException {
1287    
1288                                    LayoutSetPrototype layoutSetPrototype =
1289                                            (LayoutSetPrototype)object;
1290    
1291                                    layoutSetPrototypeLocalService.deleteLayoutSetPrototype(
1292                                            layoutSetPrototype);
1293                            }
1294    
1295                    };
1296    
1297                    layoutSetPrototypeActionableDynamicQuery.setCompanyId(companyId);
1298    
1299                    layoutSetPrototypeActionableDynamicQuery.performActions();
1300    
1301                    // Organizations
1302    
1303                    DeleteOrganizationActionableDynamicQuery
1304                            deleteOrganizationActionableDynamicQuery =
1305                                    new DeleteOrganizationActionableDynamicQuery();
1306    
1307                    deleteOrganizationActionableDynamicQuery.setCompanyId(companyId);
1308    
1309                    deleteOrganizationActionableDynamicQuery.performActions();
1310    
1311                    // Roles
1312    
1313                    ActionableDynamicQuery roleActionableDynamicQuery =
1314                            new RoleActionableDynamicQuery() {
1315    
1316                            @Override
1317                            protected void performAction(Object object)
1318                                    throws PortalException, SystemException {
1319    
1320                                    Role role = (Role)object;
1321    
1322                                    roleLocalService.deleteRole(role);
1323                            }
1324    
1325                    };
1326    
1327                    roleActionableDynamicQuery.setCompanyId(companyId);
1328    
1329                    roleActionableDynamicQuery.performActions();
1330    
1331                    // Password policy
1332    
1333                    passwordPolicyLocalService.deleteNondefaultPasswordPolicies(companyId);
1334    
1335                    PasswordPolicy defaultPasswordPolicy =
1336                            passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
1337    
1338                    if (defaultPasswordPolicy != null) {
1339                            passwordPolicyLocalService.deletePasswordPolicy(
1340                                    defaultPasswordPolicy);
1341                    }
1342    
1343                    // Portal preferences
1344    
1345                    PortalPreferences portalPreferences =
1346                            portalPreferencesPersistence.findByO_O(
1347                                    companyId, PortletKeys.PREFS_OWNER_TYPE_COMPANY);
1348    
1349                    portalPreferencesLocalService.deletePortalPreferences(
1350                            portalPreferences);
1351    
1352                    // Portlets
1353    
1354                    List<Portlet> portlets = portletPersistence.findByCompanyId(companyId);
1355    
1356                    for (Portlet portlet : portlets) {
1357                            portletLocalService.deletePortlet(portlet.getId());
1358                    }
1359    
1360                    portletLocalService.removeCompanyPortletsPool(companyId);
1361    
1362                    // Users
1363    
1364                    ActionableDynamicQuery userActionableDynamicQuery =
1365                            new UserActionableDynamicQuery() {
1366    
1367                            @Override
1368                            protected void performAction(Object object)
1369                                    throws PortalException, SystemException {
1370    
1371                                    User user = (User)object;
1372    
1373                                    if (!user.isDefaultUser()) {
1374                                            userLocalService.deleteUser(user.getUserId());
1375                                    }
1376                            }
1377    
1378                    };
1379    
1380                    userActionableDynamicQuery.setCompanyId(companyId);
1381    
1382                    userActionableDynamicQuery.performActions();
1383    
1384                    User defaultUser = userLocalService.getDefaultUser(companyId);
1385    
1386                    userLocalService.deleteUser(defaultUser);
1387    
1388                    // Virtual host
1389    
1390                    VirtualHost companyVirtualHost =
1391                            virtualHostLocalService.fetchVirtualHost(companyId, 0);
1392    
1393                    virtualHostLocalService.deleteVirtualHost(companyVirtualHost);
1394    
1395                    // Shard
1396    
1397                    Shard shard = shardLocalService.getShard(
1398                            Company.class.getName(), company.getCompanyId());
1399    
1400                    shardLocalService.deleteShard(shard);
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,
1423                            String industry, String type, String size)
1424                    throws SystemException {
1425    
1426                    Date now = new Date();
1427    
1428                    Account account = accountPersistence.fetchByPrimaryKey(
1429                            company.getAccountId());
1430    
1431                    if (account == null) {
1432                            long accountId = counterLocalService.increment();
1433    
1434                            account = accountPersistence.create(accountId);
1435    
1436                            account.setCompanyId(company.getCompanyId());
1437                            account.setCreateDate(now);
1438                            account.setUserId(0);
1439                            account.setUserName(StringPool.BLANK);
1440    
1441                            company.setAccountId(accountId);
1442    
1443                            companyPersistence.update(company);
1444                    }
1445    
1446                    account.setModifiedDate(now);
1447                    account.setName(name);
1448                    account.setLegalName(legalName);
1449                    account.setLegalId(legalId);
1450                    account.setLegalType(legalType);
1451                    account.setSicCode(sicCode);
1452                    account.setTickerSymbol(tickerSymbol);
1453                    account.setIndustry(industry);
1454                    account.setType(type);
1455                    account.setSize(size);
1456    
1457                    accountPersistence.update(account);
1458            }
1459    
1460            protected void updateVirtualHostname(long companyId, String virtualHostname)
1461                    throws CompanyVirtualHostException, SystemException {
1462    
1463                    if (Validator.isNotNull(virtualHostname)) {
1464                            VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
1465                                    virtualHostname);
1466    
1467                            if (virtualHost == null) {
1468                                    virtualHostLocalService.updateVirtualHost(
1469                                            companyId, 0, virtualHostname);
1470                            }
1471                            else {
1472                                    if ((virtualHost.getCompanyId() != companyId) ||
1473                                            (virtualHost.getLayoutSetId() != 0)) {
1474    
1475                                            throw new CompanyVirtualHostException();
1476                                    }
1477                            }
1478                    }
1479                    else {
1480                            VirtualHost virtualHost = virtualHostPersistence.fetchByC_L(
1481                                    companyId, 0);
1482    
1483                            if (virtualHost != null) {
1484                                    virtualHostPersistence.remove(virtualHost);
1485                            }
1486                    }
1487            }
1488    
1489            protected void validateLanguageIds(String languageIds)
1490                    throws PortalException {
1491    
1492                    String[] languageIdsArray = StringUtil.split(
1493                            languageIds, StringPool.COMMA);
1494    
1495                    for (String languageId : languageIdsArray) {
1496                            if (!ArrayUtil.contains(PropsValues.LOCALES, languageId)) {
1497                                    LocaleException le = new LocaleException(
1498                                            LocaleException.TYPE_DISPLAY_SETTINGS);
1499    
1500                                    le.setSourceAvailableLocales(
1501                                            LocaleUtil.fromLanguageIds(PropsValues.LOCALES));
1502                                    le.setTargetAvailableLocales(
1503                                            LocaleUtil.fromLanguageIds(languageIdsArray));
1504    
1505                                    throw le;
1506                            }
1507                    }
1508            }
1509    
1510            protected void validateMx(String mx) throws PortalException {
1511                    if (Validator.isNull(mx) || !Validator.isDomain(mx)) {
1512                            throw new CompanyMxException();
1513                    }
1514            }
1515    
1516            protected void validateName(long companyId, String name)
1517                    throws PortalException, SystemException {
1518    
1519                    Group group = groupLocalService.fetchGroup(companyId, name);
1520    
1521                    if ((group != null) || Validator.isNull(name)) {
1522                            throw new AccountNameException();
1523                    }
1524            }
1525    
1526            protected void validateVirtualHost(String webId, String virtualHostname)
1527                    throws PortalException, SystemException {
1528    
1529                    if (Validator.isNull(virtualHostname)) {
1530                            throw new CompanyVirtualHostException();
1531                    }
1532                    else if (virtualHostname.equals(_DEFAULT_VIRTUAL_HOST) &&
1533                                     !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
1534    
1535                            throw new CompanyVirtualHostException();
1536                    }
1537                    else if (!Validator.isDomain(virtualHostname)) {
1538                            throw new CompanyVirtualHostException();
1539                    }
1540                    else {
1541                            try {
1542                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1543                                            virtualHostname);
1544    
1545                                    long companyId = virtualHost.getCompanyId();
1546    
1547                                    Company virtualHostnameCompany =
1548                                            companyPersistence.findByPrimaryKey(companyId);
1549    
1550                                    if (!webId.equals(virtualHostnameCompany.getWebId())) {
1551                                            throw new CompanyVirtualHostException();
1552                                    }
1553                            }
1554                            catch (NoSuchVirtualHostException nsvhe) {
1555                            }
1556                    }
1557            }
1558    
1559            protected class DeleteGroupActionableDynamicQuery
1560                    extends GroupActionableDynamicQuery {
1561    
1562                    public DeleteGroupActionableDynamicQuery() throws SystemException {
1563                    }
1564    
1565                    public void deleteGroup(Group group)
1566                            throws PortalException, SystemException {
1567    
1568                            DeleteGroupActionableDynamicQuery
1569                                    deleteGroupActionableDynamicQuery =
1570                                            new DeleteGroupActionableDynamicQuery();
1571    
1572                            deleteGroupActionableDynamicQuery.setCompanyId(
1573                                    group.getCompanyId());
1574                            deleteGroupActionableDynamicQuery.setParentGroupId(
1575                                    group.getGroupId());
1576    
1577                            deleteGroupActionableDynamicQuery.performActions();
1578    
1579                            groupLocalService.deleteGroup(group);
1580    
1581                            LiveUsers.deleteGroup(group.getCompanyId(), group.getGroupId());
1582                    }
1583    
1584                    public void setParentGroupId(long parentGroupId) {
1585                            _parentGroupId = parentGroupId;
1586                    }
1587    
1588                    @Override
1589                    protected void addCriteria(DynamicQuery dynamicQuery) {
1590                            Property parentGroupIdProperty = PropertyFactoryUtil.forName(
1591                                    "parentGroupId");
1592    
1593                            dynamicQuery.add(parentGroupIdProperty.eq(_parentGroupId));
1594    
1595                            Property siteProperty = PropertyFactoryUtil.forName("site");
1596    
1597                            dynamicQuery.add(siteProperty.eq(Boolean.TRUE));
1598                    }
1599    
1600                    @Override
1601                    protected void performAction(Object object)
1602                            throws PortalException, SystemException {
1603    
1604                            Group group = (Group)object;
1605    
1606                            if (!PortalUtil.isSystemGroup(group.getName()) &&
1607                                    !group.isCompany()) {
1608    
1609                                    deleteGroup(group);
1610                            }
1611                    }
1612    
1613                    private long _parentGroupId = GroupConstants.DEFAULT_PARENT_GROUP_ID;
1614    
1615            }
1616    
1617            protected class DeleteOrganizationActionableDynamicQuery
1618                    extends OrganizationActionableDynamicQuery {
1619    
1620                    public DeleteOrganizationActionableDynamicQuery()
1621                            throws SystemException {
1622                    }
1623    
1624                    public void deleteOrganization(Organization organization)
1625                            throws PortalException, SystemException {
1626    
1627                            DeleteOrganizationActionableDynamicQuery
1628                                    deleteOrganizationActionableDynamicQuery =
1629                                    new DeleteOrganizationActionableDynamicQuery();
1630    
1631                            deleteOrganizationActionableDynamicQuery.setCompanyId(
1632                                    organization.getCompanyId());
1633                            deleteOrganizationActionableDynamicQuery.setParentOrganizationId(
1634                                    organization.getOrganizationId());
1635    
1636                            deleteOrganizationActionableDynamicQuery.performActions();
1637    
1638                            organizationLocalService.deleteOrganization(organization);
1639                    }
1640    
1641                    public void setParentOrganizationId(long parentOrganizationId) {
1642                            _parentOrganizationId = parentOrganizationId;
1643                    }
1644    
1645                    @Override
1646                    protected void addCriteria(DynamicQuery dynamicQuery) {
1647                            Property property = PropertyFactoryUtil.forName(
1648                                    "parentOrganizationId");
1649    
1650                            dynamicQuery.add(property.eq(_parentOrganizationId));
1651                    }
1652    
1653                    @Override
1654                    protected void performAction(Object object)
1655                            throws PortalException, SystemException {
1656    
1657                            Organization organization = (Organization)object;
1658    
1659                            deleteOrganization(organization);
1660                    }
1661    
1662                    private long _parentOrganizationId =
1663                            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;
1664    
1665            }
1666    
1667            private static final String _DEFAULT_VIRTUAL_HOST = "localhost";
1668    
1669            private static Log _log = LogFactoryUtil.getLog(
1670                    CompanyLocalServiceImpl.class);
1671    
1672    }