001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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(
553                            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;
688             *         <code>0</code> 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
756             *         assets 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                            searchContext.setSearchEngineId(SearchEngineUtil.SYSTEM_ENGINE_ID);
798    
799                            BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(
800                                    searchContext);
801    
802                            contextQuery.addRequiredTerm(Field.COMPANY_ID, companyId);
803    
804                            if (Validator.isNotNull(portletId)) {
805                                    contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);
806                            }
807    
808                            if (groupId > 0) {
809                                    contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
810                            }
811    
812                            if (Validator.isNotNull(type)) {
813                                    contextQuery.addRequiredTerm(Field.TYPE, type);
814                            }
815    
816                            BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(
817                                    searchContext);
818    
819                            searchQuery.addTerms(_KEYWORDS_FIELDS, keywords);
820    
821                            BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(
822                                    searchContext);
823    
824                            fullQuery.add(contextQuery, BooleanClauseOccur.MUST);
825    
826                            if (searchQuery.clauses().size() > 0) {
827                                    fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
828                            }
829    
830                            return SearchEngineUtil.search(
831                                    companyId, new long[] {groupId}, userId, null, fullQuery, start,
832                                    end);
833                    }
834                    catch (Exception e) {
835                            throw new SystemException(e);
836                    }
837            }
838    
839            /**
840             * Updates the company.
841             *
842             * @param  companyId the primary key of the company
843             * @param  virtualHostname the company's virtual host name
844             * @param  mx the company's mail domain
845             * @param  maxUsers the max number of company users (optionally
846             *         <code>0</code>)
847             * @param  active whether the company is active
848             * @return the company with the primary key
849             * @throws PortalException if a company with primary key could not be found
850             *         or if the new information was invalid
851             * @throws SystemException if a system exception occurred
852             */
853            public Company updateCompany(
854                            long companyId, String virtualHostname, String mx, int maxUsers,
855                            boolean active)
856                    throws PortalException, SystemException {
857    
858                    // Company
859    
860                    virtualHostname = virtualHostname.trim().toLowerCase();
861    
862                    if (!active) {
863                            if (companyId == PortalInstances.getDefaultCompanyId()) {
864                                    active = true;
865                            }
866                    }
867    
868                    Company company = companyPersistence.findByPrimaryKey(companyId);
869    
870                    validate(company.getWebId(), virtualHostname, mx);
871    
872                    if (PropsValues.MAIL_MX_UPDATE) {
873                            company.setMx(mx);
874                    }
875    
876                    company.setMaxUsers(maxUsers);
877                    company.setActive(active);
878    
879                    companyPersistence.update(company, false);
880    
881                    // Virtual host
882    
883                    updateVirtualHost(companyId, virtualHostname);
884    
885                    return company;
886            }
887    
888            /**
889             * Update the company with additional account information.
890             *
891             * @param  companyId the primary key of the company
892             * @param  virtualHostname the company's virtual host name
893             * @param  mx the company's mail domain
894             * @param  homeURL the company's home URL (optionally <code>null</code>)
895             * @param  name the company's account name(optionally <code>null</code>)
896             * @param  legalName the company's account legal name (optionally
897             *         <code>null</code>)
898             * @param  legalId the company's account legal ID (optionally
899             *         <code>null</code>)
900             * @param  legalType the company's account legal type (optionally
901             *         <code>null</code>)
902             * @param  sicCode the company's account SIC code (optionally
903             *         <code>null</code>)
904             * @param  tickerSymbol the company's account ticker symbol (optionally
905             *         <code>null</code>)
906             * @param  industry the company's account industry (optionally
907             *         <code>null</code>)
908             * @param  type the company's account type (optionally <code>null</code>)
909             * @param  size the company's account size (optionally <code>null</code>)
910             * @return the company with the primary key
911             * @throws PortalException if a company with the primary key could not be
912             *         found or if the new information was invalid
913             * @throws SystemException if a system exception occurred
914             */
915            public Company updateCompany(
916                            long companyId, String virtualHostname, String mx, String homeURL,
917                            String name, String legalName, String legalId, String legalType,
918                            String sicCode, String tickerSymbol, String industry, String type,
919                            String size)
920                    throws PortalException, SystemException {
921    
922                    // Company
923    
924                    virtualHostname = virtualHostname.trim().toLowerCase();
925                    Date now = new Date();
926    
927                    Company company = companyPersistence.findByPrimaryKey(companyId);
928    
929                    validate(company.getWebId(), virtualHostname, mx);
930                    validate(name);
931    
932                    if (PropsValues.MAIL_MX_UPDATE) {
933                            company.setMx(mx);
934                    }
935    
936                    company.setHomeURL(homeURL);
937    
938                    companyPersistence.update(company, false);
939    
940                    // Account
941    
942                    Account account = accountPersistence.fetchByPrimaryKey(
943                            company.getAccountId());
944    
945                    if (account == null) {
946                            long accountId = counterLocalService.increment();
947    
948                            account = accountPersistence.create(accountId);
949    
950                            account.setCreateDate(now);
951                            account.setCompanyId(companyId);
952                            account.setUserId(0);
953                            account.setUserName(StringPool.BLANK);
954    
955                            company.setAccountId(accountId);
956    
957                            companyPersistence.update(company, false);
958                    }
959    
960                    account.setModifiedDate(now);
961                    account.setName(name);
962                    account.setLegalName(legalName);
963                    account.setLegalId(legalId);
964                    account.setLegalType(legalType);
965                    account.setSicCode(sicCode);
966                    account.setTickerSymbol(tickerSymbol);
967                    account.setIndustry(industry);
968                    account.setType(type);
969                    account.setSize(size);
970    
971                    accountPersistence.update(account, false);
972    
973                    // Virtual host
974    
975                    updateVirtualHost(companyId, virtualHostname);
976    
977                    return company;
978            }
979    
980            /**
981             * Update the company's display.
982             *
983             * @param  companyId the primary key of the company
984             * @param  languageId the ID of the company's default user's language
985             * @param  timeZoneId the ID of the company's default user's time zone
986             * @throws PortalException if the company's default user could not be found
987             * @throws SystemException if a system exception occurred
988             */
989            public void updateDisplay(
990                            long companyId, String languageId, String timeZoneId)
991                    throws PortalException, SystemException {
992    
993                    User user = userLocalService.getDefaultUser(companyId);
994    
995                    user.setLanguageId(languageId);
996                    user.setTimeZoneId(timeZoneId);
997    
998                    userPersistence.update(user, false);
999            }
1000    
1001            /**
1002             * Updates the company's logo.
1003             *
1004             * @param  companyId the primary key of the company
1005             * @param  bytes the bytes of the company's logo image
1006             * @throws PortalException if the company's logo ID could not be found or
1007             *         if the logo's image was corrupted
1008             * @throws SystemException if a system exception occurred
1009             */
1010            public void updateLogo(long companyId, byte[] bytes)
1011                    throws PortalException, SystemException {
1012    
1013                    long logoId = getLogoId(companyId);
1014    
1015                    imageLocalService.updateImage(logoId, bytes);
1016            }
1017    
1018            /**
1019             * Updates the company's logo.
1020             *
1021             * @param  companyId the primary key of the company
1022             * @param  file the file of the company's logo image
1023             * @throws PortalException the company's logo ID could not be found or if
1024             *         the logo's image was corrupted
1025             * @throws SystemException if a system exception occurred
1026             */
1027            public void updateLogo(long companyId, File file)
1028                    throws PortalException, SystemException {
1029    
1030                    long logoId = getLogoId(companyId);
1031    
1032                    imageLocalService.updateImage(logoId, file);
1033            }
1034    
1035            /**
1036             * Update the company's logo.
1037             *
1038             * @param  companyId the primary key of the company
1039             * @param  is the input stream of the company's logo image
1040             * @throws PortalException if the company's logo ID could not be found or
1041             *         if the company's logo image was corrupted
1042             * @throws SystemException if a system exception occurred
1043             */
1044            public void updateLogo(long companyId, InputStream is)
1045                    throws PortalException, SystemException {
1046    
1047                    long logoId = getLogoId(companyId);
1048    
1049                    imageLocalService.updateImage(logoId, is);
1050            }
1051    
1052            /**
1053             * Updates the company's preferences. The company's default properties are
1054             * found in portal.properties.
1055             *
1056             * @param  companyId the primary key of the company
1057             * @param  properties the company's properties. See {@link
1058             *         com.liferay.portal.kernel.util.UnicodeProperties}
1059             * @throws PortalException if the properties contained new locales that
1060             *         were not supported
1061             * @throws SystemException if a system exception occurred
1062             */
1063            public void updatePreferences(long companyId, UnicodeProperties properties)
1064                    throws PortalException, SystemException {
1065    
1066                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1067                            companyId);
1068    
1069                    try {
1070                            String newLocales = properties.getProperty(PropsKeys.LOCALES);
1071    
1072                            if (newLocales != null) {
1073                                    String oldLocales = preferences.getValue(
1074                                            PropsKeys.LOCALES, StringPool.BLANK);
1075    
1076                                    if (!Validator.equals(oldLocales, newLocales)) {
1077                                            validateLocales(newLocales);
1078    
1079                                            LanguageUtil.resetAvailableLocales(companyId);
1080                                    }
1081                            }
1082    
1083                            List<String> resetKeys = new ArrayList<String>();
1084    
1085                            for (Map.Entry<String, String> entry : properties.entrySet()) {
1086                                    String key = entry.getKey();
1087                                    String value = entry.getValue();
1088    
1089                                    if (value.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
1090                                            continue;
1091                                    }
1092    
1093                                    String propsUtilValue = PropsUtil.get(key);
1094    
1095                                    if (!value.equals(propsUtilValue)) {
1096                                            preferences.setValue(key, value);
1097                                    }
1098                                    else {
1099                                            String preferencesValue = preferences.getValue(key, null);
1100    
1101                                            if (preferencesValue != null) {
1102                                                    resetKeys.add(key);
1103                                            }
1104                                    }
1105                            }
1106    
1107                            for (String key : resetKeys) {
1108                                    preferences.reset(key);
1109                            }
1110    
1111                            preferences.store();
1112                    }
1113                    catch (LocaleException le) {
1114                            throw le;
1115                    }
1116                    catch (Exception e) {
1117                            throw new SystemException(e);
1118                    }
1119            }
1120    
1121            /**
1122             * Updates the company's security properties.
1123             *
1124             * @param  companyId the primary key of the company
1125             * @param  authType the company's method of authenticating users
1126             * @param  autoLogin whether to allow users to select the "remember me"
1127             *         feature
1128             * @param  sendPassword whether to allow users to ask the company to send
1129             *         their password
1130             * @param  strangers whether to allow strangers to create accounts register
1131             *         themselves in the company
1132             * @param  strangersWithMx whether to allow strangers to create accounts
1133             *         with email addresses that match the company mail suffix
1134             * @param  strangersVerify whether to require strangers who create accounts
1135             *         to be verified via email
1136             * @param  siteLogo whether to allow site administrators to use their own
1137             *         logo instead of the enterprise logo
1138             * @throws SystemException if a system exception occurred
1139             */
1140            public void updateSecurity(
1141                            long companyId, String authType, boolean autoLogin,
1142                            boolean sendPassword, boolean strangers, boolean strangersWithMx,
1143                            boolean strangersVerify, boolean siteLogo)
1144                    throws SystemException {
1145    
1146                    PortletPreferences preferences = PrefsPropsUtil.getPreferences(
1147                            companyId);
1148    
1149                    try {
1150                            preferences.setValue(
1151                                    PropsKeys.COMPANY_SECURITY_AUTH_TYPE, authType);
1152                            preferences.setValue(
1153                                    PropsKeys.COMPANY_SECURITY_AUTO_LOGIN,
1154                                    String.valueOf(autoLogin));
1155                            preferences.setValue(
1156                                    PropsKeys.COMPANY_SECURITY_SEND_PASSWORD,
1157                                    String.valueOf(sendPassword));
1158                            preferences.setValue(
1159                                    PropsKeys.COMPANY_SECURITY_STRANGERS,
1160                                    String.valueOf(strangers));
1161                            preferences.setValue(
1162                                    PropsKeys.COMPANY_SECURITY_STRANGERS_WITH_MX,
1163                                    String.valueOf(strangersWithMx));
1164                            preferences.setValue(
1165                                    PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY,
1166                                    String.valueOf(strangersVerify));
1167                            preferences.setValue(
1168                                    PropsKeys.COMPANY_SECURITY_SITE_LOGO,
1169                                    String.valueOf(siteLogo));
1170    
1171                            preferences.store();
1172                    }
1173                    catch (IOException ioe) {
1174                            throw new SystemException(ioe);
1175                    }
1176                    catch (PortletException pe) {
1177                            throw new SystemException(pe);
1178                    }
1179            }
1180    
1181            protected long getLogoId(long companyId)
1182                    throws PortalException, SystemException {
1183    
1184                    Company company = companyPersistence.findByPrimaryKey(companyId);
1185    
1186                    long logoId = company.getLogoId();
1187    
1188                    if (logoId <= 0) {
1189                            logoId = counterLocalService.increment();
1190    
1191                            company.setLogoId(logoId);
1192    
1193                            companyPersistence.update(company, false);
1194                    }
1195    
1196                    return logoId;
1197            }
1198    
1199            protected void updateVirtualHost(long companyId, String virtualHostname)
1200                    throws CompanyVirtualHostException, SystemException {
1201    
1202                    if (Validator.isNotNull(virtualHostname)) {
1203                            try {
1204                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1205                                            virtualHostname);
1206    
1207                                    if ((virtualHost.getCompanyId() != companyId) ||
1208                                            (virtualHost.getLayoutSetId() != 0)) {
1209    
1210                                            throw new CompanyVirtualHostException();
1211                                    }
1212                            }
1213                            catch (NoSuchVirtualHostException nsvhe) {
1214                                    virtualHostLocalService.updateVirtualHost(
1215                                            companyId, 0, virtualHostname);
1216                            }
1217                    }
1218                    else {
1219                            try {
1220                                    virtualHostPersistence.removeByC_L(companyId, 0);
1221                            }
1222                            catch (NoSuchVirtualHostException nsvhe) {
1223                            }
1224                    }
1225            }
1226    
1227            protected void validate(String name) throws PortalException {
1228                    if (Validator.isNull(name)) {
1229                            throw new AccountNameException();
1230                    }
1231            }
1232    
1233            protected void validate(String webId, String virtualHostname, String mx)
1234                    throws PortalException, SystemException {
1235    
1236                    if (Validator.isNull(virtualHostname)) {
1237                            throw new CompanyVirtualHostException();
1238                    }
1239                    else if (virtualHostname.equals(_DEFAULT_VIRTUAL_HOST) &&
1240                                     !webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
1241    
1242                            throw new CompanyVirtualHostException();
1243                    }
1244                    else if (!Validator.isDomain(virtualHostname)) {
1245                            throw new CompanyVirtualHostException();
1246                    }
1247                    else {
1248                            try {
1249                                    VirtualHost virtualHost = virtualHostPersistence.findByHostname(
1250                                            virtualHostname);
1251    
1252                                    long companyId = virtualHost.getCompanyId();
1253    
1254                                    Company virtualHostnameCompany =
1255                                            companyPersistence.findByPrimaryKey(companyId);
1256    
1257                                    if (!virtualHostnameCompany.getWebId().equals(webId)) {
1258                                            throw new CompanyVirtualHostException();
1259                                    }
1260                            }
1261                            catch (NoSuchVirtualHostException nsvhe) {
1262                            }
1263                    }
1264    
1265                    if (Validator.isNull(mx)) {
1266                            throw new CompanyMxException();
1267                    }
1268                    else if (!Validator.isDomain(mx)) {
1269                            throw new CompanyMxException();
1270                    }
1271            }
1272    
1273            protected void validateLocales(String locales) throws PortalException {
1274                    String[] localesArray = StringUtil.split(locales, StringPool.COMMA);
1275    
1276                    for (String locale : localesArray) {
1277                            if (!ArrayUtil.contains(PropsValues.LOCALES, locale)) {
1278                                    throw new LocaleException();
1279                            }
1280                    }
1281            }
1282    
1283            private static Log _log = LogFactoryUtil.getLog(
1284                    CompanyLocalServiceImpl.class);
1285    
1286            private static final String _DEFAULT_VIRTUAL_HOST = "localhost";
1287    
1288            private static final String[] _KEYWORDS_FIELDS = {
1289                    Field.ASSET_TAG_NAMES, Field.CONTENT, Field.DESCRIPTION,
1290                    Field.PROPERTIES, Field.TITLE
1291            };
1292    
1293    }