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