/** * This method trys to build a cache key based on the information given in the request - if the * page can't be cached, or caching is not availbale then return null * * @param request * @return */ private String getPageCacheKey(HttpServletRequest request) { // no license if (LicenseUtil.getLevel() < 100) { return null; } // don't cache posts if (!"GET".equalsIgnoreCase(request.getMethod())) { return null; } // nocache passed either as a session var, as a request var or as a // request attribute if ("no".equals(request.getParameter("dotcache")) || "no".equals(request.getAttribute("dotcache")) || "no".equals(request.getSession().getAttribute("dotcache"))) { return null; } String idInode = (String) request.getAttribute("idInode"); User user = (com.liferay.portal.model.User) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); HTMLPage page = null; try { page = APILocator.getHTMLPageAPI().loadLivePageById(idInode, user, true); } catch (Exception e) { Logger.error( HTMLPageWebAPI.class, "unable to load live version of page: " + idInode + " because " + e.getMessage()); return null; } if (page == null || page.getCacheTTL() < 1) { return null; } StringBuilder sb = new StringBuilder(); sb.append(page.getInode()); sb.append("_" + page.getModDate().getTime()); String userId = (user != null) ? user.getUserId() : "PUBLIC"; sb.append("_" + userId); String language = (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE); sb.append("_" + language); String urlMap = (String) request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE); if (urlMap != null) { sb.append("_" + urlMap); } if (UtilMethods.isSet(request.getQueryString())) { sb.append("_" + request.getQueryString()); } return sb.toString(); }
@Override public PublisherConfig init(PublisherConfig config) throws DotPublishingException { if (LicenseUtil.getLevel() < 400) throw new RuntimeException("need an enterprise prime license to run this bundler"); this.config = super.init(config); tFactory = new TrustFactory(); return this.config; }
@Override public void executeAction( WorkflowProcessor processor, Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { if (LicenseUtil.getLevel() < 200) return; // the apis will do nothing anyway WebContext ctx = WebContextFactory.get(); HttpServletRequest request = ctx.getHttpServletRequest(); User user = null; try { user = uWebAPI.getLoggedInUser(request); } catch (Exception exx) { throw new WorkflowActionFailureException(exx.getMessage()); } Contentlet con = processor.getContentlet(); List<InvalidLink> httpResponse = null; try { httpResponse = APILocator.getLinkCheckerAPI().findInvalidLinks(con); } catch (Exception e1) { Logger.error(this, e1.getMessage(), e1); throw new WorkflowActionFailureException(e1.getMessage()); } // if there are unreachable URL... if (httpResponse.size() > 0) { String msg = ""; try { msg = LanguageUtil.get(user, "checkURL.errorBrokenLinks"); } catch (Exception e) { } throw new WorkflowActionFailureException( LinkCheckerUtil.buildPopupMsgWithLinksList(msg, httpResponse)); } }
@Override public PublisherConfig process(final PublishStatus status) throws DotPublishingException { if (LicenseUtil.getLevel() < 400) throw new RuntimeException("need an enterprise prime license to run this bundler"); PublishAuditHistory currentStatusHistory = null; try { // Compressing bundle File bundleRoot = BundlerUtil.getBundleRoot(config); ArrayList<File> list = new ArrayList<File>(1); list.add(bundleRoot); File bundle = new File( bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz"); PushUtils.compressFiles(list, bundle, bundleRoot.getAbsolutePath()); // Retriving enpoints and init client List<PublishingEndPoint> endpoints = ((PushPublisherConfig) config).getEndpoints(); Map<String, List<PublishingEndPoint>> endpointsMap = new HashMap<String, List<PublishingEndPoint>>(); List<PublishingEndPoint> buffer = null; // Organize the endpoints grouping them by groupId for (PublishingEndPoint pEndPoint : endpoints) { String gid = UtilMethods.isSet(pEndPoint.getGroupId()) ? pEndPoint.getGroupId() : pEndPoint.getId(); if (endpointsMap.get(gid) == null) buffer = new ArrayList<PublishingEndPoint>(); else buffer = endpointsMap.get(gid); buffer.add(pEndPoint); // put in map with either the group key or the id if no group is set endpointsMap.put(gid, buffer); } ClientConfig cc = new DefaultClientConfig(); if (Config.getStringProperty("TRUSTSTORE_PATH") != null && !Config.getStringProperty("TRUSTSTORE_PATH").trim().equals("")) cc.getProperties() .put( HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(tFactory.getHostnameVerifier(), tFactory.getSSLContext())); Client client = Client.create(cc); // Updating audit table currentStatusHistory = pubAuditAPI.getPublishAuditStatus(config.getId()).getStatusPojo(); currentStatusHistory.setPublishStart(new Date()); pubAuditAPI.updatePublishAuditStatus( config.getId(), PublishAuditStatus.Status.SENDING_TO_ENDPOINTS, currentStatusHistory); // Increment numTries currentStatusHistory.addNumTries(); boolean hasError = false; int errorCounter = 0; for (String group : endpointsMap.keySet()) { List<PublishingEndPoint> groupList = endpointsMap.get(group); boolean sent = false; for (PublishingEndPoint endpoint : groupList) { EndpointDetail detail = new EndpointDetail(); try { FormDataMultiPart form = new FormDataMultiPart(); form.field( "AUTH_TOKEN", retriveKeyString( PublicEncryptionFactory.decryptString(endpoint.getAuthKey().toString()))); form.field( "GROUP_ID", UtilMethods.isSet(endpoint.getGroupId()) ? endpoint.getGroupId() : endpoint.getId()); form.field("ENDPOINT_ID", endpoint.getId()); form.bodyPart( new FileDataBodyPart("bundle", bundle, MediaType.MULTIPART_FORM_DATA_TYPE)); // Sending bundle to endpoint WebResource resource = client.resource(endpoint.toURL() + "/api/bundlePublisher/publish"); ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); if (response.getClientResponseStatus().getStatusCode() == HttpStatus.SC_OK) { detail.setStatus(PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY.getCode()); detail.setInfo("Everything ok"); sent = true; } else { detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode()); detail.setInfo( "Returned " + response.getClientResponseStatus().getStatusCode() + " status code " + "for the endpoint " + endpoint.getId() + "with address " + endpoint.getAddress()); } } catch (Exception e) { hasError = true; detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode()); String error = "An error occured for the endpoint " + endpoint.getId() + " with address " + endpoint.getAddress() + ". Error: " + e.getMessage(); detail.setInfo(error); Logger.error(this.getClass(), error); } currentStatusHistory.addOrUpdateEndpoint(group, endpoint.getId(), detail); if (sent) break; } if (!sent) { hasError = true; errorCounter++; } } if (!hasError) { // Updating audit table currentStatusHistory.setPublishEnd(new Date()); pubAuditAPI.updatePublishAuditStatus( config.getId(), PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY, currentStatusHistory); // Deleting queue records // pubAPI.deleteElementsFromPublishQueueTable(config.getId()); } else { if (errorCounter == endpointsMap.size()) { pubAuditAPI.updatePublishAuditStatus( config.getId(), PublishAuditStatus.Status.FAILED_TO_SEND_TO_ALL_GROUPS, currentStatusHistory); } else { pubAuditAPI.updatePublishAuditStatus( config.getId(), PublishAuditStatus.Status.FAILED_TO_SEND_TO_SOME_GROUPS, currentStatusHistory); } } return config; } catch (Exception e) { // Updating audit table try { pubAuditAPI.updatePublishAuditStatus( config.getId(), PublishAuditStatus.Status.FAILED_TO_PUBLISH, currentStatusHistory); } catch (DotPublisherException e1) { throw new DotPublishingException(e.getMessage()); } Logger.error(this.getClass(), e.getMessage(), e); throw new DotPublishingException(e.getMessage()); } }
@SuppressWarnings("unchecked") protected void doEditMode(HttpServletRequest request, HttpServletResponse response) throws Exception { String uri = request.getRequestURI(); uri = UtilMethods.cleanURI(uri); Host host = hostWebAPI.getCurrentHost(request); StringBuilder preExecuteCode = new StringBuilder(); Boolean widgetPreExecute = false; // Getting the user to check the permissions com.liferay.portal.model.User backendUser = null; try { backendUser = com.liferay.portal.util.PortalUtil.getUser(request); } catch (Exception nsue) { Logger.warn(this, "Exception trying getUser: "******"idInode", String.valueOf(id.getInode())); Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode()); Template template = null; Template hostVariablesTemplate = null; // creates the context where to place the variables response.setContentType(CHARSET); Context context = VelocityUtil.getWebContext(request, response); HTMLPage htmlPage = (HTMLPage) APILocator.getVersionableAPI() .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); // to check user has permission to write on this page boolean hasAddChildrenPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, backendUser); boolean hasWritePermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, backendUser); boolean hasPublishPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, backendUser); context.put("ADD_CHILDREN_HTMLPAGE_PERMISSION", new Boolean(hasAddChildrenPermOverHTMLPage)); context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage)); context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage)); context.put("canAddForm", new Boolean(LicenseUtil.getLevel() > 199 ? true : false)); context.put("canViewDiff", new Boolean(LicenseUtil.getLevel() > 199 ? true : false)); boolean canUserWriteOnTemplate = permissionAPI.doesUserHavePermission( htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, backendUser) && portletAPI.hasTemplateManagerRights(backendUser); context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate); com.dotmarketing.portlets.templates.model.Template cmsTemplate = com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate( htmlPage, true); if (cmsTemplate == null) { // DOTCMS-4051 cmsTemplate = new com.dotmarketing.portlets.templates.model.Template(); Logger.debug(VelocityServlet.class, "HTMLPAGE TEMPLATE NOT FOUND"); } Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate); Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode()); VelocityUtil.makeBackendContext( context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, true, false, host); // added to show tabs context.put("previewPage", "1"); // get the containers for the page and stick them in context List<Container> containers = APILocator.getTemplateAPI() .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false); for (Container c : containers) { context.put( String.valueOf("container" + c.getIdentifier()), "/working/" + c.getIdentifier() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")); boolean hasWritePermissionOnContainer = permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, backendUser, false) && portletAPI.hasContainerManagerRights(backendUser); boolean hasReadPermissionOnContainer = permissionAPI.doesUserHavePermission(c, PERMISSION_READ, backendUser, false); context.put("EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), hasWritePermissionOnContainer); if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), true); else context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), hasReadPermissionOnContainer); // to check user has permission to write this container Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class); boolean hasWritePermOverTheStructure = permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, backendUser); context.put( "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure)); Logger.debug( VelocityServlet.class, String.valueOf("container" + c.getIdentifier()) + "=/working/" + c.getIdentifier() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")); String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy(); List<Contentlet> contentlets = null; boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery()); // get contentlets only for main frame if (request.getParameter("mainFrame") != null) { if (staticContainer) { Logger.debug(VelocityServlet.class, "Static Container!!!!"); Logger.debug( VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode()); // The container doesn't have categories Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); Identifier idenContainer = APILocator.getIdentifierAPI().find(c); contentlets = conAPI.findPageContentlets( idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, -1, backendUser, true); Logger.debug( VelocityServlet.class, "Getting contentlets for language=" + (String) request .getSession() .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE) + " contentlets =" + contentlets.size()); } else { String luceneQuery = c.getLuceneQuery(); int limit = c.getMaxContentlets(); String sortBy = c.getSortContentletsBy(); int offset = 0; contentlets = conAPI.search(luceneQuery, limit, offset, sortBy, backendUser, true); } if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) { Set<String> contentletIdentList = new HashSet<String>(); List<Contentlet> contentletsFilter = new ArrayList<Contentlet>(); for (Contentlet cont : contentlets) { if (!contentletIdentList.contains(cont.getIdentifier())) { contentletIdentList.add(cont.getIdentifier()); contentletsFilter.add(cont); } } contentlets = contentletsFilter; } List<String> contentletList = new ArrayList<String>(); if (contentlets != null) { Iterator<Contentlet> iter = contentlets.iterator(); int count = 0; while (iter.hasNext() && (count < c.getMaxContentlets())) { count++; Contentlet contentlet = (Contentlet) iter.next(); Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet); boolean hasWritePermOverContentlet = permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, backendUser); context.put( "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(), new Boolean(hasWritePermOverContentlet)); contentletList.add(String.valueOf(contentletIdentifier.getInode())); Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode()); Structure contStructure = contentlet.getStructure(); if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { Field field = contStructure.getFieldVar("widgetPreexecute"); if (field != null && UtilMethods.isSet(field.getValues())) { preExecuteCode.append(field.getValues().trim() + "\n"); widgetPreExecute = true; } } } } // sets contentletlist with all the files to load per // container context.put("contentletList" + c.getIdentifier(), contentletList); context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size())); // ### Add the structure fake contentlet ### if (contentletList.size() == 0) { Structure structure = ContainerFactory.getContainerStructure(c); contentletList.add(structure.getInode() + ""); // sets contentletlist with all the files to load per // container context.remove("contentletList" + c.getIdentifier()); context.remove("totalSize" + c.getIdentifier()); // http://jira.dotmarketing.net/browse/DOTCMS-2876 context.put("contentletList" + c.getIdentifier(), new long[0]); context.put("totalSize" + c.getIdentifier(), 0); } // ### END Add the structure fake contentlet ### } } Logger.debug( VelocityServlet.class, "Before finding template: /working/" + templateIdentifier.getInode() + "." + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")); Logger.debug( VelocityServlet.class, "Velocity directory:" + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH)); if (request.getParameter("leftMenu") != null) { /* * try to get the messages from the session */ List<String> list = new ArrayList<String>(); if (SessionMessages.contains(request, "message")) { list.add((String) SessionMessages.get(request, "message")); SessionMessages.clear(request); } if (SessionMessages.contains(request, "custommessage")) { list.add((String) SessionMessages.get(request, "custommessage")); SessionMessages.clear(request); } if (list.size() > 0) { ArrayList<String> mymessages = new ArrayList<String>(); Iterator<String> it = list.iterator(); while (it.hasNext()) { try { String message = (String) it.next(); Company comp = PublicCompanyFactory.getDefaultCompany(); mymessages.add(LanguageUtil.get(comp.getCompanyId(), backendUser.getLocale(), message)); } catch (Exception e) { } } context.put("vmessages", mymessages); } template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl"); } else if (request.getParameter("mainFrame") != null) { hostVariablesTemplate = VelocityUtil.getEngine() .getTemplate( "/working/" + host.getIdentifier() + "." + Config.getStringProperty("VELOCITY_HOST_EXTENSION")); template = VelocityUtil.getEngine() .getTemplate( "/working/" + templateIdentifier.getInode() + "." + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")); } else { // Return a resource not found right away if the page is not found, // not try to load the frames if (!InodeUtils.isSet(templateIdentifier.getInode())) throw new ResourceNotFoundException(""); template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl"); } PrintWriter out = response.getWriter(); request.setAttribute("velocityContext", context); try { if (widgetPreExecute) { VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString()); } if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out); template.merge(context, out); } catch (ParseErrorException e) { out.append(e.getMessage()); } }
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL) && LicenseUtil.getLevel() < 299) { request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response); return; } if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.ORACLE) && LicenseUtil.getLevel() < 399) { request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response); return; } if (!LicenseUtil.isASAllowed()) { request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response); return; } Long profileTime = null; if (Config.getBooleanProperty("VELOCITY_PROFILING", false)) { profileTime = Calendar.getInstance().getTimeInMillis(); } try { // Check if the uri is a physical file. Fix for the cases when the // site configure VELOCITY_PAGE_EXTENSION as htm, html or any known // extension. // Example: // /html/js/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm String uri = request.getRequestURI(); uri = URLDecoder.decode(uri, "UTF-8"); File file = new File(Config.CONTEXT.getRealPath(uri)); if (file.exists()) { FileInputStream fileIS = new FileInputStream(file); ServletOutputStream servletOS = response.getOutputStream(); int b; for (; -1 < (b = fileIS.read()); ) { servletOS.write(b); } fileIS.close(); servletOS.flush(); servletOS.close(); return; } // If we are at a directory, e.g. /home // we need to redirect to /home/ String forwardFor = (String) request.getRequestURL().toString(); if (request.getAttribute(Globals.MAPPING_KEY) == null && forwardFor != null && !forwardFor.endsWith("/") && !forwardFor.endsWith("." + Config.getStringProperty("VELOCITY_PAGE_EXTENSION"))) { // The query string parameters should be preserved as well String queryString = request.getQueryString(); response.sendRedirect( forwardFor + "/" + (UtilMethods.isSet(queryString) ? "?" + queryString : "")); return; } HttpSession session = request.getSession(false); boolean ADMIN_MODE = session != null && (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null); boolean PREVIEW_MODE = ADMIN_MODE && (session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null); boolean EDIT_MODE = ADMIN_MODE && (session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null); String value = request.getHeader("X-Requested-With"); if ((value != null) && value.equals("XMLHttpRequest") && EDIT_MODE && ADMIN_MODE) { ADMIN_MODE = false; } // ### VALIDATE ARCHIVE ### if ((EDIT_MODE || PREVIEW_MODE) && isArchive(request)) { PREVIEW_MODE = true; EDIT_MODE = false; request.setAttribute("archive", true); } // ### END VALIDATE ARCHIVE ### LanguageWebAPI langWebAPI = WebAPILocator.getLanguageWebAPI(); langWebAPI.checkSessionLocale(request); if (PREVIEW_MODE && ADMIN_MODE) { // preview mode has the left hand menu and edit buttons on the // working page Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON PREVIEW MODE!!!"); doPreviewMode(request, response); } else if (EDIT_MODE && ADMIN_MODE) { // edit mode has the left hand menu and edit buttons on the // working page Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON EDIT MODE!!!"); doEditMode(request, response); } else if (ADMIN_MODE) { // admin mode has the left hand menu and shows the live page in // the frame Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON ADMIN MODE!!!"); doAdminMode(request, response); } else { // live mode has no frame and shows the live page Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON LIVE MODE!!!"); doLiveMode(request, response); } } catch (ResourceNotFoundException rnfe) { // response.sendError(404); request.setAttribute(Constants.SERVE_URL, request.getRequestURI()); request.getRequestDispatcher("/localResourceServlet").forward(request, response); } catch (ParseErrorException pee) { Logger.error(this, "Template Parse Exception : " + pee.toString(), pee); try { response.sendError(500, "Template Parse Exception"); } catch (Throwable t) { Logger.error(this, t.getMessage(), t); PrintWriter out = response.getWriter(); out.println("Template Parse Exception"); out.println("On template:" + request.getRequestURI() + request.getQueryString()); } } catch (MethodInvocationException mie) { Logger.error(this, "MethodInvocationException" + mie.toString(), mie); try { response.sendError(500, "MethodInvocationException Error on template"); } catch (Throwable t) { Logger.error(this, t.getMessage(), t); PrintWriter out = response.getWriter(); out.println( "MethodInvocationException Error on template:" + request.getRequestURI() + request.getQueryString()); } } catch (Exception e) { Logger.error(this, e.toString(), e); try { response.sendError(500, "MethodInvocationException Error on template"); } catch (Throwable t) { Logger.error(this, t.getMessage(), t); PrintWriter out = response.getWriter(); out.println("Error on template:" + request.getRequestURI() + request.getQueryString()); } } finally { // catchall // added finally because of // http://jira.dotmarketing.net/browse/DOTCMS-1334 try { HibernateUtil.commitTransaction(); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } DbConnectionFactory.closeConnection(); } if (profileTime != null) { profileTime = Calendar.getInstance().getTimeInMillis() - profileTime; VelocityProfiler.log( VelocityServlet.class, "VelocityPage time: " + request.getRequestURL() + " " + profileTime + " millis"); } }
@SuppressWarnings("unchecked") public static InputStream buildStream(HTMLPage htmlPage, Identifier identifier, boolean EDIT_MODE) throws DotDataException, DotSecurityException { String folderPath = (!EDIT_MODE) ? "live/" : "working/"; InputStream result; StringBuilder sb = new StringBuilder(); ContentletAPI conAPI = APILocator.getContentletAPI(); Template cmsTemplate = com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate( htmlPage, EDIT_MODE); if (cmsTemplate == null || !InodeUtils.isSet(cmsTemplate.getInode())) { Logger.error( This.class, "PAGE DOES NOT HAVE A VALID TEMPLATE (template unpublished?) : page id " + htmlPage.getIdentifier() + ":" + identifier.getURI()); } // gets pageChannel for this path java.util.StringTokenizer st = new java.util.StringTokenizer(String.valueOf(identifier.getURI()), "/"); String pageChannel = null; if (st.hasMoreTokens()) { pageChannel = st.nextToken(); } // set the page cache var if (htmlPage.getCacheTTL() > 0 && LicenseUtil.getLevel() > 99) { sb.append("#set($dotPageCacheDate = \"").append(new java.util.Date()).append("\")"); sb.append("#set($dotPageCacheTTL = \"").append(htmlPage.getCacheTTL()).append("\")"); } // set the host variables HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); Host host = htmlPageAPI.getParentHost(htmlPage); sb.append("#if(!$doNotParseTemplate)"); sb.append("$velutil.mergeTemplate('") .append(folderPath) .append(host.getIdentifier()) .append(".") .append(Config.getStringProperty("VELOCITY_HOST_EXTENSION")) .append("')"); sb.append(" #end "); // creates the context where to place the variables // Build a context to pass to the page sb.append("#if(!$doNotSetPageInfo)"); sb.append("#set ( $quote = '\"' )"); sb.append("#set ($HTMLPAGE_INODE = \"") .append(String.valueOf(htmlPage.getInode())) .append("\" )"); sb.append("#set ($HTMLPAGE_IDENTIFIER = \"") .append(String.valueOf(htmlPage.getIdentifier())) .append("\" )"); sb.append("#set ($HTMLPAGE_TITLE = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getTitle())) .append("\" )"); sb.append( "#set ($HTMLPAGE_FRIENDLY_NAME = \"" + UtilMethods.espaceForVelocity(htmlPage.getFriendlyName())) .append("\" )"); sb.append("#set ($TEMPLATE_INODE = \"") .append(String.valueOf(cmsTemplate.getInode())) .append("\" )"); sb.append("#set ($HTMLPAGE_META = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getMetadata())) .append("\" )"); sb.append("#set ($HTMLPAGE_META = \"#fixBreaks($HTMLPAGE_META)\")"); sb.append("#set ($HTMLPAGE_DESCRIPTION = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getSeoDescription())) .append("\" )"); sb.append("#set ($HTMLPAGE_DESCRIPTION = \"#fixBreaks($HTMLPAGE_DESCRIPTION)\")"); sb.append("#set ($HTMLPAGE_KEYWORDS = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getSeoKeywords())) .append("\" )"); sb.append("#set ($HTMLPAGE_KEYWORDS = \"#fixBreaks($HTMLPAGE_KEYWORDS)\")"); sb.append("#set ($HTMLPAGE_SECURE = \"") .append(String.valueOf(htmlPage.isHttpsRequired())) .append("\" )"); sb.append("#set ($VTLSERVLET_URI = \"") .append(UtilMethods.encodeURIComponent(identifier.getURI())) .append("\" )"); sb.append("#set ($HTMLPAGE_REDIRECT = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getRedirect())) .append("\" )"); sb.append("#set ($pageTitle = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getTitle())) .append("\" )"); sb.append("#set ($pageChannel = \"").append(pageChannel).append("\" )"); sb.append("#set ($friendlyName = \"") .append(UtilMethods.espaceForVelocity(htmlPage.getFriendlyName())) .append("\" )"); Date moddate = null; if (UtilMethods.isSet(htmlPage.getModDate())) { moddate = htmlPage.getModDate(); } else { moddate = htmlPage.getStartDate(); } moddate = new Timestamp(moddate.getTime()); sb.append("#set ($HTML_PAGE_LAST_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"") .append(moddate) .append("\"))"); sb.append("#set ($HTMLPAGE_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"") .append(moddate) .append("\"))"); sb.append(" #end "); // get the containers for the page and stick them in context // List identifiers = InodeFactory.getChildrenClass(cmsTemplate, Identifier.class); List<Container> containerList = APILocator.getTemplateAPI() .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false); Iterator i = containerList.iterator(); while (i.hasNext()) { Container ident = (Container) i.next(); Container c = null; if (EDIT_MODE) { c = (Container) APILocator.getVersionableAPI() .findWorkingVersion( ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false); } else { c = (Container) APILocator.getVersionableAPI() .findLiveVersion( ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false); } // sets container to load the container file sb.append("#set ($container") .append(ident.getIdentifier()) .append(" = \"") .append(folderPath) .append(ident.getIdentifier()) .append(".") .append(Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")) .append("\" )"); String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy(); boolean dynamicContainer = UtilMethods.isSet(c.getLuceneQuery()); int langCounter = 0; List<Contentlet> contentlets = new ArrayList<Contentlet>(); List<Contentlet> contentletsFull = new ArrayList<Contentlet>(); if (!dynamicContainer) { Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); Identifier idenContainer = APILocator.getIdentifierAPI().find(c); // The container doesn't have categories try { contentlets = conAPI.findPageContentlets( idenHtmlPage.getId(), idenContainer.getId(), sort, EDIT_MODE, -1, APILocator.getUserAPI().getSystemUser(), false); if (EDIT_MODE) contentletsFull = contentlets; else contentletsFull = conAPI.findPageContentlets( idenHtmlPage.getId(), idenContainer.getId(), sort, true, -1, APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { Logger.error(PageServices.class, "Unable to retrive contentlets on page", e); } Logger.debug( PageServices.class, "HTMLPage= " + htmlPage.getInode() + " Container=" + c.getInode() + " Language=-1 Contentlets=" + contentlets.size()); } // this is to filter the contentlets list removing the repited identifiers if (contentlets.size() > 0) { Set<String> contentletIdentList = new HashSet<String>(); List<Contentlet> contentletsFilter = new ArrayList<Contentlet>(); for (Contentlet cont : contentlets) { if (!contentletIdentList.contains(cont.getIdentifier())) { contentletIdentList.add(cont.getIdentifier()); contentletsFilter.add(cont); } } contentlets = contentletsFilter; } if (contentletsFull.size() > 0) { Set<String> contentletIdentList = new HashSet<String>(); List<Contentlet> contentletsFilter = new ArrayList<Contentlet>(); for (Contentlet cont : contentletsFull) { if (!contentletIdentList.contains(cont.getIdentifier())) { contentletIdentList.add(cont.getIdentifier()); contentletsFilter.add(cont); } } contentletsFull = contentletsFilter; } StringBuilder widgetpree = new StringBuilder(); StringBuilder widgetpreeFull = new StringBuilder(); StringBuilder contentletList = new StringBuilder(); int count = 0; for (Contentlet contentlet : contentlets) { contentletList .append(count == 0 ? "" : ",") .append('"') .append(contentlet.getIdentifier()) .append('"'); if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { Field field = contentlet.getStructure().getFieldVar("widgetPreexecute"); if (field != null && UtilMethods.isSet(field.getValues())) widgetpree.append(field.getValues().trim()); } if (++count >= c.getMaxContentlets()) break; } StringBuilder contentletListFull = new StringBuilder(); int countFull = 0; for (Contentlet contentlet : contentletsFull) { contentletListFull .append(countFull == 0 ? "" : ",") .append('"') .append(contentlet.getIdentifier()) .append('"'); if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { Field field = contentlet.getStructure().getFieldVar("widgetPreexecute"); if (field != null && UtilMethods.isSet(field.getValues())) widgetpreeFull.append(field.getValues().trim()); } if (++countFull >= c.getMaxContentlets()) break; } sb.append("#if($request.session.getAttribute(\"tm_date\"))"); sb.append(widgetpreeFull); sb.append("#set ($contentletList") .append(ident.getIdentifier()) .append(" = [") .append(contentletListFull.toString()) .append("] )"); sb.append("#set ($totalSize") .append(ident.getIdentifier()) .append("=") .append(countFull) .append(")"); sb.append("#else "); sb.append(widgetpree); sb.append("#set ($contentletList") .append(ident.getIdentifier()) .append(" = [") .append(contentletList.toString()) .append("] )"); sb.append("#set ($totalSize") .append(ident.getIdentifier()) .append("=") .append(count) .append(")"); sb.append("#end "); langCounter++; } if (htmlPage.isHttpsRequired()) { sb.append(" #if(!$ADMIN_MODE && !$request.isSecure())"); sb.append(" #if($request.getQueryString())"); sb.append( " #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')?$request.getQueryString()\")"); sb.append(" #else "); sb.append( " #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')\")"); sb.append(" #end "); sb.append(" $response.sendRedirect(\"$REDIRECT_URL\")"); sb.append(" #end "); } sb.append("#if($HTMLPAGE_REDIRECT != \"\")"); sb.append(" $response.sendRedirect(\"$HTMLPAGE_REDIRECT\")"); sb.append("#end"); Identifier iden = APILocator.getIdentifierAPI().find(cmsTemplate); sb.append("#if(!$doNotParseTemplate)"); if (cmsTemplate.isDrawed()) { // We have a designed template // Setting some theme variables sb.append("#set ($dotTheme = $templatetool.theme(\"") .append(cmsTemplate.getTheme()) .append("\",\"") .append(host.getIdentifier()) .append("\"))"); sb.append("#set ($dotThemeLayout = $templatetool.themeLayout(\"") .append(cmsTemplate.getInode()) .append("\" ))"); // Merging our template sb.append("$velutil.mergeTemplate(\"$dotTheme.templatePath\")"); } else { sb.append("$velutil.mergeTemplate('") .append(folderPath) .append(iden.getInode()) .append(".") .append(Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")) .append("')"); } sb.append("#end"); try { if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) { String realFolderPath = (!EDIT_MODE) ? "live" + java.io.File.separator : "working" + java.io.File.separator; String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT"); String filePath = realFolderPath + identifier.getInode() + "." + Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION"); if (velocityRootPath.startsWith("/WEB-INF")) { velocityRootPath = com.liferay.util.FileUtil.getRealPath(velocityRootPath); } velocityRootPath += java.io.File.separator; java.io.BufferedOutputStream tmpOut = new java.io.BufferedOutputStream( new java.io.FileOutputStream( new java.io.File( ConfigUtils.getDynamicVelocityPath() + java.io.File.separator + filePath))); // Specify a proper character encoding OutputStreamWriter out = new OutputStreamWriter(tmpOut, UtilMethods.getCharsetConfiguration()); out.write(sb.toString()); out.flush(); out.close(); tmpOut.close(); } } catch (Exception e) { Logger.error(PageServices.class, e.toString(), e); } try { result = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { result = new ByteArrayInputStream(sb.toString().getBytes()); Logger.error(ContainerServices.class, e1.getMessage(), e1); } return result; }