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