001    /**
002     * Copyright (c) 2000-2012 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.NoSuchUserException;
024    import com.liferay.portal.NoSuchVirtualHostException;
025    import com.liferay.portal.kernel.exception.PortalException;
026    import com.liferay.portal.kernel.exception.SystemException;
027    import com.liferay.portal.kernel.language.LanguageUtil;
028    import com.liferay.portal.kernel.log.Log;
029    import com.liferay.portal.kernel.log.LogFactoryUtil;
030    import com.liferay.portal.kernel.search.FacetedSearcher;
031    import com.liferay.portal.kernel.search.Hits;
032    import com.liferay.portal.kernel.search.Indexer;
033    import com.liferay.portal.kernel.search.SearchContext;
034    import com.liferay.portal.kernel.search.SearchEngineUtil;
035    import com.liferay.portal.kernel.search.facet.AssetEntriesFacet;
036    import com.liferay.portal.kernel.search.facet.Facet;
037    import com.liferay.portal.kernel.search.facet.ScopeFacet;
038    import com.liferay.portal.kernel.util.ArrayUtil;
039    import com.liferay.portal.kernel.util.Base64;
040    import com.liferay.portal.kernel.util.LocaleUtil;
041    import com.liferay.portal.kernel.util.PropsKeys;
042    import com.liferay.portal.kernel.util.StringPool;
043    import com.liferay.portal.kernel.util.StringUtil;
044    import com.liferay.portal.kernel.util.TimeZoneUtil;
045    import com.liferay.portal.kernel.util.UnicodeProperties;
046    import com.liferay.portal.kernel.util.Validator;
047    import com.liferay.portal.kernel.workflow.WorkflowConstants;
048    import com.liferay.portal.model.Account;
049    import com.liferay.portal.model.Company;
050    import com.liferay.portal.model.CompanyConstants;
051    import com.liferay.portal.model.Contact;
052    import com.liferay.portal.model.ContactConstants;
053    import com.liferay.portal.model.Group;
054    import com.liferay.portal.model.GroupConstants;
055    import com.liferay.portal.model.Role;
056    import com.liferay.portal.model.RoleConstants;
057    import com.liferay.portal.model.User;
058    import com.liferay.portal.model.VirtualHost;
059    import com.liferay.portal.service.ServiceContext;
060    import com.liferay.portal.service.base.CompanyLocalServiceBaseImpl;
061    import com.liferay.portal.util.Portal;
062    import com.liferay.portal.util.PortalInstances;
063    import com.liferay.portal.util.PrefsPropsUtil;
064    import com.liferay.portal.util.PropsUtil;
065    import com.liferay.portal.util.PropsValues;
066    import com.liferay.util.Encryptor;
067    import com.liferay.util.EncryptorException;
068    
069    import java.io.File;
070    import java.io.IOException;
071    import java.io.InputStream;
072    
073    import java.util.ArrayList;
074    import java.util.Calendar;
075    import java.util.Date;
076    import java.util.List;
077    import java.util.Locale;
078    import java.util.Map;
079    import java.util.TimeZone;
080    
081    import javax.portlet.PortletException;
082    import javax.portlet.PortletPreferences;
083    
084    /**
085     * The implementation of the company local service. Each company refers to a
086     * separate portal instance.
087     *
088     * @author Brian Wing Shun Chan
089     * @author Julio Camarero
090     */
091    public class CompanyLocalServiceImpl extends CompanyLocalServiceBaseImpl {
092    
093            /**
094             * Adds a company.
095             *
096             * @param  webId the the company's web domain
097             * @param  virtualHostname the company's virtual host name
098             * @param  mx the company's mail domain
099             * @param  shardName the company's shard
100             * @param  system whether the company is the very first company (i.e., the
101             *         super company)
102             * @param  maxUsers the max number of company users (optionally
103             *         <code>0</code>)
104             * @param  active whether the company is active
105             * @return the company
106             * @throws PortalException if the web domain, virtual host name, or mail
107             *         domain was invalid
108             * @throws SystemException if a system exception occurred
109             */
110            public Company addCompany(
111                            String webId, String virtualHostname, String mx, String shardName,
112                            boolean system, int maxUsers, boolean active)
113                    throws PortalException, SystemException {
114    
115                    // Company
116    
117                    virtualHostname = virtualHostname.trim().toLowerCase();
118    
119                    if ((Validator.isNull(webId)) ||
120                            (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) ||
121                            (companyPersistence.fetchByWebId(webId) != null)) {
122    
123                            throw new CompanyWebIdException();
124                    }
125    
126                    validate(webId, virtualHostname, mx);
127    
128                    Company company = checkCompany(webId, mx, shardName);
129    
130                    company.setMx(mx);
131                    company.setSystem(system);
132                    company.setMaxUsers(maxUsers);
133                    company.setActive(active);
134    
135                    companyPersistence.update(company, false);
136    
137                    // Virtual host
138    
139                    updateVirtualHost(company.getCompanyId(), virtualHostname);
140    
141                    return company;
142            }
143    
144            /**
145             * Returns the company with the web domain.
146             *
147             * The method sets mail domain to the web domain, and the shard name to
148             * the default name set in portal.properties
149             *
150             * @param  webId the company's web domain
151             * @return the company with the web domain
152             * @throws PortalException if a portal exception occurred
153             * @throws SystemException if a system exception occurred
154             */
155            public Company checkCompany(String webId)
156                    throws PortalException, SystemException {
157    
158                    String mx = webId;
159    
160                    return companyLocalService.checkCompany(
161                            webId, mx, PropsValues.SHARD_DEFAULT_NAME);
162            }
163    
164            /**
165             * Returns the company with the web domain, mail domain, and shard. If no
166             * such company exits, the method will create a new company.
167             *
168             * The method goes through a series of checks to ensure that the company
169             * contains default users, groups, etc.
170             *
171             * @param  webId the company's web domain
172             * @param  mx the company's mail domain
173             * @param  shardName the company's shard
174             * @return the company with the web domain, mail domain, and shard
175             * @throws PortalException if a portal exception occurred
176             * @throws SystemException if a system exception occurred
177             */
178            public Company checkCompany(String webId, String mx, String shardName)
179                    throws PortalException, SystemException {
180    
181                    // Company
182    
183                    Date now = new Date();
184    
185                    Company company = companyPersistence.fetchByWebId(webId);
186    
187                    if (company == null) {
188                            String virtualHostname = webId;
189    
190                            if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
191                                    virtualHostname = _DEFAULT_VIRTUAL_HOST;
192                            }
193    
194                            String homeURL = null;
195                            String name = webId;
196                            String legalName = null;
197                            String legalId = null;
198                            String legalType = null;
199                            String sicCode = null;
200                            String tickerSymbol = null;
201                            String industry = null;
202                            String type = null;
203                            String size = null;
204    
205                            long companyId = counterLocalService.increment();
206    
207                            company = companyPersistence.create(companyId);
208    
209                            try {
210                                    company.setKey(Base64.objectToString(Encryptor.generateKey()));
211                            }
212                            catch (EncryptorException ee) {
213                                    throw new SystemException(ee);
214                            }
215    
216                            company.setWebId(webId);
217                            company.setMx(mx);
218                            company.setActive(true);
219    
220                            companyPersistence.update(company, false);
221    
222                            // Shard
223    
224                            shardLocalService.addShard(
225                                    Company.class.getName(), companyId, shardName);
226    
227                            // Company
228    
229                            updateCompany(
230                                    companyId, virtualHostname, mx, homeURL, name, legalName,
231                                    legalId, legalType, sicCode, tickerSymbol, industry, type,
232                                    size);
233    
234                            // Virtual host
235    
236                            updateVirtualHost(companyId, virtualHostname);
237    
238                            // Demo settings
239    
240                            if (webId.equals("liferay.net")) {
241                                    company = companyPersistence.findByWebId(webId);
242    
243                                    updateVirtualHost(companyId, "demo.liferay.net");
244    
245                                    updateSecurity(
246                                            companyId, CompanyConstants.AUTH_TYPE_EA, true, true, true,
247                                            true, false, true);
248    
249                                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
250                                            companyId);
251    
252                                    try {
253                                            preferences.setValue(
254                                                    PropsKeys.ADMIN_EMAIL_FROM_NAME, "Liferay Demo");
255                                            preferences.setValue(
256                                                    PropsKeys.ADMIN_EMAIL_FROM_ADDRESS, "test@liferay.net");
257    
258                                            preferences.store();
259                                    }
260                                    catch (IOException ioe) {
261                                            throw new SystemException(ioe);
262                                    }
263                                    catch (PortletException pe) {
264                                            throw new SystemException(pe);
265                                    }
266                            }
267                    }
268                    else {
269                            try {
270                                    shardLocalService.getShard(
271                                            Company.class.getName(), company.getCompanyId());
272                            }
273                            catch (NoSuchShardException nsse) {
274                                    shardLocalService.addShard(
275                                            Company.class.getName(), company.getCompanyId(), shardName);
276                            }
277                    }
278    
279                    long companyId = company.getCompanyId();
280    
281                    // Key
282    
283                    checkCompanyKey(companyId);
284    
285                    // Default user
286    
287                    User defaultUser = null;
288    
289                    try {
290                            defaultUser = userLocalService.getDefaultUser(companyId);
291    
292                            if (!defaultUser.isAgreedToTermsOfUse()) {
293                                    defaultUser.setAgreedToTermsOfUse(true);
294    
295                                    userPersistence.update(defaultUser, false);
296                            }
297                    }
298                    catch (NoSuchUserException nsue) {
299                            long userId = counterLocalService.increment();
300    
301                            defaultUser = userPersistence.create(userId);
302    
303                            defaultUser.setCompanyId(companyId);
304                            defaultUser.setCreateDate(now);
305                            defaultUser.setModifiedDate(now);
306                            defaultUser.setDefaultUser(true);
307                            defaultUser.setContactId(counterLocalService.increment());
308                            defaultUser.setPassword("password");
309                            defaultUser.setScreenName(String.valueOf(defaultUser.getUserId()));
310                            defaultUser.setEmailAddress("default@" + company.getMx());
311    
312                            if (Validator.isNotNull(PropsValues.COMPANY_DEFAULT_LOCALE)) {
313                                    defaultUser.setLanguageId(PropsValues.COMPANY_DEFAULT_LOCALE);
314                            }
315                            else {
316                                    Locale locale = LocaleUtil.getDefault();
317    
318                                    defaultUser.setLanguageId(locale.toString());
319                            }
320    
321                            if (Validator.isNotNull(PropsValues.COMPANY_DEFAULT_TIME_ZONE)) {
322                                    defaultUser.setTimeZoneId(
323                                            PropsValues.COMPANY_DEFAULT_TIME_ZONE);
324                            }
325                            else {
326                                    TimeZone timeZone = TimeZoneUtil.getDefault();
327    
328                                    defaultUser.setTimeZoneId(timeZone.getID());
329                            }
330    
331                            defaultUser.setGreeting(
332                                    LanguageUtil.format(
333                                            defaultUser.getLocale(), "welcome-x", StringPool.BLANK,
334                                            false));
335                            defaultUser.setLoginDate(now);
336                            defaultUser.setFailedLoginAttempts(0);
337                            defaultUser.setAgreedToTermsOfUse(true);
338                            defaultUser.setStatus(WorkflowConstants.STATUS_APPROVED);
339    
340                            userPersistence.update(defaultUser, false);
341    
342                            // Contact
343    
344                            Contact defaultContact = contactPersistence.create(
345                                    defaultUser.getContactId());
346    
347                            defaultContact.setCompanyId(defaultUser.getCompanyId());
348                            defaultContact.setUserId(defaultUser.getUserId());
349                            defaultContact.setUserName(StringPool.BLANK);
350                            defaultContact.setCreateDate(now);
351                            defaultContact.setModifiedDate(now);
352                            defaultContact.setAccountId(company.getAccountId());
353                            defaultContact.setParentContactId(
354                                    ContactConstants.DEFAULT_PARENT_CONTACT_ID);
355                            defaultContact.setFirstName(StringPool.BLANK);
356                            defaultContact.setMiddleName(StringPool.BLANK);
357                            defaultContact.setLastName(StringPool.BLANK);
358                            defaultContact.setMale(true);
359                            defaultContact.setBirthday(now);
360    
361                            contactPersistence.update(defaultContact, false);
362                    }
363    
364                    // System roles
365    
366                    roleLocalService.checkSystemRoles(companyId);
367    
368                    // System groups
369    
370                    groupLocalService.checkSystemGroups(companyId);
371    
372                    // Company group
373    
374                    groupLocalService.checkCompanyGroup(companyId);
375    
376                    // Default password policy
377    
378                    passwordPolicyLocalService.checkDefaultPasswordPolicy(companyId);
379    
380                    // Default user must have the Guest role
381    
382                    Role guestRole = roleLocalService.getRole(
383                            companyId, RoleConstants.GUEST);
384    
385                    roleLocalService.setUserRoles(
386                            defaultUser.getUserId(), new long[] {guestRole.getRoleId()});
387    
388                    // Default admin
389    
390                    if (userPersistence.countByCompanyId(companyId) == 1) {
391                            long creatorUserId = 0;
392                            boolean autoPassword = false;
393                            String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
394                            String password2 = password1;
395                            boolean autoScreenName = false;
396                            String screenName = PropsValues.DEFAULT_ADMIN_SCREEN_NAME;
397    
398                            String emailAddress = null;
399    
400                            if (companyPersistence.countAll() == 1) {
401                                    emailAddress = PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS;
402                            }
403    
404                            if (Validator.isNull(emailAddress)) {
405                                    emailAddress =
406                                            PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + "@" + mx;
407                            }
408    
409                            long facebookId = 0;
410                            String openId = StringPool.BLANK;
411                            Locale locale = defaultUser.getLocale();
412                            String firstName = PropsValues.DEFAULT_ADMIN_FIRST_NAME;
413                            String middleName = PropsValues.DEFAULT_ADMIN_MIDDLE_NAME;
414                            String lastName = PropsValues.DEFAULT_ADMIN_LAST_NAME;
415                            int prefixId = 0;
416                            int suffixId = 0;
417                            boolean male = true;
418                            int birthdayMonth = Calendar.JANUARY;
419                            int birthdayDay = 1;
420                            int birthdayYear = 1970;
421                            String jobTitle = StringPool.BLANK;
422    
423                            Group guestGroup = groupLocalService.getGroup(
424                                    companyId, GroupConstants.GUEST);
425    
426                            long[] groupIds = new long[] {guestGroup.getGroupId()};
427    
428                            long[] organizationIds = null;
429    
430                            Role adminRole = roleLocalService.getRole(
431                                    companyId, RoleConstants.ADMINISTRATOR);
432    
433                            Role powerUserRole = roleLocalService.getRole(
434                                    companyId, RoleConstants.POWER_USER);
435    
436                            long[] roleIds = new long[] {
437                                    adminRole.getRoleId(), powerUserRole.getRoleId()
438                            };
439    
440                            long[] userGroupIds = null;
441                            boolean sendEmail = false;
442                            ServiceContext serviceContext = new ServiceContext();
443    
444                            User defaultAdminUser = userLocalService.addUser(
445                                    creatorUserId, companyId, autoPassword, password1, password2,
446                                    autoScreenName, screenName, emailAddress, facebookId, openId,
447                                    locale, firstName, middleName, lastName, prefixId, suffixId,
448                                    male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
449                                    groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
450                                    serviceContext);
451    
452                            userLocalService.updateEmailAddressVerified(
453                                    defaultAdminUser.getUserId(), true);
454    
455                            userLocalService.updateLastLogin(
456                                    defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
457    
458                            userLocalService.updatePasswordReset(
459                                    defaultAdminUser.getUserId(), false);
460                    }
461    
462                    // Portlets
463    
464                    portletLocalService.checkPortlets(companyId);
465    
466                    return company;
467            }
468    
469            /**
470             * Checks if the company has an encryption key. It will create a key if one
471             * does not exist.
472             *
473             * @param  companyId the primary key of the company
474             * @throws PortalException if a company with the primary key could not be
475             *         found
476             * @throws SystemException if a system exception occurred
477             */
478            public void checkCompanyKey(long companyId)
479                    throws PortalException, SystemException {
480    
481                    Company company = companyPersistence.findByPrimaryKey(companyId);
482    
483                    if ((Validator.isNull(company.getKey())) &&
484                            (company.getKeyObj() == null)) {
485    
486                            try {
487                                    company.setKey(Base64.objectToString(Encryptor.generateKey()));
488                            }
489                            catch (EncryptorException ee) {
490                                    throw new SystemException(ee);
491                            }
492    
493                            companyPersistence.update(company, false);
494                    }
495            }
496    
497            /**
498             * Deletes the company's logo.
499             *
500             * @param  companyId the primary key of the company
501             * @throws PortalException if the company with the primary key could not be
502             *         found or if the company's logo could not be found
503             * @throws SystemException if a system exception occurred
504             */
505            public void deleteLogo(long companyId)
506                    throws PortalException, SystemException {
507    
508                    Company company = companyPersistence.findByPrimaryKey(companyId);
509    
510                    long logoId = company.getLogoId();
511    
512                    if (logoId > 0) {
513                            company.setLogoId(0);
514    
515                            companyPersistence.update(company, false);
516    
517                            imageLocalService.deleteImage(logoId);
518                    }
519            }
520    
521            /**
522             * Returns the company with the primary key.
523             *
524             * @param  companyId the primary key of the company
525             * @return the company with the primary key, <code>null</code> if a company
526             *         with the primary key could not be found
527             * @throws SystemException if a system exception occurred
528             */
529            public Company fetchCompanyById(long companyId) throws SystemException {
530                    return companyPersistence.fetchByPrimaryKey(companyId);
531            }
532    
533            /**
534             * Returns the company with the virtual host name.
535             *
536             * @param  virtualHostname the virtual host name
537             * @return the company with the virtual host name, <code>null</code> if a
538             *         company with the virtual host could not be found
539             * @throws SystemException if a system exception occurred
540             */
541            public Company fetchCompanyByVirtualHost(String virtualHostname)
542                    throws SystemException {
543    
544                    virtualHostname = virtualHostname.trim().toLowerCase();
545    
546                    VirtualHost virtualHost = virtualHostPersistence.fetchByHostname(
547                            virtualHostname);
548    
549                    if ((virtualHost == null) || (virtualHost.getLayoutSetId() != 0)) {
550                            return null;
551                    }
552    
553                    return companyPersistence.fetchByPrimaryKey(virtualHost.getCompanyId());
554            }
555    
556            /**
557             * Returns all the companies.
558             *
559             * @return the companies
560             * @throws SystemException if a system exception occurred
561             */
562            public List<Company> getCompanies() throws SystemException {
563                    return companyPersistence.findAll();
564            }
565    
566            /**
567             * Returns all the companies used by WSRP.
568             *
569             * @param  system whether the company is the very first company (i.e., the
570             *         super company)
571             * @return the companies used by WSRP
572             * @throws SystemException if a system exception occurred
573             */
574            public List<Company> getCompanies(boolean system) throws SystemException {
575                    return companyPersistence.findBySystem(system);
576            }
577    
578            /**
579             * Returns the number of companies used by WSRP.
580             *
581             * @param  system whether the company is the very first company (i.e., the
582             *         super company)
583             * @return the number of companies used by WSRP
584             * @throws SystemException if a system exception occurred
585             */
586            public int getCompaniesCount(boolean system) throws SystemException {
587                    return companyPersistence.countBySystem(system);
588            }
589    
590            /**
591             * Returns the company with the primary key.
592             *
593             * @param  companyId the primary key of the company
594             * @return the company with the primary key
595             * @throws PortalException if a company with the primary key could not be
596             *         found
597             * @throws SystemException if a system exception occurred
598             */
599            public Company getCompanyById(long companyId)
600                    throws PortalException, SystemException {
601    
602                    return companyPersistence.findByPrimaryKey(companyId);
603            }
604    
605            /**
606             * Returns the company with the logo.
607             *
608             * @param  logoId the ID of the company's logo
609             * @return the company with the logo
610             * @throws PortalException if the company with the logo could not be found
611             * @throws SystemException if a system exception occurred
612             */
613            public Company getCompanyByLogoId(long logoId)
614                    throws PortalException, SystemException {
615    
616                    return companyPersistence.findByLogoId(logoId);
617            }
618    
619            /**
620             * Returns the company with the mail domain.
621             *
622             * @param  mx the company's mail domain
623             * @return the company with the mail domain
624             * @throws PortalException if the company with the mail domain could not be
625             *         found
626             * @throws SystemException if a system exception occurred
627             */
628            public Company getCompanyByMx(String mx)
629                    throws PortalException, SystemException {
630    
631                    return companyPersistence.findByMx(mx);
632            }
633    
634            /**
635             * Returns the company with the virtual host name.
636             *
637             * @param  virtualHostname the company's virtual host name
638             * @return the company with the virtual host name
639             * @throws PortalException if the company with the virtual host name could
640             *         not be found or if the virtual host was not associated with a
641             *         company
642             * @throws SystemException if a system exception occurred
643             */
644            public Company getCompanyByVirtualHost(String virtualHostname)
645                    throws PortalException, SystemException {
646    
647                    try {
648                            virtualHostname = virtualHostname.trim().toLowerCase();
649    
650                            VirtualHost virtualHost = virtualHostPersistence.findByHostname(
651                                    virtualHostname);
652    
653                            if (virtualHost.getLayoutSetId() != 0) {
654                                    throw new CompanyVirtualHostException(
655                                            "Virtual host is associated with layout set " +
656                                                    virtualHost.getLayoutSetId());
657                            }
658    
659                            return companyPersistence.findByPrimaryKey(
660                                    virtualHost.getCompanyId());
661                    }
662                    catch (NoSuchVirtualHostException nsvhe) {
663                            throw new CompanyVirtualHostException(nsvhe);
664                    }
665            }
666    
667            /**
668             * Returns the company with the web domain.
669             *
670             * @param  webId the company's web domain
671             * @return the company with the web domain
672             * @throws PortalException if the company with the web domain could not be
673             *         found
674             * @throws SystemException if a system exception occurred
675             */
676            public Company getCompanyByWebId(String webId)
677                    throws PortalException, SystemException {
678    
679                    return companyPersistence.findByWebId(webId);
680            }
681    
682            /**
683             * Returns the user's company.
684             *
685             * @param  userId the primary key of the user
686             * @return Returns the first company if there is only one company or the
687             *         user's company if there are more than one company; <code>0</code>
688             *         otherwise
689             * @throws Exception if a user with the primary key could not be found
690             */
691            public long getCompanyIdByUserId(long userId) throws Exception {
692                    long[] companyIds = PortalInstances.getCompanyIds();
693    
694                    long companyId = 0;
695    
696                    if (companyIds.length == 1) {
697                            companyId = companyIds[0];
698                    }
699                    else if (companyIds.length > 1) {
700                            try {
701                                    User user = userPersistence.findByPrimaryKey(userId);
702    
703                                    companyId = user.getCompanyId();
704                            }
705                            catch (Exception e) {
706                                    if (_log.isWarnEnabled()) {
707                                            _log.warn(
708                                                    "Unable to get the company id for user " + userId, e);
709                                    }
710                            }
711                    }
712    
713                    return companyId;
714            }
715    
716            /**
717             * Removes the values that match the keys of the company's preferences.
718             *
719             * This method is called by {@link
720             * com.liferay.portlet.portalsettings.action.EditLDAPServerAction} remotely
721             * through {@link com.liferay.portal.service.CompanyService}.
722             *
723             * @param  companyId the primary key of the company
724             * @param  keys the company's preferences keys to be remove
725             * @throws SystemException if a system exception occurred
726             */
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            public Hits search(
764                            long companyId, long userId, String keywords, int start, int end)
765                    throws SystemException {
766    
767                    return search(companyId, userId, null, 0, null, keywords, start, end);
768            }
769    
770            /**
771             * Returns an ordered range of all assets that match the keywords in the
772             * portlet within the company.
773             *
774             * @param  companyId the primary key of the company
775             * @param  userId the primary key of the user
776             * @param  portletId the primary key of the portlet (optionally
777             *         <code>null</code>)
778             * @param  groupId the primary key of the group (optionally <code>0</code>)
779             * @param  type the mime type of assets to return(optionally
780             *         <code>null</code>)
781             * @param  keywords the keywords (space separated), which may occur in any
782             *         assets in the portlet (optionally <code>null</code>)
783             * @param  start the lower bound of the range of assets to return
784             * @param  end the upper bound of the range of assets to return (not
785             *         inclusive)
786             * @return the matching assets in the portlet within the company
787             * @throws SystemException if a system exception occurred
788             */
789            public Hits search(
790                            long companyId, long userId, String portletId, long groupId,
791                            String type, String keywords, int start, int end)
792                    throws SystemException {
793    
794                    try {
795                            SearchContext searchContext = new SearchContext();
796    
797                            Facet assetEntriesFacet = new AssetEntriesFacet(searchContext);
798    
799                            assetEntriesFacet.setStatic(true);
800    
801                            searchContext.addFacet(assetEntriesFacet);
802    
803                            Facet scopeFacet = new ScopeFacet(searchContext);
804    
805                            scopeFacet.setStatic(true);
806    
807                            searchContext.addFacet(scopeFacet);
808    
809                            searchContext.setCompanyId(companyId);
810                            searchContext.setEnd(end);
811                            searchContext.setEntryClassNames(
812                                    SearchEngineUtil.getEntryClassNames());
813    
814                            if (groupId > 0) {
815                                    searchContext.setGroupIds(new long[]{groupId});
816                            }
817    
818                            searchContext.setKeywords(keywords);
819    
820                            if (Validator.isNotNull(portletId)) {
821                                    searchContext.setPortletIds(new String[] {portletId});
822                            }
823    
824                            searchContext.setSearchEngineId(SearchEngineUtil.SYSTEM_ENGINE_ID);
825                            searchContext.setStart(start);
826                            searchContext.setUserId(userId);
827    
828                            Indexer indexer = FacetedSearcher.getInstance();
829    
830                            return indexer.search(searchContext);
831                    }
832                    catch (Exception e) {
833                            throw new SystemException(e);
834                    }
835            }
836    
837            /**
838             * Updates the company.
839             *
840             * @param  companyId the primary key of the company
841             * @param  virtualHostname the company's virtual host name
842             * @param  mx the company's mail domain
843             * @param  maxUsers the max number of company users (optionally
844             *         <code>0</code>)
845             * @param  active whether the company is active
846             * @return the company with the primary key
847             * @throws PortalException if a company with primary key could not be found
848             *         or if the new information was invalid
849             * @throws SystemException if a system exception occurred
850             */
851            public Company updateCompany(
852                            long companyId, String virtualHostname, String mx, int maxUsers,
853                            boolean active)
854                    throws PortalException, SystemException {
855    
856                    // Company
857    
858                    virtualHostname = virtualHostname.trim().toLowerCase();
859    
860                    if (!active) {
861                            if (companyId == PortalInstances.getDefaultCompanyId()) {
862                                    active = true;
863                            }
864                    }
865    
866                    Company company = companyPersistence.findByPrimaryKey(companyId);
867    
868                    validate(company.getWebId(), virtualHostname, mx);
869    
870                    if (PropsValues.MAIL_MX_UPDATE) {
871                            company.setMx(mx);
872                    }
873    
874                    company.setMaxUsers(maxUsers);
875                    company.setActive(active);
876    
877                    companyPersistence.update(company, false);
878    
879                    // Virtual host
880    
881                    updateVirtualHost(companyId, virtualHostname);
882    
883                    return company;
884            }
885    
886            /**
887             * Update the company with additional account information.
888             *
889             * @param  companyId the primary key of the company
890             * @param  virtualHostname the company's virtual host name
891             * @param  mx the company's mail domain
892             * @param  homeURL the company's home URL (optionally <code>null</code>)
893             * @param  name the company's account name(optionally <code>null</code>)
894             * @param  legalName the company's account legal name (optionally
895             *         <code>null</code>)
896             * @param  legalId the company's account legal ID (optionally
897             *         <code>null</code>)
898             * @param  legalType the company's account legal type (optionally
899             *         <code>null</code>)
900             * @param  sicCode the company's account SIC code (optionally
901             *         <code>null</code>)
902             * @param  tickerSymbol the company's account ticker symbol (optionally
903             *         <code>null</code>)
904             * @param  industry the company's account industry (optionally
905             *         <code>null</code>)
906             * @param  type the company's account type (optionally <code>null</code>)
907             * @param  size the company's account size (optionally <code>null</code>)
908             * @return the company with the primary key
909             * @throws PortalException if a company with the primary key could not be
910             *         found or if the new information was invalid
911             * @throws SystemException if a system exception occurred
912             */
913            public Company updateCompany(
914                            long companyId, String virtualHostname, String mx, String homeURL,
915                            String name, String legalName, String legalId, String legalType,
916                            String sicCode, String tickerSymbol, String industry, String type,
917                            String size)
918                    throws PortalException, SystemException {
919    
920                    // Company
921    
922                    virtualHostname = virtualHostname.trim().toLowerCase();
923                    Date now = new Date();
924    
925                    Company company = companyPersistence.findByPrimaryKey(companyId);
926    
927                    validate(company.getWebId(), virtualHostname, mx);
928                    validate(name);
929    
930                    if (PropsValues.MAIL_MX_UPDATE) {
931                            company.setMx(mx);
932                    }
933    
934                    company.setHomeURL(homeURL);
935    
936                    companyPersistence.update(company, false);
937    
938                    // Account
939    
940                    Account account = accountPersistence.fetchByPrimaryKey(
941                            company.getAccountId());
942    
943                    if (account == null) {
944                            long accountId = counterLocalService.increment();
945    
946                            account = accountPersistence.create(accountId);
947    
948                            account.setCreateDate(now);
949                            account.setCompanyId(companyId);
950                            account.setUserId(0);
951                            account.setUserName(StringPool.BLANK);
952    
953                            company.setAccountId(accountId);
954    
955                            companyPersistence.update(company, false);
956                    }
957    
958                    account.setModifiedDate(now);
959                    account.setName(name);
960                    account.setLegalName(legalName);
961                    account.setLegalId(legalId);
962                    account.setLegalType(legalType);
963                    account.setSicCode(sicCode);
964                    account.setTickerSymbol(tickerSymbol);
965                    account.setIndustry(industry);
966                    account.setType(type);
967                    account.setSize(size);
968    
969                    accountPersistence.update(account, false);
970    
971                    // Virtual host
972    
973                    updateVirtualHost(companyId, virtualHostname);
974    
975                    return company;
976            }
977    
978            /**
979             * Update the company's display.
980             *
981             * @param  companyId the primary key of the company
982             * @param  languageId the ID of the company's default user's language
983             * @param  timeZoneId the ID of the company's default user's time zone
984             * @throws PortalException if the company's default user could not be found
985             * @throws SystemException if a system exception occurred
986             */
987            public void updateDisplay(
988                            long companyId, String languageId, String timeZoneId)
989                    throws PortalException, SystemException {
990    
991                    User user = userLocalService.getDefaultUser(companyId);
992    
993                    user.setLanguageId(languageId);
994                    user.setTimeZoneId(timeZoneId);
995    
996                    userPersistence.update(user, false);
997            }
998    
999            /**
1000             * Updates the company's logo.
1001             *
1002             * @param  companyId the primary key of the company
1003             * @param  bytes the bytes of the company's logo image
1004             * @return the company with the primary key
1005             * @throws PortalException if the company's logo ID could not be found or if
1006             *         the logo's image was corrupted
1007             * @throws SystemException if a system exception occurred
1008             */
1009            public Company updateLogo(long companyId, byte[] bytes)
1010                    throws PortalException, SystemException {
1011    
1012                    Company company = checkLogo(companyId);
1013    
1014                    imageLocalService.updateImage(company.getLogoId(), bytes);
1015    
1016                    return company;
1017            }
1018    
1019            /**
1020             * Updates the company's logo.
1021             *
1022             * @param  companyId the primary key of the company
1023             * @param  file the file of the company's logo image
1024             * @return the company with the primary key
1025             * @throws PortalException the company's logo ID could not be found or if
1026             *         the logo's image was corrupted
1027             * @throws SystemException if a system exception occurred
1028             */
1029            public Company updateLogo(long companyId, File file)
1030                    throws PortalException, SystemException {
1031    
1032                    Company company = checkLogo(companyId);
1033    
1034                    imageLocalService.updateImage(company.getLogoId(), file);
1035    
1036                    return company;
1037            }
1038    
1039            /**
1040             * Update the company's logo.
1041             *
1042             * @param  companyId the primary key of the company
1043             * @param  is the input stream of the company's logo image
1044             * @return the company with the primary key
1045             * @throws PortalException if the company's logo ID could not be found or if
1046             *         the company's logo image was corrupted
1047             * @throws SystemException if a system exception occurred
1048             */
1049            public Company updateLogo(long companyId, InputStream is)
1050                    throws PortalException, SystemException {
1051    
1052                    Company company = checkLogo(companyId);
1053    
1054                    imageLocalService.updateImage(company.getLogoId(), is);
1055    
1056                    return company;
1057            }
1058    
1059            /**
1060             * Updates the company's preferences. The company's default properties are
1061             * found in portal.properties.
1062             *
1063             * @param  companyId the primary key of the company
1064             * @param  properties the company's properties. See {@link
1065             *         com.liferay.portal.kernel.util.UnicodeProperties}
1066             * @throws PortalException if the properties contained new locales that were
1067             *         not supported
1068             * @throws SystemException if a system exception occurred
1069             */
1070            public void updatePreferences(long companyId, UnicodeProperties properties)
1071                    throws PortalException, SystemException {
1072    
1073                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1074                            companyId);
1075    
1076                    try {
1077                            String newLocales = properties.getProperty(PropsKeys.LOCALES);
1078    
1079                            if (newLocales != null) {
1080                                    String oldLocales = preferences.getValue(
1081                                            PropsKeys.LOCALES, StringPool.BLANK);
1082    
1083                                    if (!Validator.equals(oldLocales, newLocales)) {
1084                                            validateLocales(newLocales);
1085    
1086                                            LanguageUtil.resetAvailableLocales(companyId);
1087                                    }
1088                            }
1089    
1090                            List<String> resetKeys = new ArrayList<String>();
1091    
1092                            for (Map.Entry<String, String> entry : properties.entrySet()) {
1093                                    String key = entry.getKey();
1094                                    String value = entry.getValue();
1095    
1096                                    if (value.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
1097                                            continue;
1098                                    }
1099    
1100                                    String propsUtilValue = PropsUtil.get(key);
1101    
1102                                    if (!value.equals(propsUtilValue)) {
1103                                            preferences.setValue(key, value);
1104                                    }
1105                                    else {
1106                                            String preferencesValue = preferences.getValue(key, null);
1107    
1108                                            if (preferencesValue != null) {
1109                                                    resetKeys.add(key);
1110                                            }
1111                                    }
1112                            }
1113    
1114                            for (String key : resetKeys) {
1115                                    preferences.reset(key);
1116                            }
1117    
1118                            preferences.store();
1119                    }
1120                    catch (LocaleException le) {
1121                            throw le;
1122                    }
1123                    catch (Exception e) {
1124                            throw new SystemException(e);
1125                    }
1126            }
1127    
1128            /**
1129             * Updates the company's security properties.
1130             *
1131             * @param  companyId the primary key of the company
1132             * @param  authType the company's method of authenticating users
1133             * @param  autoLogin whether to allow users to select the "remember me"
1134             *         feature
1135             * @param  sendPassword whether to allow users to ask the company to send
1136             *         their password
1137             * @param  strangers whether to allow strangers to create accounts register
1138             *         themselves in the company
1139             * @param  strangersWithMx whether to allow strangers to create accounts
1140             *         with email addresses that match the company mail suffix
1141             * @param  strangersVerify whether to require strangers who create accounts
1142             *         to be verified via email
1143             * @param  siteLogo whether to allow site administrators to use their own
1144             *         logo instead of the enterprise logo
1145             * @throws SystemException if a system exception occurred
1146             */
1147            public void updateSecurity(
1148                            long companyId, String authType, boolean autoLogin,
1149                            boolean sendPassword, boolean strangers, boolean strangersWithMx,
1150                            boolean strangersVerify, boolean siteLogo)
1151                    throws SystemException {
1152    
1153                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1154                            companyId);
1155    
1156                    try {
1157                            preferences.setValue(
1158                                    PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
1159                            preferences.setValue(
1160                                    PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
1161                                    String.valueOf(autoLogin));
1162                            preferences.setValue(
1163                                    PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
1164                                    String.valueOf(sendPassword));
1165                            preferences.setValue(
1166                                    PropsKeys.COMPANY_SECURITY_STRANGERS,
1167                                    String.valueOf(strangers));
1168                            preferences.setValue(
1169                                    PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
1170                                    String.valueOf(strangersWithMx));
1171                            preferences.setValue(
1172                                    PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
1173                                    String.valueOf(strangersVerify));
1174                            preferences.setValue(
1175                                    PropsKeys.COMPANY_SECURITY_SITE_LOGO, String.valueOf(siteLogo));
1176    
1177                            preferences.store();
1178                    }
1179                    catch (IOException ioe) {
1180                            throw new SystemException(ioe);
1181                    }
1182                    catch (PortletException pe) {
1183                            throw new SystemException(pe);
1184                    }
1185            }
1186    
1187            protected Company checkLogo(long companyId)
1188                    throws PortalException, SystemException {
1189    
1190                    Company company = companyPersistence.findByPrimaryKey(companyId);
1191    
1192                    long logoId = company.getLogoId();
1193    
1194                    if (logoId <= 0) {
1195                            logoId = counterLocalService.increment();
1196    
1197                            company.setLogoId(logoId);
1198    
1199                            company = companyPersistence.update(company, false);
1200                    }
1201    
1202                    return company;
1203            }
1204    
1205            protected void updateVirtualHost(long companyId, String virtualHostname)
1206                    throws CompanyVirtualHostException, SystemException {
1207    
1208                    if (Validator.isNotNull(virtualHostname)) {
1209                            try {
1210                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1211                                            virtualHostname);
1212    
1213                                    if ((virtualHost.getCompanyId() != companyId) ||
1214                                            (virtualHost.getLayoutSetId() != 0)) {
1215    
1216                                            throw new CompanyVirtualHostException();
1217                                    }
1218                            }
1219                            catch (NoSuchVirtualHostException nsvhe) {
1220                                    virtualHostLocalService.updateVirtualHost(
1221                                            companyId, 0, virtualHostname);
1222                            }
1223                    }
1224                    else {
1225                            try {
1226                                    virtualHostPersistence.removeByC_L(companyId, 0);
1227                            }
1228                            catch (NoSuchVirtualHostException nsvhe) {
1229                            }
1230                    }
1231            }
1232    
1233            protected void validate(String name) throws PortalException {
1234                    if (Validator.isNull(name)) {
1235                            throw new AccountNameException();
1236                    }
1237            }
1238    
1239            protected void validate(String webId, String virtualHostname, String mx)
1240                    throws PortalException, SystemException {
1241    
1242                    if (Validator.isNull(virtualHostname)) {
1243                            throw new CompanyVirtualHostException();
1244                    }
1245                    else if (virtualHostname.equals(_DEFAULT_VIRTUAL_HOST) &&
1246                                     !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
1247    
1248                            throw new CompanyVirtualHostException();
1249                    }
1250                    else if (!Validator.isDomain(virtualHostname)) {
1251                            throw new CompanyVirtualHostException();
1252                    }
1253                    else {
1254                            try {
1255                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1256                                            virtualHostname);
1257    
1258                                    long companyId = virtualHost.getCompanyId();
1259    
1260                                    Company virtualHostnameCompany =
1261                                            companyPersistence.findByPrimaryKey(companyId);
1262    
1263                                    if (!virtualHostnameCompany.getWebId().equals(webId)) {
1264                                            throw new CompanyVirtualHostException();
1265                                    }
1266                            }
1267                            catch (NoSuchVirtualHostException nsvhe) {
1268                            }
1269                    }
1270    
1271                    if (Validator.isNull(mx)) {
1272                            throw new CompanyMxException();
1273                    }
1274                    else if (!Validator.isDomain(mx)) {
1275                            throw new CompanyMxException();
1276                    }
1277            }
1278    
1279            protected void validateLocales(String locales) throws PortalException {
1280                    String[] localesArray = StringUtil.split(locales, StringPool.COMMA);
1281    
1282                    for (String locale : localesArray) {
1283                            if (!ArrayUtil.contains(PropsValues.LOCALES, locale)) {
1284                                    throw new LocaleException();
1285                            }
1286                    }
1287            }
1288    
1289            private static final String _DEFAULT_VIRTUAL_HOST = "localhost";
1290    
1291            private static Log _log = LogFactoryUtil.getLog(
1292                    CompanyLocalServiceImpl.class);
1293    
1294    }