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