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.servlet;
016    
017    import com.liferay.portal.NoSuchLayoutException;
018    import com.liferay.portal.events.EventsProcessorUtil;
019    import com.liferay.portal.events.StartupAction;
020    import com.liferay.portal.events.StartupHelperUtil;
021    import com.liferay.portal.kernel.cache.thread.local.Lifecycle;
022    import com.liferay.portal.kernel.cache.thread.local.ThreadLocalCacheManager;
023    import com.liferay.portal.kernel.deploy.hot.HotDeployUtil;
024    import com.liferay.portal.kernel.exception.PortalException;
025    import com.liferay.portal.kernel.language.LanguageUtil;
026    import com.liferay.portal.kernel.log.Log;
027    import com.liferay.portal.kernel.log.LogFactoryUtil;
028    import com.liferay.portal.kernel.module.framework.ModuleServiceLifecycle;
029    import com.liferay.portal.kernel.patcher.PatchInconsistencyException;
030    import com.liferay.portal.kernel.patcher.PatcherUtil;
031    import com.liferay.portal.kernel.plugin.PluginPackage;
032    import com.liferay.portal.kernel.servlet.DynamicServletRequest;
033    import com.liferay.portal.kernel.servlet.PortalSessionThreadLocal;
034    import com.liferay.portal.kernel.template.TemplateConstants;
035    import com.liferay.portal.kernel.template.TemplateManager;
036    import com.liferay.portal.kernel.util.ClassLoaderUtil;
037    import com.liferay.portal.kernel.util.ContentTypes;
038    import com.liferay.portal.kernel.util.GetterUtil;
039    import com.liferay.portal.kernel.util.HttpUtil;
040    import com.liferay.portal.kernel.util.InstanceFactory;
041    import com.liferay.portal.kernel.util.ParamUtil;
042    import com.liferay.portal.kernel.util.PortalLifecycleUtil;
043    import com.liferay.portal.kernel.util.PropsKeys;
044    import com.liferay.portal.kernel.util.ReleaseInfo;
045    import com.liferay.portal.kernel.util.StringPool;
046    import com.liferay.portal.kernel.util.StringUtil;
047    import com.liferay.portal.kernel.util.Validator;
048    import com.liferay.portal.kernel.util.WebKeys;
049    import com.liferay.portal.kernel.xml.Document;
050    import com.liferay.portal.kernel.xml.DocumentException;
051    import com.liferay.portal.kernel.xml.Element;
052    import com.liferay.portal.kernel.xml.UnsecureSAXReaderUtil;
053    import com.liferay.portal.model.Company;
054    import com.liferay.portal.model.Group;
055    import com.liferay.portal.model.GroupConstants;
056    import com.liferay.portal.model.Layout;
057    import com.liferay.portal.model.LayoutConstants;
058    import com.liferay.portal.model.LayoutTemplate;
059    import com.liferay.portal.model.Portlet;
060    import com.liferay.portal.model.PortletApp;
061    import com.liferay.portal.model.PortletFilter;
062    import com.liferay.portal.model.PortletURLListener;
063    import com.liferay.portal.model.Theme;
064    import com.liferay.portal.model.User;
065    import com.liferay.portal.plugin.PluginPackageUtil;
066    import com.liferay.portal.security.auth.CompanyThreadLocal;
067    import com.liferay.portal.security.auth.PrincipalException;
068    import com.liferay.portal.security.ldap.LDAPSettings;
069    import com.liferay.portal.security.permission.ResourceActionsUtil;
070    import com.liferay.portal.server.capabilities.ServerCapabilitiesUtil;
071    import com.liferay.portal.service.CompanyLocalServiceUtil;
072    import com.liferay.portal.service.GroupLocalServiceUtil;
073    import com.liferay.portal.service.LayoutLocalServiceUtil;
074    import com.liferay.portal.service.LayoutTemplateLocalServiceUtil;
075    import com.liferay.portal.service.PortletLocalServiceUtil;
076    import com.liferay.portal.service.ResourceActionLocalServiceUtil;
077    import com.liferay.portal.service.ThemeLocalServiceUtil;
078    import com.liferay.portal.service.UserLocalServiceUtil;
079    import com.liferay.portal.servlet.filters.absoluteredirects.AbsoluteRedirectsResponse;
080    import com.liferay.portal.servlet.filters.i18n.I18nFilter;
081    import com.liferay.portal.setup.SetupWizardSampleDataUtil;
082    import com.liferay.portal.struts.PortletRequestProcessor;
083    import com.liferay.portal.struts.StrutsUtil;
084    import com.liferay.portal.util.ExtRegistry;
085    import com.liferay.portal.util.MaintenanceUtil;
086    import com.liferay.portal.util.PortalInstances;
087    import com.liferay.portal.util.PortalUtil;
088    import com.liferay.portal.util.PropsUtil;
089    import com.liferay.portal.util.PropsValues;
090    import com.liferay.portal.util.ShutdownUtil;
091    import com.liferay.portlet.PortletBagFactory;
092    import com.liferay.portlet.PortletConfigFactoryUtil;
093    import com.liferay.portlet.PortletFilterFactory;
094    import com.liferay.portlet.PortletInstanceFactoryUtil;
095    import com.liferay.portlet.PortletURLListenerFactory;
096    import com.liferay.portlet.social.util.SocialConfigurationUtil;
097    import com.liferay.registry.Filter;
098    import com.liferay.registry.Registry;
099    import com.liferay.registry.RegistryUtil;
100    import com.liferay.registry.ServiceRegistration;
101    import com.liferay.registry.dependency.ServiceDependencyListener;
102    import com.liferay.registry.dependency.ServiceDependencyManager;
103    import com.liferay.util.ContentUtil;
104    import com.liferay.util.servlet.EncryptedServletRequest;
105    
106    import java.io.IOException;
107    import java.io.PrintWriter;
108    
109    import java.util.ArrayList;
110    import java.util.HashMap;
111    import java.util.List;
112    import java.util.Locale;
113    import java.util.Map;
114    import java.util.Set;
115    
116    import javax.portlet.PortletConfig;
117    import javax.portlet.PortletContext;
118    import javax.portlet.PortletException;
119    
120    import javax.servlet.RequestDispatcher;
121    import javax.servlet.ServletContext;
122    import javax.servlet.ServletException;
123    import javax.servlet.http.HttpServletRequest;
124    import javax.servlet.http.HttpServletResponse;
125    import javax.servlet.http.HttpSession;
126    import javax.servlet.jsp.PageContext;
127    
128    import org.apache.struts.Globals;
129    import org.apache.struts.action.ActionServlet;
130    import org.apache.struts.action.RequestProcessor;
131    import org.apache.struts.config.ControllerConfig;
132    import org.apache.struts.config.ModuleConfig;
133    import org.apache.struts.tiles.TilesUtilImpl;
134    
135    /**
136     * @author Brian Wing Shun Chan
137     * @author Jorge Ferrer
138     * @author Brian Myunghun Kim
139     */
140    public class MainServlet extends ActionServlet {
141    
142            @Override
143            public void destroy() {
144                    if (_log.isDebugEnabled()) {
145                            _log.debug("Destroy plugins");
146                    }
147    
148                    _moduleServiceLifecycleServiceRegistration.unregister();
149                    _servletContextServiceRegistration.unregister();
150    
151                    PortalLifecycleUtil.flushDestroys();
152    
153                    List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
154    
155                    if (_log.isDebugEnabled()) {
156                            _log.debug("Destroy portlets");
157                    }
158    
159                    try {
160                            destroyPortlets(portlets);
161                    }
162                    catch (Exception e) {
163                            _log.error(e, e);
164                    }
165    
166                    if (_log.isDebugEnabled()) {
167                            _log.debug("Destroy companies");
168                    }
169    
170                    try {
171                            destroyCompanies();
172                    }
173                    catch (Exception e) {
174                            _log.error(e, e);
175                    }
176    
177                    if (_log.isDebugEnabled()) {
178                            _log.debug("Process global shutdown events");
179                    }
180    
181                    try {
182                            processGlobalShutdownEvents();
183                    }
184                    catch (Exception e) {
185                            _log.error(e, e);
186                    }
187    
188                    if (_log.isDebugEnabled()) {
189                            _log.debug("Destroy");
190                    }
191    
192                    callParentDestroy();
193            }
194    
195            @Override
196            public void init() throws ServletException {
197                    if (_log.isDebugEnabled()) {
198                            _log.debug("Initialize");
199                    }
200    
201                    ServletContext servletContext = getServletContext();
202    
203                    servletContext.setAttribute(MainServlet.class.getName(), Boolean.TRUE);
204    
205                    callParentInit();
206    
207                    if (_log.isDebugEnabled()) {
208                            _log.debug("Verify patch levels");
209                    }
210    
211                    try {
212                            PatcherUtil.verifyPatchLevels();
213                    }
214                    catch (PatchInconsistencyException pie) {
215                            if (!PropsValues.VERIFY_PATCH_LEVELS_DISABLED) {
216                                    _log.error(
217                                            "Stopping the server due to the inconsistent patch levels");
218    
219                                    if (_log.isWarnEnabled()) {
220                                            _log.warn(
221                                                    "Set the property \"verify.patch.levels.disabled\" " +
222                                                            "to override stopping the server due to the " +
223                                                                    "inconsistent patch levels");
224                                    }
225    
226                                    System.exit(0);
227                            }
228                    }
229    
230                    if (_log.isDebugEnabled()) {
231                            _log.debug("Process startup events");
232                    }
233    
234                    try {
235                            processStartupEvents();
236                    }
237                    catch (Exception e) {
238                            _log.error(e, e);
239    
240                            System.out.println(
241                                    "Stopping the server due to unexpected startup errors");
242    
243                            System.exit(0);
244                    }
245    
246                    if (_log.isDebugEnabled()) {
247                            _log.debug("Initialize server detector");
248                    }
249    
250                    try {
251                            initServerDetector();
252                    }
253                    catch (Exception e) {
254                            _log.error(e, e);
255                    }
256    
257                    if (_log.isDebugEnabled()) {
258                            _log.debug("Initialize plugin package");
259                    }
260    
261                    PluginPackage pluginPackage = null;
262    
263                    try {
264                            pluginPackage = initPluginPackage();
265                    }
266                    catch (Exception e) {
267                            _log.error(e, e);
268                    }
269    
270                    if (_log.isDebugEnabled()) {
271                            _log.debug("Initialize portlets");
272                    }
273    
274                    List<Portlet> portlets = new ArrayList<>();
275    
276                    try {
277                            portlets.addAll(initPortlets(pluginPackage));
278                    }
279                    catch (Exception e) {
280                            _log.error(e, e);
281                    }
282    
283                    try {
284                            initLayoutTemplates(pluginPackage);
285                    }
286                    catch (Exception e) {
287                            _log.error(e, e);
288                    }
289    
290                    if (_log.isDebugEnabled()) {
291                            _log.debug("Initialize social");
292                    }
293    
294                    try {
295                            initSocial(pluginPackage);
296                    }
297                    catch (Exception e) {
298                            _log.error(e, e);
299                    }
300    
301                    if (_log.isDebugEnabled()) {
302                            _log.debug("Initialize themes");
303                    }
304    
305                    try {
306                            initThemes(pluginPackage, portlets);
307                    }
308                    catch (Exception e) {
309                            _log.error(e, e);
310                    }
311    
312                    if (_log.isDebugEnabled()) {
313                            _log.debug("Initialize web settings");
314                    }
315    
316                    try {
317                            initWebSettings();
318                    }
319                    catch (Exception e) {
320                            _log.error(e, e);
321                    }
322    
323                    if (_log.isDebugEnabled()) {
324                            _log.debug("Initialize extension environment");
325                    }
326    
327                    try {
328                            initExt();
329                    }
330                    catch (Exception e) {
331                            _log.error(e, e);
332                    }
333    
334                    if (_log.isDebugEnabled()) {
335                            _log.debug("Process global startup events");
336                    }
337    
338                    try {
339                            processGlobalStartupEvents();
340                    }
341                    catch (Exception e) {
342                            _log.error(e, e);
343                    }
344    
345                    if (_log.isDebugEnabled()) {
346                            _log.debug("Initialize resource actions");
347                    }
348    
349                    try {
350                            initResourceActions(portlets);
351                    }
352                    catch (Exception e) {
353                            _log.error(e, e);
354                    }
355    
356                    try {
357                            initCompanies();
358                    }
359                    catch (Exception e) {
360                            _log.error(e, e);
361                    }
362    
363                    if (StartupHelperUtil.isDBNew() &&
364                            PropsValues.SETUP_WIZARD_ADD_SAMPLE_DATA) {
365    
366                            try {
367                                    SetupWizardSampleDataUtil.addSampleData(
368                                            PortalInstances.getDefaultCompanyId());
369                            }
370                            catch (Exception e) {
371                                    _log.error(e, e);
372                            }
373                    }
374    
375                    if (_log.isDebugEnabled()) {
376                            _log.debug("Initialize plugins");
377                    }
378    
379                    try {
380                            initPlugins();
381                    }
382                    catch (Exception e) {
383                            _log.error(e, e);
384                    }
385    
386                    servletContext.setAttribute(WebKeys.STARTUP_FINISHED, true);
387    
388                    StartupHelperUtil.setStartupFinished(true);
389    
390                    registerPortalInitialized();
391    
392                    ThreadLocalCacheManager.clearAll(Lifecycle.REQUEST);
393            }
394    
395            @Override
396            public void service(
397                            HttpServletRequest request, HttpServletResponse response)
398                    throws IOException, ServletException {
399    
400                    if (_log.isDebugEnabled()) {
401                            _log.debug("Process service request");
402                    }
403    
404                    if (processShutdownRequest(request, response)) {
405                            if (_log.isDebugEnabled()) {
406                                    _log.debug("Processed shutdown request");
407                            }
408    
409                            return;
410                    }
411    
412                    if (processMaintenanceRequest(request, response)) {
413                            if (_log.isDebugEnabled()) {
414                                    _log.debug("Processed maintenance request");
415                            }
416    
417                            return;
418                    }
419    
420                    if (_log.isDebugEnabled()) {
421                            _log.debug("Get company id");
422                    }
423    
424                    long companyId = getCompanyId(request);
425    
426                    if (processCompanyInactiveRequest(request, response, companyId)) {
427                            if (_log.isDebugEnabled()) {
428                                    _log.debug("Processed company inactive request");
429                            }
430    
431                            return;
432                    }
433    
434                    try {
435                            if (processGroupInactiveRequest(request, response)) {
436                                    if (_log.isDebugEnabled()) {
437                                            _log.debug("Processed site inactive request");
438                                    }
439    
440                                    return;
441                            }
442                    }
443                    catch (Exception e) {
444                            if (e instanceof NoSuchLayoutException) {
445                                    if (_log.isDebugEnabled()) {
446                                            _log.debug(e, e);
447                                    }
448                            }
449                            else {
450                                    _log.error(e, e);
451                            }
452                    }
453    
454                    if (_log.isDebugEnabled()) {
455                            _log.debug("Set portal port");
456                    }
457    
458                    setPortalInetSocketAddresses(request);
459    
460                    if (_log.isDebugEnabled()) {
461                            _log.debug("Check variables");
462                    }
463    
464                    checkServletContext(request);
465                    checkPortletRequestProcessor(request);
466                    checkTilesDefinitionsFactory();
467    
468                    if (_log.isDebugEnabled()) {
469                            _log.debug("Handle non-serializable request");
470                    }
471    
472                    if (_log.isDebugEnabled()) {
473                            _log.debug("Encrypt request");
474                    }
475    
476                    request = encryptRequest(request, companyId);
477    
478                    long userId = getUserId(request);
479    
480                    String remoteUser = getRemoteUser(request, userId);
481    
482                    try {
483                            if (_log.isDebugEnabled()) {
484                                    _log.debug(
485                                            "Authenticate user id " + userId + " and remote user " +
486                                                    remoteUser);
487                            }
488    
489                            userId = loginUser(
490                                    request, response, companyId, userId, remoteUser);
491    
492                            if (_log.isDebugEnabled()) {
493                                    _log.debug("Authenticated user id " + userId);
494                            }
495                    }
496                    catch (Exception e) {
497                            _log.error(e, e);
498                    }
499    
500                    if (_log.isDebugEnabled()) {
501                            _log.debug("Set session thread local");
502                    }
503    
504                    PortalSessionThreadLocal.setHttpSession(request.getSession());
505    
506                    if (_log.isDebugEnabled()) {
507                            _log.debug("Process service pre events");
508                    }
509    
510                    if (processServicePre(request, response, userId)) {
511                            if (_log.isDebugEnabled()) {
512                                    _log.debug("Processing service pre events has errors");
513                            }
514    
515                            return;
516                    }
517    
518                    if (hasAbsoluteRedirect(request)) {
519                            if (_log.isDebugEnabled()) {
520                                    String currentURL = PortalUtil.getCurrentURL(request);
521    
522                                    _log.debug(
523                                            "Current URL " + currentURL + " has absolute redirect");
524                            }
525    
526                            return;
527                    }
528    
529                    if (!hasThemeDisplay(request)) {
530                            if (_log.isDebugEnabled()) {
531                                    String currentURL = PortalUtil.getCurrentURL(request);
532    
533                                    _log.debug(
534                                            "Current URL " + currentURL +
535                                                    " does not have a theme display");
536                            }
537    
538                            return;
539                    }
540    
541                    try {
542                            if (_log.isDebugEnabled()) {
543                                    _log.debug("Call parent service");
544                            }
545    
546                            callParentService(request, response);
547                    }
548                    finally {
549                            if (_log.isDebugEnabled()) {
550                                    _log.debug("Process service post events");
551                            }
552    
553                            processServicePost(request, response);
554                    }
555            }
556    
557            protected void callParentDestroy() {
558                    super.destroy();
559            }
560    
561            protected void callParentInit() throws ServletException {
562                    super.init();
563            }
564    
565            protected void callParentService(
566                            HttpServletRequest request, HttpServletResponse response)
567                    throws IOException, ServletException {
568    
569                    super.service(request, response);
570            }
571    
572            protected void checkPortletRequestProcessor(HttpServletRequest request)
573                    throws ServletException {
574    
575                    ServletContext servletContext = getServletContext();
576    
577                    PortletRequestProcessor portletReqProcessor =
578                            (PortletRequestProcessor)servletContext.getAttribute(
579                                    WebKeys.PORTLET_STRUTS_PROCESSOR);
580    
581                    if (portletReqProcessor == null) {
582                            ModuleConfig moduleConfig = getModuleConfig(request);
583    
584                            portletReqProcessor = PortletRequestProcessor.getInstance(
585                                    this, moduleConfig);
586    
587                            servletContext.setAttribute(
588                                    WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
589                    }
590            }
591    
592            protected void checkServletContext(HttpServletRequest request) {
593                    ServletContext servletContext = getServletContext();
594    
595                    request.setAttribute(WebKeys.CTX, servletContext);
596    
597                    String contextPath = request.getContextPath();
598    
599                    servletContext.setAttribute(WebKeys.CTX_PATH, contextPath);
600            }
601    
602            protected void checkTilesDefinitionsFactory() {
603                    ServletContext servletContext = getServletContext();
604    
605                    if (servletContext.getAttribute(
606                                    TilesUtilImpl.DEFINITIONS_FACTORY) != null) {
607    
608                            return;
609                    }
610    
611                    servletContext.setAttribute(
612                            TilesUtilImpl.DEFINITIONS_FACTORY,
613                            servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
614            }
615    
616            protected void checkWebSettings(String xml) throws DocumentException {
617                    Document doc = UnsecureSAXReaderUtil.read(xml);
618    
619                    Element root = doc.getRootElement();
620    
621                    int timeout = PropsValues.SESSION_TIMEOUT;
622    
623                    Element sessionConfig = root.element("session-config");
624    
625                    if (sessionConfig != null) {
626                            String sessionTimeout = sessionConfig.elementText(
627                                    "session-timeout");
628    
629                            timeout = GetterUtil.getInteger(sessionTimeout, timeout);
630                    }
631    
632                    PropsUtil.set(PropsKeys.SESSION_TIMEOUT, String.valueOf(timeout));
633    
634                    PropsValues.SESSION_TIMEOUT = timeout;
635    
636                    I18nServlet.setLanguageIds(root);
637                    I18nFilter.setLanguageIds(I18nServlet.getLanguageIds());
638            }
639    
640            protected void destroyCompanies() throws Exception {
641                    long[] companyIds = PortalInstances.getCompanyIds();
642    
643                    for (long companyId : companyIds) {
644                            destroyCompany(companyId);
645                    }
646            }
647    
648            protected void destroyCompany(long companyId) {
649                    if (_log.isDebugEnabled()) {
650                            _log.debug("Process shutdown events");
651                    }
652    
653                    try {
654                            EventsProcessorUtil.process(
655                                    PropsKeys.APPLICATION_SHUTDOWN_EVENTS,
656                                    PropsValues.APPLICATION_SHUTDOWN_EVENTS,
657                                    new String[] {String.valueOf(companyId)});
658                    }
659                    catch (Exception e) {
660                            _log.error(e, e);
661                    }
662            }
663    
664            protected void destroyPortlets(List<Portlet> portlets) throws Exception {
665                    for (Portlet portlet : portlets) {
666                            PortletInstanceFactoryUtil.destroy(portlet);
667    
668                            Map<String, PortletFilter> portletFilters =
669                                    portlet.getPortletFilters();
670    
671                            for (PortletFilter portletFilter : portletFilters.values()) {
672                                    PortletFilterFactory.destroy(portletFilter);
673                            }
674                    }
675            }
676    
677            protected HttpServletRequest encryptRequest(
678                    HttpServletRequest request, long companyId) {
679    
680                    boolean encryptRequest = ParamUtil.getBoolean(request, WebKeys.ENCRYPT);
681    
682                    if (!encryptRequest) {
683                            return request;
684                    }
685    
686                    try {
687                            Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
688    
689                            request = new EncryptedServletRequest(request, company.getKeyObj());
690                    }
691                    catch (Exception e) {
692                    }
693    
694                    return request;
695            }
696    
697            protected long getCompanyId(HttpServletRequest request) {
698                    return PortalInstances.getCompanyId(request);
699            }
700    
701            protected String getRemoteUser(HttpServletRequest request, long userId) {
702                    String remoteUser = request.getRemoteUser();
703    
704                    if (!PropsValues.PORTAL_JAAS_ENABLE) {
705                            HttpSession session = request.getSession();
706    
707                            String jRemoteUser = (String)session.getAttribute("j_remoteuser");
708    
709                            if (jRemoteUser != null) {
710                                    remoteUser = jRemoteUser;
711    
712                                    session.removeAttribute("j_remoteuser");
713                            }
714                    }
715    
716                    if ((userId > 0) && (remoteUser == null)) {
717                            remoteUser = String.valueOf(userId);
718                    }
719    
720                    return remoteUser;
721            }
722    
723            @Override
724            protected synchronized RequestProcessor getRequestProcessor(
725                            ModuleConfig moduleConfig)
726                    throws ServletException {
727    
728                    ServletContext servletContext = getServletContext();
729    
730                    String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();
731    
732                    RequestProcessor requestProcessor =
733                            (RequestProcessor)servletContext.getAttribute(key);
734    
735                    if (requestProcessor == null) {
736                            ControllerConfig controllerConfig =
737                                    moduleConfig.getControllerConfig();
738    
739                            try {
740                                    requestProcessor =
741                                            (RequestProcessor)InstanceFactory.newInstance(
742                                                    ClassLoaderUtil.getPortalClassLoader(),
743                                                    controllerConfig.getProcessorClass());
744                            }
745                            catch (Exception e) {
746                                    throw new ServletException(e);
747                            }
748    
749                            requestProcessor.init(this, moduleConfig);
750    
751                            servletContext.setAttribute(key, requestProcessor);
752                    }
753    
754                    return requestProcessor;
755            }
756    
757            protected long getUserId(HttpServletRequest request) {
758                    return PortalUtil.getUserId(request);
759            }
760    
761            protected boolean hasAbsoluteRedirect(HttpServletRequest request) {
762                    if (request.getAttribute(
763                                    AbsoluteRedirectsResponse.class.getName()) == null) {
764    
765                            return false;
766                    }
767                    else {
768                            return true;
769                    }
770            }
771    
772            protected boolean hasThemeDisplay(HttpServletRequest request) {
773                    if (request.getAttribute(WebKeys.THEME_DISPLAY) == null) {
774                            return false;
775                    }
776                    else {
777                            return true;
778                    }
779            }
780    
781            protected void initCompanies() throws Exception {
782                    ServiceDependencyManager serviceDependencyManager =
783                            new ServiceDependencyManager();
784    
785                    serviceDependencyManager.addServiceDependencyListener(
786                            new ServiceDependencyListener() {
787    
788                                    @Override
789                                    public void dependenciesFulfilled() {
790                                            try {
791                                                    if (_log.isDebugEnabled()) {
792                                                            _log.debug("Initialize companies");
793                                                    }
794    
795                                                    ServletContext servletContext = getServletContext();
796    
797                                                    try {
798                                                            String[] webIds = PortalInstances.getWebIds();
799    
800                                                            for (String webId : webIds) {
801                                                                    PortalInstances.initCompany(
802                                                                            servletContext, webId);
803                                                            }
804                                                    }
805                                                    finally {
806                                                            CompanyThreadLocal.setCompanyId(
807                                                                    PortalInstances.getDefaultCompanyId());
808                                                    }
809                                            }
810                                            catch (Exception e) {
811                                                    _log.error(e, e);
812                                            }
813                                    }
814    
815                                    @Override
816                                    public void destroy() {
817                                    }
818    
819                            });
820    
821                    Registry registry = RegistryUtil.getRegistry();
822    
823                    Filter filter = registry.getFilter("(search.engine.id=SYSTEM_ENGINE)");
824    
825                    serviceDependencyManager.registerDependencies(
826                            new Class[] {LDAPSettings.class}, new Filter[] {filter});
827            }
828    
829            protected void initExt() throws Exception {
830                    ServletContext servletContext = getServletContext();
831    
832                    ExtRegistry.registerPortal(servletContext);
833            }
834    
835            protected void initLayoutTemplates(final PluginPackage pluginPackage) {
836                    ServiceDependencyManager serviceDependencyManager =
837                            new ServiceDependencyManager();
838    
839                    serviceDependencyManager.addServiceDependencyListener(
840                            new ServiceDependencyListener() {
841    
842                                    @Override
843                                    public void dependenciesFulfilled() {
844                                            try {
845                                                    if (_log.isDebugEnabled()) {
846                                                            _log.debug("Initialize layout templates");
847                                                    }
848    
849                                                    ServletContext servletContext = getServletContext();
850    
851                                                    String[] xmls = new String[] {
852                                                            HttpUtil.URLtoString(
853                                                                    servletContext.getResource(
854                                                                            "/WEB-INF/liferay-layout-templates.xml")),
855                                                            HttpUtil.URLtoString(
856                                                                    servletContext.getResource(
857                                                                            "/WEB-INF/" +
858                                                                                    "liferay-layout-templates-ext.xml"))
859                                                    };
860    
861                                                    List<LayoutTemplate> layoutTemplates =
862                                                            LayoutTemplateLocalServiceUtil.init(
863                                                                    servletContext, xmls, pluginPackage);
864    
865                                                    servletContext.setAttribute(
866                                                            WebKeys.PLUGIN_LAYOUT_TEMPLATES, layoutTemplates);
867                                            }
868                                            catch (Exception e) {
869                                                    _log.error(e, e);
870                                            }
871                                    }
872    
873                                    @Override
874                                    public void destroy() {
875                                    }
876    
877                            });
878    
879                    Registry registry = RegistryUtil.getRegistry();
880    
881                    Filter freeMarkerFilter = registry.getFilter(
882                            "(&(language.type=" + TemplateConstants.LANG_TYPE_FTL +
883                                    ")(objectClass=" + TemplateManager.class.getName() + "))");
884                    Filter velocityFilter = registry.getFilter(
885                            "(&(language.type=" + TemplateConstants.LANG_TYPE_VM +
886                                    ")(objectClass=" + TemplateManager.class.getName() + "))");
887    
888                    serviceDependencyManager.registerDependencies(
889                            freeMarkerFilter, velocityFilter);
890            }
891    
892            protected PluginPackage initPluginPackage() throws Exception {
893                    ServletContext servletContext = getServletContext();
894    
895                    return PluginPackageUtil.readPluginPackageServletContext(
896                            servletContext);
897            }
898    
899            /**
900             * @see SetupWizardUtil#_initPlugins
901             */
902            protected void initPlugins() throws Exception {
903    
904                    // See LEP-2885. Don't flush hot deploy events until after the portal
905                    // has initialized.
906    
907                    if (!PropsValues.SETUP_WIZARD_ENABLED) {
908                            HotDeployUtil.setCapturePrematureEvents(false);
909    
910                            PortalLifecycleUtil.flushInits();
911                    }
912            }
913    
914            protected void initPortletApp(
915                            Portlet portlet, ServletContext servletContext)
916                    throws PortletException {
917    
918                    PortletApp portletApp = portlet.getPortletApp();
919    
920                    PortletConfig portletConfig = PortletConfigFactoryUtil.create(
921                            portlet, servletContext);
922    
923                    PortletContext portletContext = portletConfig.getPortletContext();
924    
925                    Set<PortletFilter> portletFilters = portletApp.getPortletFilters();
926    
927                    for (PortletFilter portletFilter : portletFilters) {
928                            PortletFilterFactory.create(portletFilter, portletContext);
929                    }
930    
931                    Set<PortletURLListener> portletURLListeners =
932                            portletApp.getPortletURLListeners();
933    
934                    for (PortletURLListener portletURLListener : portletURLListeners) {
935                            PortletURLListenerFactory.create(portletURLListener);
936                    }
937            }
938    
939            protected List<Portlet> initPortlets(PluginPackage pluginPackage)
940                    throws Exception {
941    
942                    ServletContext servletContext = getServletContext();
943    
944                    String[] xmls = new String[PropsValues.PORTLET_CONFIGS.length];
945    
946                    for (int i = 0; i < PropsValues.PORTLET_CONFIGS.length; i++) {
947                            xmls[i] = HttpUtil.URLtoString(
948                                    servletContext.getResource(PropsValues.PORTLET_CONFIGS[i]));
949                    }
950    
951                    PortletLocalServiceUtil.initEAR(servletContext, xmls, pluginPackage);
952    
953                    PortletBagFactory portletBagFactory = new PortletBagFactory();
954    
955                    portletBagFactory.setClassLoader(
956                            ClassLoaderUtil.getPortalClassLoader());
957                    portletBagFactory.setServletContext(servletContext);
958                    portletBagFactory.setWARFile(false);
959    
960                    List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();
961    
962                    for (int i = 0; i < portlets.size(); i++) {
963                            Portlet portlet = portlets.get(i);
964    
965                            portletBagFactory.create(portlet);
966    
967                            if (i == 0) {
968                                    initPortletApp(portlet, servletContext);
969                            }
970                    }
971    
972                    servletContext.setAttribute(WebKeys.PLUGIN_PORTLETS, portlets);
973    
974                    return portlets;
975            }
976    
977            protected void initResourceActions(List<Portlet> portlets)
978                    throws Exception {
979    
980                    for (Portlet portlet : portlets) {
981                            List<String> portletActions =
982                                    ResourceActionsUtil.getPortletResourceActions(portlet);
983    
984                            ResourceActionLocalServiceUtil.checkResourceActions(
985                                    portlet.getPortletId(), portletActions);
986    
987                            List<String> modelNames =
988                                    ResourceActionsUtil.getPortletModelResources(
989                                            portlet.getPortletId());
990    
991                            for (String modelName : modelNames) {
992                                    List<String> modelActions =
993                                            ResourceActionsUtil.getModelResourceActions(modelName);
994    
995                                    ResourceActionLocalServiceUtil.checkResourceActions(
996                                            modelName, modelActions);
997                            }
998                    }
999            }
1000    
1001            protected void initServerDetector() throws Exception {
1002                    ServerCapabilitiesUtil.determineServerCapabilities(getServletContext());
1003            }
1004    
1005            protected void initSocial(PluginPackage pluginPackage) throws Exception {
1006                    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();
1007    
1008                    ServletContext servletContext = getServletContext();
1009    
1010                    String[] xmls = new String[] {
1011                            HttpUtil.URLtoString(
1012                                    servletContext.getResource("/WEB-INF/liferay-social.xml")),
1013                            HttpUtil.URLtoString(
1014                                    servletContext.getResource("/WEB-INF/liferay-social-ext.xml"))
1015                    };
1016    
1017                    SocialConfigurationUtil.read(classLoader, xmls);
1018            }
1019    
1020            protected void initThemes(
1021                            PluginPackage pluginPackage, List<Portlet> portlets)
1022                    throws Exception {
1023    
1024                    ServletContext servletContext = getServletContext();
1025    
1026                    String[] xmls = new String[] {
1027                            HttpUtil.URLtoString(
1028                                    servletContext.getResource(
1029                                            "/WEB-INF/liferay-look-and-feel.xml")),
1030                            HttpUtil.URLtoString(
1031                                    servletContext.getResource(
1032                                            "/WEB-INF/liferay-look-and-feel-ext.xml"))
1033                    };
1034    
1035                    List<Theme> themes = ThemeLocalServiceUtil.init(
1036                            servletContext, null, true, xmls, pluginPackage);
1037    
1038                    servletContext.setAttribute(WebKeys.PLUGIN_THEMES, themes);
1039            }
1040    
1041            protected void initWebSettings() throws Exception {
1042                    ServletContext servletContext = getServletContext();
1043    
1044                    String xml = HttpUtil.URLtoString(
1045                            servletContext.getResource("/WEB-INF/web.xml"));
1046    
1047                    checkWebSettings(xml);
1048            }
1049    
1050            protected long loginUser(
1051                            HttpServletRequest request, HttpServletResponse response,
1052                            long companyId, long userId, String remoteUser)
1053                    throws PortalException {
1054    
1055                    if ((userId > 0) || (remoteUser == null)) {
1056                            return userId;
1057                    }
1058    
1059                    userId = GetterUtil.getLong(remoteUser);
1060    
1061                    User user = UserLocalServiceUtil.getUserById(userId);
1062    
1063                    if (!user.isDefaultUser()) {
1064                            EventsProcessorUtil.process(
1065                                    PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE,
1066                                    request, response);
1067    
1068                            if (PropsValues.USERS_UPDATE_LAST_LOGIN ||
1069                                    (user.getLastLoginDate() == null)) {
1070    
1071                                    user = UserLocalServiceUtil.updateLastLogin(
1072                                            userId, request.getRemoteAddr());
1073                            }
1074                    }
1075    
1076                    HttpSession session = request.getSession();
1077    
1078                    session.setAttribute(WebKeys.USER, user);
1079                    session.setAttribute(WebKeys.USER_ID, Long.valueOf(userId));
1080                    session.setAttribute(Globals.LOCALE_KEY, user.getLocale());
1081    
1082                    if (!user.isDefaultUser()) {
1083                            EventsProcessorUtil.process(
1084                                    PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST,
1085                                    request, response);
1086                    }
1087    
1088                    return userId;
1089            }
1090    
1091            protected boolean processCompanyInactiveRequest(
1092                            HttpServletRequest request, HttpServletResponse response,
1093                            long companyId)
1094                    throws IOException {
1095    
1096                    if (PortalInstances.isCompanyActive(companyId)) {
1097                            return false;
1098                    }
1099    
1100                    processInactiveRequest(
1101                            request, response,
1102                            "this-instance-is-inactive-please-contact-the-administrator");
1103    
1104                    return true;
1105            }
1106    
1107            protected void processGlobalShutdownEvents() throws Exception {
1108                    EventsProcessorUtil.process(
1109                            PropsKeys.GLOBAL_SHUTDOWN_EVENTS,
1110                            PropsValues.GLOBAL_SHUTDOWN_EVENTS);
1111    
1112                    super.destroy();
1113            }
1114    
1115            protected void processGlobalStartupEvents() throws Exception {
1116                    EventsProcessorUtil.process(
1117                            PropsKeys.GLOBAL_STARTUP_EVENTS, PropsValues.GLOBAL_STARTUP_EVENTS);
1118            }
1119    
1120            protected boolean processGroupInactiveRequest(
1121                            HttpServletRequest request, HttpServletResponse response)
1122                    throws IOException, PortalException {
1123    
1124                    long plid = ParamUtil.getLong(request, "p_l_id");
1125    
1126                    if (plid <= 0) {
1127                            return false;
1128                    }
1129    
1130                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1131    
1132                    Group group = layout.getGroup();
1133    
1134                    if (group.isActive()) {
1135                            return false;
1136                    }
1137    
1138                    processInactiveRequest(
1139                            request, response,
1140                            "this-site-is-inactive-please-contact-the-administrator");
1141    
1142                    return true;
1143            }
1144    
1145            protected void processInactiveRequest(
1146                            HttpServletRequest request, HttpServletResponse response,
1147                            String messageKey)
1148                    throws IOException {
1149    
1150                    response.setContentType(ContentTypes.TEXT_HTML_UTF8);
1151    
1152                    Locale locale = PortalUtil.getLocale(request);
1153    
1154                    String message = LanguageUtil.get(locale, messageKey);
1155    
1156                    String html = ContentUtil.get(
1157                            "com/liferay/portal/dependencies/inactive.html");
1158    
1159                    html = StringUtil.replace(html, "[$MESSAGE$]", message);
1160    
1161                    PrintWriter printWriter = response.getWriter();
1162    
1163                    printWriter.print(html);
1164            }
1165    
1166            protected boolean processMaintenanceRequest(
1167                            HttpServletRequest request, HttpServletResponse response)
1168                    throws IOException, ServletException {
1169    
1170                    if (!MaintenanceUtil.isMaintaining()) {
1171                            return false;
1172                    }
1173    
1174                    RequestDispatcher requestDispatcher = request.getRequestDispatcher(
1175                            "/html/portal/maintenance.jsp");
1176    
1177                    requestDispatcher.include(request, response);
1178    
1179                    return true;
1180            }
1181    
1182            protected void processServicePost(
1183                    HttpServletRequest request, HttpServletResponse response) {
1184    
1185                    try {
1186                            EventsProcessorUtil.process(
1187                                    PropsKeys.SERVLET_SERVICE_EVENTS_POST,
1188                                    PropsValues.SERVLET_SERVICE_EVENTS_POST, request, response);
1189                    }
1190                    catch (Exception e) {
1191                            _log.error(e, e);
1192                    }
1193            }
1194    
1195            protected boolean processServicePre(
1196                            HttpServletRequest request, HttpServletResponse response,
1197                            long userId)
1198                    throws IOException, ServletException {
1199    
1200                    try {
1201                            EventsProcessorUtil.process(
1202                                    PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
1203                                    PropsValues.SERVLET_SERVICE_EVENTS_PRE, request, response);
1204                    }
1205                    catch (Exception e) {
1206                            Throwable cause = e.getCause();
1207    
1208                            if (cause instanceof NoSuchLayoutException) {
1209                                    sendError(
1210                                            HttpServletResponse.SC_NOT_FOUND, cause, request, response);
1211    
1212                                    return true;
1213                            }
1214                            else if (cause instanceof PrincipalException) {
1215                                    processServicePrePrincipalException(
1216                                            cause, userId, request, response);
1217    
1218                                    return true;
1219                            }
1220    
1221                            _log.error(e, e);
1222    
1223                            request.setAttribute(PageContext.EXCEPTION, e);
1224    
1225                            ServletContext servletContext = getServletContext();
1226    
1227                            StrutsUtil.forward(
1228                                    PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE,
1229                                    servletContext, request, response);
1230    
1231                            return true;
1232                    }
1233    
1234                    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
1235                    }
1236                    else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
1237                            response.addHeader(
1238                                    _LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getName());
1239                    }
1240                    else {
1241                            response.addHeader(
1242                                    _LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
1243                    }
1244    
1245                    return false;
1246            }
1247    
1248            protected void processServicePrePrincipalException(
1249                            Throwable t, long userId, HttpServletRequest request,
1250                            HttpServletResponse response)
1251                    throws IOException, ServletException {
1252    
1253                    if (userId > 0) {
1254                            sendError(
1255                                    HttpServletResponse.SC_UNAUTHORIZED, t, request, response);
1256    
1257                            return;
1258                    }
1259    
1260                    String redirect = PortalUtil.getPathMain().concat("/portal/login");
1261    
1262                    String currentURL = PortalUtil.getCurrentURL(request);
1263    
1264                    redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);
1265    
1266                    long plid = ParamUtil.getLong(request, "p_l_id");
1267    
1268                    if (plid > 0) {
1269                            try {
1270                                    redirect = HttpUtil.addParameter(redirect, "refererPlid", plid);
1271    
1272                                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1273    
1274                                    Group group = layout.getGroup();
1275    
1276                                    plid = group.getDefaultPublicPlid();
1277    
1278                                    if ((plid == LayoutConstants.DEFAULT_PLID) ||
1279                                            group.isStagingGroup()) {
1280    
1281                                            Group guestGroup = GroupLocalServiceUtil.getGroup(
1282                                                    layout.getCompanyId(), GroupConstants.GUEST);
1283    
1284                                            plid = guestGroup.getDefaultPublicPlid();
1285                                    }
1286    
1287                                    redirect = HttpUtil.addParameter(redirect, "p_l_id", plid);
1288                            }
1289                            catch (Exception e) {
1290                            }
1291                    }
1292    
1293                    response.sendRedirect(redirect);
1294            }
1295    
1296            protected boolean processShutdownRequest(
1297                            HttpServletRequest request, HttpServletResponse response)
1298                    throws IOException {
1299    
1300                    if (!ShutdownUtil.isShutdown()) {
1301                            return false;
1302                    }
1303    
1304                    String messageKey = ShutdownUtil.getMessage();
1305    
1306                    if (Validator.isNull(messageKey)) {
1307                            messageKey = "the-system-is-shutdown-please-try-again-later";
1308                    }
1309    
1310                    processInactiveRequest(request, response, messageKey);
1311    
1312                    return true;
1313            }
1314    
1315            protected void processStartupEvents() throws Exception {
1316                    StartupAction startupAction = new StartupAction();
1317    
1318                    startupAction.run(null);
1319            }
1320    
1321            protected void registerPortalInitialized() {
1322                    Registry registry = RegistryUtil.getRegistry();
1323    
1324                    Map<String, Object> properties = new HashMap<>();
1325    
1326                    properties.put("module.service.lifecycle", "portal.initialized");
1327                    properties.put("service.vendor", ReleaseInfo.getVendor());
1328                    properties.put("service.version", ReleaseInfo.getVersion());
1329    
1330                    _moduleServiceLifecycleServiceRegistration = registry.registerService(
1331                            ModuleServiceLifecycle.class, new ModuleServiceLifecycle() {},
1332                            properties);
1333    
1334                    properties = new HashMap<>();
1335    
1336                    properties.put("bean.id", ServletContext.class.getName());
1337                    properties.put("original.bean", Boolean.TRUE);
1338                    properties.put("service.vendor", ReleaseInfo.getVendor());
1339    
1340                    _servletContextServiceRegistration = registry.registerService(
1341                            ServletContext.class, getServletContext(), properties);
1342            }
1343    
1344            protected void sendError(
1345                            int status, Throwable t, HttpServletRequest request,
1346                            HttpServletResponse response)
1347                    throws IOException, ServletException {
1348    
1349                    DynamicServletRequest dynamicRequest = new DynamicServletRequest(
1350                            request);
1351    
1352                    // Reset layout params or there will be an infinite loop
1353    
1354                    dynamicRequest.setParameter("p_l_id", StringPool.BLANK);
1355    
1356                    dynamicRequest.setParameter("groupId", StringPool.BLANK);
1357                    dynamicRequest.setParameter("layoutId", StringPool.BLANK);
1358                    dynamicRequest.setParameter("privateLayout", StringPool.BLANK);
1359    
1360                    PortalUtil.sendError(status, (Exception)t, dynamicRequest, response);
1361            }
1362    
1363            protected void setPortalInetSocketAddresses(HttpServletRequest request) {
1364                    PortalUtil.setPortalInetSocketAddresses(request);
1365            }
1366    
1367            private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_DEFAULT =
1368                    StringUtil.equalsIgnoreCase(
1369                            PropsValues.HTTP_HEADER_VERSION_VERBOSITY, ReleaseInfo.getName());
1370    
1371            private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_PARTIAL =
1372                    StringUtil.equalsIgnoreCase(
1373                            PropsValues.HTTP_HEADER_VERSION_VERBOSITY, "partial");
1374    
1375            private static final String _LIFERAY_PORTAL_REQUEST_HEADER =
1376                    "Liferay-Portal";
1377    
1378            private static final Log _log = LogFactoryUtil.getLog(MainServlet.class);
1379    
1380            private ServiceRegistration<ModuleServiceLifecycle>
1381                    _moduleServiceLifecycleServiceRegistration;
1382            private ServiceRegistration<ServletContext>
1383                    _servletContextServiceRegistration;
1384    
1385    }