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