001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.util;
016    
017    import com.liferay.portal.events.EventsProcessorUtil;
018    import com.liferay.portal.kernel.dao.jdbc.DataAccess;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.search.SearchEngineUtil;
022    import com.liferay.portal.kernel.util.ArrayUtil;
023    import com.liferay.portal.kernel.util.CookieKeys;
024    import com.liferay.portal.kernel.util.GetterUtil;
025    import com.liferay.portal.kernel.util.HttpUtil;
026    import com.liferay.portal.kernel.util.PropsKeys;
027    import com.liferay.portal.kernel.util.SetUtil;
028    import com.liferay.portal.kernel.util.Validator;
029    import com.liferay.portal.model.Company;
030    import com.liferay.portal.model.Group;
031    import com.liferay.portal.model.LayoutSet;
032    import com.liferay.portal.model.PortletCategory;
033    import com.liferay.portal.model.User;
034    import com.liferay.portal.model.VirtualHost;
035    import com.liferay.portal.security.auth.CompanyThreadLocal;
036    import com.liferay.portal.security.auth.PrincipalThreadLocal;
037    import com.liferay.portal.security.exportimport.UserImporterUtil;
038    import com.liferay.portal.security.ldap.LDAPSettingsUtil;
039    import com.liferay.portal.service.CompanyLocalServiceUtil;
040    import com.liferay.portal.service.GroupLocalServiceUtil;
041    import com.liferay.portal.service.LayoutSetLocalServiceUtil;
042    import com.liferay.portal.service.PortletLocalServiceUtil;
043    import com.liferay.portal.service.UserLocalServiceUtil;
044    import com.liferay.portal.service.VirtualHostLocalServiceUtil;
045    
046    import java.sql.Connection;
047    import java.sql.PreparedStatement;
048    import java.sql.ResultSet;
049    import java.sql.SQLException;
050    
051    import java.util.ArrayList;
052    import java.util.List;
053    import java.util.Set;
054    
055    import javax.servlet.ServletContext;
056    import javax.servlet.http.HttpServletRequest;
057    
058    /**
059     * @author Brian Wing Shun Chan
060     * @author Jose Oliver
061     * @author Atul Patel
062     * @author Mika Koivisto
063     */
064    public class PortalInstances {
065    
066            public static void addCompanyId(long companyId) {
067                    _instance._addCompanyId(companyId);
068            }
069    
070            public static long getCompanyId(HttpServletRequest request) {
071                    return _instance._getCompanyId(request);
072            }
073    
074            public static long[] getCompanyIds() {
075                    return _instance._getCompanyIds();
076            }
077    
078            public static long[] getCompanyIdsBySQL() throws SQLException {
079                    return _instance._getCompanyIdsBySQL();
080            }
081    
082            public static long getDefaultCompanyId() {
083                    return _instance._getDefaultCompanyId();
084            }
085    
086            public static String[] getWebIds() {
087                    return _instance._getWebIds();
088            }
089    
090            public static long initCompany(
091                    ServletContext servletContext, String webId) {
092    
093                    return _instance._initCompany(servletContext, webId);
094            }
095    
096            public static boolean isAutoLoginIgnoreHost(String host) {
097                    return _instance._isAutoLoginIgnoreHost(host);
098            }
099    
100            public static boolean isAutoLoginIgnorePath(String path) {
101                    return _instance._isAutoLoginIgnorePath(path);
102            }
103    
104            public static boolean isCompanyActive(long companyId) {
105                    return _instance._isCompanyActive(companyId);
106            }
107    
108            public static boolean isVirtualHostsIgnoreHost(String host) {
109                    return _instance._isVirtualHostsIgnoreHost(host);
110            }
111    
112            public static boolean isVirtualHostsIgnorePath(String path) {
113                    return _instance._isVirtualHostsIgnorePath(path);
114            }
115    
116            public static void reload(ServletContext servletContext) {
117                    _instance._reload(servletContext);
118            }
119    
120            public static void removeCompany(long companyId) {
121                    _instance._removeCompanyId(companyId);
122            }
123    
124            private PortalInstances() {
125                    _companyIds = new long[0];
126                    _autoLoginIgnoreHosts = SetUtil.fromArray(
127                            PropsUtil.getArray(PropsKeys.AUTO_LOGIN_IGNORE_HOSTS));
128                    _autoLoginIgnorePaths = SetUtil.fromArray(
129                            PropsUtil.getArray(PropsKeys.AUTO_LOGIN_IGNORE_PATHS));
130                    _virtualHostsIgnoreHosts = SetUtil.fromArray(
131                            PropsUtil.getArray(PropsKeys.VIRTUAL_HOSTS_IGNORE_HOSTS));
132                    _virtualHostsIgnorePaths = SetUtil.fromArray(
133                            PropsUtil.getArray(PropsKeys.VIRTUAL_HOSTS_IGNORE_PATHS));
134            }
135    
136            private void _addCompanyId(long companyId) {
137                    if (ArrayUtil.contains(_companyIds, companyId)) {
138                            return;
139                    }
140    
141                    long[] companyIds = new long[_companyIds.length + 1];
142    
143                    System.arraycopy(_companyIds, 0, companyIds, 0, _companyIds.length);
144    
145                    companyIds[_companyIds.length] = companyId;
146    
147                    _companyIds = companyIds;
148            }
149    
150            private long _getCompanyId(HttpServletRequest request) {
151                    if (_log.isDebugEnabled()) {
152                            _log.debug("Get company id");
153                    }
154    
155                    Long companyIdObj = (Long)request.getAttribute(WebKeys.COMPANY_ID);
156    
157                    if (_log.isDebugEnabled()) {
158                            _log.debug("Company id from request " + companyIdObj);
159                    }
160    
161                    if (companyIdObj != null) {
162                            return companyIdObj.longValue();
163                    }
164    
165                    long companyId = _getCompanyIdByVirtualHosts(request);
166    
167                    if (_log.isDebugEnabled()) {
168                            _log.debug("Company id from host " + companyId);
169                    }
170    
171                    if (companyId <= 0) {
172                            long cookieCompanyId = GetterUtil.getLong(
173                                    CookieKeys.getCookie(request, CookieKeys.COMPANY_ID, false));
174    
175                            if (cookieCompanyId > 0) {
176                                    try {
177                                            if (CompanyLocalServiceUtil.fetchCompanyById(
178                                                            cookieCompanyId) == null) {
179    
180                                                    if (_log.isWarnEnabled()) {
181                                                            _log.warn(
182                                                                    "Company id from cookie " + cookieCompanyId +
183                                                                            " does not exist");
184                                                    }
185                                            }
186                                            else {
187                                                    companyId = cookieCompanyId;
188    
189                                                    if (_log.isDebugEnabled()) {
190                                                            _log.debug("Company id from cookie " + companyId);
191                                                    }
192                                            }
193                                    }
194                                    catch (Exception e) {
195                                            _log.error(e, e);
196                                    }
197                            }
198                    }
199    
200                    if (companyId <= 0) {
201                            companyId = _getDefaultCompanyId();
202    
203                            if (_log.isDebugEnabled()) {
204                                    _log.debug("Default company id " + companyId);
205                            }
206                    }
207    
208                    if (_log.isDebugEnabled()) {
209                            _log.debug("Set company id " + companyId);
210                    }
211    
212                    request.setAttribute(WebKeys.COMPANY_ID, Long.valueOf(companyId));
213    
214                    CompanyThreadLocal.setCompanyId(companyId);
215    
216                    if (Validator.isNotNull(PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME) &&
217                            (request.getAttribute(WebKeys.VIRTUAL_HOST_LAYOUT_SET) == null)) {
218    
219                            try {
220                                    Group group = GroupLocalServiceUtil.getGroup(
221                                            companyId, PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME);
222    
223                                    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(
224                                            group.getGroupId(), false);
225    
226                                    if (Validator.isNull(layoutSet.getVirtualHostname())) {
227                                            request.setAttribute(
228                                                    WebKeys.VIRTUAL_HOST_LAYOUT_SET, layoutSet);
229                                    }
230                            }
231                            catch (Exception e) {
232                                    _log.error(e, e);
233                            }
234                    }
235    
236                    return companyId;
237            }
238    
239            private long _getCompanyIdByVirtualHosts(HttpServletRequest request) {
240                    String host = PortalUtil.getHost(request);
241    
242                    if (_log.isDebugEnabled()) {
243                            _log.debug("Host " + host);
244                    }
245    
246                    if (Validator.isNull(host) || _isVirtualHostsIgnoreHost(host)) {
247                            return 0;
248                    }
249    
250                    try {
251                            VirtualHost virtualHost =
252                                    VirtualHostLocalServiceUtil.fetchVirtualHost(host);
253    
254                            if (virtualHost == null) {
255                                    return 0;
256                            }
257    
258                            if (virtualHost.getLayoutSetId() != 0) {
259                                    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(
260                                            virtualHost.getLayoutSetId());
261    
262                                    if (_log.isDebugEnabled()) {
263                                            _log.debug(
264                                                    "Company " + virtualHost.getCompanyId() +
265                                                            " is associated with layout set " +
266                                                                    virtualHost.getLayoutSetId());
267                                    }
268    
269                                    request.setAttribute(
270                                            WebKeys.VIRTUAL_HOST_LAYOUT_SET, layoutSet);
271                            }
272    
273                            return virtualHost.getCompanyId();
274                    }
275                    catch (Exception e) {
276                            _log.error(e, e);
277                    }
278    
279                    return 0;
280            }
281    
282            private long[] _getCompanyIds() {
283                    return _companyIds;
284            }
285    
286            private long[] _getCompanyIdsBySQL() throws SQLException {
287                    List<Long> companyIds = new ArrayList<>();
288    
289                    Connection con = null;
290                    PreparedStatement ps = null;
291                    ResultSet rs = null;
292    
293                    try {
294                            con = DataAccess.getConnection();
295    
296                            ps = con.prepareStatement(_GET_COMPANY_IDS);
297    
298                            rs = ps.executeQuery();
299    
300                            while (rs.next()) {
301                                    long companyId = rs.getLong("companyId");
302    
303                                    companyIds.add(companyId);
304                            }
305                    }
306                    finally {
307                            DataAccess.cleanUp(con, ps, rs);
308                    }
309    
310                    return ArrayUtil.toArray(
311                            companyIds.toArray(new Long[companyIds.size()]));
312            }
313    
314            private long _getDefaultCompanyId() {
315                    return _companyIds[0];
316            }
317    
318            private String[] _getWebIds() {
319                    if (_webIds != null) {
320                            return _webIds;
321                    }
322    
323                    if (Validator.isNull(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
324                            throw new RuntimeException("Default web id must not be null");
325                    }
326    
327                    try {
328                            List<Company> companies = CompanyLocalServiceUtil.getCompanies(
329                                    false);
330    
331                            List<String> webIdsList = new ArrayList<>(companies.size());
332    
333                            for (Company company : companies) {
334                                    String webId = company.getWebId();
335    
336                                    if (webId.equals(PropsValues.COMPANY_DEFAULT_WEB_ID)) {
337                                            webIdsList.add(0, webId);
338                                    }
339                                    else {
340                                            webIdsList.add(webId);
341                                    }
342                            }
343    
344                            _webIds = webIdsList.toArray(new String[webIdsList.size()]);
345                    }
346                    catch (Exception e) {
347                            _log.error(e, e);
348                    }
349    
350                    if (ArrayUtil.isEmpty(_webIds)) {
351                            _webIds = new String[] {PropsValues.COMPANY_DEFAULT_WEB_ID};
352                    }
353    
354                    return _webIds;
355            }
356    
357            private long _initCompany(ServletContext servletContext, String webId) {
358    
359                    // Begin initializing company
360    
361                    if (_log.isDebugEnabled()) {
362                            _log.debug("Begin initializing company with web id " + webId);
363                    }
364    
365                    long companyId = 0;
366    
367                    try {
368                            Company company = CompanyLocalServiceUtil.checkCompany(webId);
369    
370                            companyId = company.getCompanyId();
371                    }
372                    catch (Exception e) {
373                            _log.error(e, e);
374                    }
375    
376                    Long currentThreadCompanyId = CompanyThreadLocal.getCompanyId();
377    
378                    String currentThreadPrincipalName = PrincipalThreadLocal.getName();
379    
380                    try {
381                            CompanyThreadLocal.setCompanyId(companyId);
382    
383                            String principalName = null;
384    
385                            try {
386                                    User user = UserLocalServiceUtil.getUser(
387                                            PrincipalThreadLocal.getUserId());
388    
389                                    if (user.getCompanyId() == companyId) {
390                                            principalName = currentThreadPrincipalName;
391                                    }
392                            }
393                            catch (Exception e) {
394                            }
395    
396                            PrincipalThreadLocal.setName(principalName);
397    
398                            // Initialize display
399    
400                            if (_log.isDebugEnabled()) {
401                                    _log.debug("Initialize display");
402                            }
403    
404                            try {
405                                    String xml = HttpUtil.URLtoString(
406                                            servletContext.getResource("/WEB-INF/liferay-display.xml"));
407    
408                                    PortletCategory portletCategory = (PortletCategory)
409                                            WebAppPool.get(companyId, WebKeys.PORTLET_CATEGORY);
410    
411                                    if (portletCategory == null) {
412                                            portletCategory = new PortletCategory();
413                                    }
414    
415                                    PortletCategory newPortletCategory =
416                                            PortletLocalServiceUtil.getEARDisplay(xml);
417    
418                                    portletCategory.merge(newPortletCategory);
419    
420                                    for (int i = 0; i < _companyIds.length; i++) {
421                                            long currentCompanyId = _companyIds[i];
422    
423                                            PortletCategory currentPortletCategory =
424                                                    (PortletCategory)WebAppPool.get(
425                                                            currentCompanyId, WebKeys.PORTLET_CATEGORY);
426    
427                                            if (currentPortletCategory != null) {
428                                                    portletCategory.merge(currentPortletCategory);
429                                            }
430                                    }
431    
432                                    WebAppPool.put(
433                                            companyId, WebKeys.PORTLET_CATEGORY, portletCategory);
434                            }
435                            catch (Exception e) {
436                                    _log.error(e, e);
437                            }
438    
439                            // LDAP import
440    
441                            try {
442                                    if (LDAPSettingsUtil.isImportOnStartup(companyId)) {
443                                            UserImporterUtil.importUsers(companyId);
444                                    }
445                            }
446                            catch (Exception e) {
447                                    _log.error(e, e);
448                            }
449    
450                            // Process application startup events
451    
452                            if (_log.isDebugEnabled()) {
453                                    _log.debug("Process application startup events");
454                            }
455    
456                            try {
457                                    EventsProcessorUtil.process(
458                                            PropsKeys.APPLICATION_STARTUP_EVENTS,
459                                            PropsValues.APPLICATION_STARTUP_EVENTS,
460                                            new String[] {String.valueOf(companyId)});
461                            }
462                            catch (Exception e) {
463                                    _log.error(e, e);
464                            }
465    
466                            // End initializing company
467    
468                            if (_log.isDebugEnabled()) {
469                                    _log.debug(
470                                            "End initializing company with web id " + webId +
471                                                    " and company id " + companyId);
472                            }
473    
474                            addCompanyId(companyId);
475                    }
476                    finally {
477                            CompanyThreadLocal.setCompanyId(currentThreadCompanyId);
478    
479                            PrincipalThreadLocal.setName(currentThreadPrincipalName);
480                    }
481    
482                    return companyId;
483            }
484    
485            private boolean _isAutoLoginIgnoreHost(String host) {
486                    return _autoLoginIgnoreHosts.contains(host);
487            }
488    
489            private boolean _isAutoLoginIgnorePath(String path) {
490                    return _autoLoginIgnorePaths.contains(path);
491            }
492    
493            private boolean _isCompanyActive(long companyId) {
494                    try {
495                            Company company = CompanyLocalServiceUtil.fetchCompanyById(
496                                    companyId);
497    
498                            if (company != null) {
499                                    return company.isActive();
500                            }
501                    }
502                    catch (Exception e) {
503                            _log.error(e, e);
504                    }
505    
506                    return false;
507            }
508    
509            private boolean _isVirtualHostsIgnoreHost(String host) {
510                    return _virtualHostsIgnoreHosts.contains(host);
511            }
512    
513            private boolean _isVirtualHostsIgnorePath(String path) {
514                    return _virtualHostsIgnorePaths.contains(path);
515            }
516    
517            private void _reload(ServletContext servletContext) {
518                    _companyIds = new long[0];
519                    _webIds = null;
520    
521                    String[] webIds = _getWebIds();
522    
523                    for (String webId : webIds) {
524                            _initCompany(servletContext, webId);
525                    }
526            }
527    
528            private void _removeCompanyId(long companyId) {
529                    _companyIds = ArrayUtil.remove(_companyIds, companyId);
530                    _webIds = null;
531    
532                    _getWebIds();
533    
534                    SearchEngineUtil.removeCompany(companyId);
535    
536                    WebAppPool.remove(companyId, WebKeys.PORTLET_CATEGORY);
537            }
538    
539            private static final String _GET_COMPANY_IDS =
540                    "select companyId from Company";
541    
542            private static final Log _log = LogFactoryUtil.getLog(
543                    PortalInstances.class);
544    
545            private static final PortalInstances _instance = new PortalInstances();
546    
547            private final Set<String> _autoLoginIgnoreHosts;
548            private final Set<String> _autoLoginIgnorePaths;
549            private long[] _companyIds;
550            private final Set<String> _virtualHostsIgnoreHosts;
551            private final Set<String> _virtualHostsIgnorePaths;
552            private String[] _webIds;
553    
554    }