public static InputStream buildVelocity( Container container, Identifier identifier, boolean EDIT_MODE) { InputStream result; StringBuilder sb = new StringBuilder(); boolean isDynamic = UtilMethods.isSet(container.getLuceneQuery()); // let's write this puppy out to our file sb.append("#set($SERVER_NAME =\"$host.getHostname()\" )"); sb.append("#set($CONTAINER_IDENTIFIER_INODE = '").append(identifier.getInode()).append("')"); sb.append("#set($CONTAINER_INODE = '").append(container.getInode()).append("')"); sb.append("#set($CONTAINER_MAX_CONTENTLETS = ") .append(container.getMaxContentlets()) .append(")"); Structure st = (Structure) InodeFactory.getInode(container.getStructureInode(), Structure.class); sb.append("#set($CONTAINER_STRUCTURE_NAME = \"") .append((UtilMethods.isSet(st.getName()) ? st.getName() : "")) .append("\")"); sb.append("#set($STATIC_CONTAINER = ") .append(!UtilMethods.isSet(container.getLuceneQuery())) .append(")"); sb.append("#set($SORT_PAGE = \"").append(container.getSortContentletsBy()).append("\")"); sb.append("#set($containerInode = '").append(container.getInode()).append("')"); if (EDIT_MODE) { // Permissions to read/use the container in order to be able to add content to it and reorder // content sb.append("#set($USE_CONTAINER_PERMISSION = $USE_CONTAINER_PERMISSION") .append(identifier.getInode()) .append(")"); // Permissions to edit the container based on write permission ).append( access to the portlet sb.append("#set($EDIT_CONTAINER_PERMISSION = $EDIT_CONTAINER_PERMISSION") .append(identifier.getInode()) .append(")"); // Permissions over the structure to add new contents sb.append("#set($ADD_CONTENT_PERMISSION = $ADD_CONTENT_PERMISSION") .append(identifier.getInode()) .append(")"); } sb.append("#set($CONTENTLETS = $contentletList").append(identifier.getInode()).append(")"); sb.append("#set($CONTAINER_NUM_CONTENTLETS = $totalSize") .append(identifier.getInode()) .append(")"); sb.append("#set($CONTAINER_NAME = \"") .append(UtilMethods.espaceForVelocity(container.getTitle())) .append("\")"); sb.append("#set($CONTAINER_STRUCTURE_NAME = \"") .append(UtilMethods.espaceForVelocity(st.getName())) .append("\")"); if (UtilMethods.isSet(container.getNotes())) sb.append("#set($CONTAINER_NOTES = \"") .append(UtilMethods.espaceForVelocity(container.getNotes())) .append("\")"); else sb.append("#set($CONTAINER_NOTES = \"\")"); /* * isDynamic means that the content list will be pulled from lucene. */ if (isDynamic) { String luceneQuery = container.getLuceneQuery(); sb.append("#set($CONTENTS_PER_PAGE = \"$CONTAINER_MAX_CONTENTLETS\")"); sb.append("#if($request.getParameter(\"cont_") .append(identifier.getInode()) .append("_per_page\"))"); sb.append("#set($CONTENTS_PER_PAGE = $request.getParameter(\"cont_") .append(identifier.getInode()) .append("_per_page\"))"); sb.append("#end"); sb.append("#set($CURRENT_PAGE = \"1\")"); sb.append("#if($request.getParameter(\"cont_") .append(identifier.getInode()) .append("_page\"))"); sb.append("#set($CURRENT_PAGE = $request.getParameter(\"cont_") .append(identifier.getInode()) .append("_page\"))"); sb.append("#end"); sb.append("#set($LUCENE_QUERY = \"").append(luceneQuery).append("\")"); } // if the container needs to get its contentlets if (container.getMaxContentlets() > 0) { sb.append("#if($EDIT_MODE)"); // To edit the look, see WEB-INF/velocity/static/preview/container_controls.vtl sb.append("<div class='dotContainer'>"); sb.append("#end"); // pre loop if it exists if (UtilMethods.isSet(container.getPreLoop())) { sb.append(container.getPreLoop()); } // let's do the search of contentlets using lucene query if (isDynamic) { Structure containerStructure = (Structure) InodeFactory.getInode(container.getStructureInode(), Structure.class); sb.append("#set($contentletResultsMap") .append(identifier.getInode()) .append(" = $contents.searchWithLuceneQuery(\"") .append(containerStructure.getInode()) .append("\", ") .append("\"$LUCENE_QUERY\", ") .append("\"$SORT_PAGE\", ") .append("$CURRENT_PAGE, $CONTENTS_PER_PAGE)) "); sb.append("#set($contentletList") .append(identifier.getInode()) .append(" = $contents.getContentIdentifiersFromLuceneHits($contentletResultsMap") .append(identifier.getInode()) .append(".get(\"assets\")))"); sb.append("#set($HAS_NEXT_PAGE = $contentletResultsMap") .append(identifier.getInode()) .append(".get(\"has_next_page\"))"); sb.append("#set($HAS_PREVIOUS_PAGE = $contentletResultsMap") .append(identifier.getInode()) .append(".get(\"has_previous_page\"))"); sb.append("#set($TOTAL_CONTENTS = $contentletResultsMap") .append(identifier.getInode()) .append(".get(\"total_records_int\"))"); sb.append("#set($TOTAL_PAGES = $contentletResultsMap") .append(identifier.getInode()) .append(".get(\"total_pages_int\"))"); sb.append("#set($CONTENTLETS = $contentletList").append(identifier.getInode()).append(")"); sb.append("#set($CONTAINER_NUM_CONTENTLETS = $totalSize") .append(identifier.getInode()) .append(")"); } sb.append("#foreach ($contentletId in $contentletList") .append(identifier.getInode()) .append(")"); // ##Checking of contentlet is parseable and not throwing errors if (EDIT_MODE) { sb.append("#if($webapi.canParseContent($contentletId,true))"); } // sb.append("\n#if($webapi.canParseContent($contentletId,"+EDIT_MODE+")) "); sb.append(" #set($_show_working_=false) "); // if timemachine future enabled sb.append(" #if($request.session.getAttribute(\"tm_date\")) "); sb.append( " #set($_tmdate=$date.toDate($webapi.parseLong($request.session.getAttribute(\"tm_date\")))) "); sb.append(" #set($_ident=$webapi.findIdentifierById($contentletId)) "); // if the content has expired we rewrite the identifier so it isn't loaded sb.append( " #if($UtilMethods.isSet($_ident.sysExpireDate) && $_tmdate.after($_ident.sysExpireDate))"); sb.append(" #set($contentletId='') "); sb.append(" #end "); // if the content should be published then force to show the working version sb.append( " #if($UtilMethods.isSet($_ident.sysPublishDate) && $_tmdate.after($_ident.sysPublishDate))"); sb.append(" #set($_show_working_=true) "); sb.append(" #end "); sb.append(" #end "); sb.append("#set($CONTENT_INODE = '')"); sb.append(" #if($contentletId != '') "); sb.append(" #getContentDetail($contentletId) "); sb.append(" #end "); sb.append("#if($CONTENT_INODE != '')"); if (!EDIT_MODE) { sb.append( "#set($_hasPermissionToViewContent = $contents.doesUserHasPermission($CONTENT_INODE, 1, $user, true))"); // ##Checking permission to see content sb.append("#if($_hasPermissionToViewContent)"); } String code = container.getCode(); // ### HEADER ### String startTag = "${contentletStart}"; if (!code.contains(startTag)) { sb.append("#if($EDIT_MODE)"); sb.append("<div class=\"dotContentlet\">"); // An empty div is added here because in Internet Explorer, there is a styling issue // http://jira.dotmarketing.net/browse/DOTCMS-1974 sb.append("<div>"); sb.append(" #end "); } else { String headerString = "#if($EDIT_MODE)" + "<div class=\"dotContentlet\">" + "<div>" + "#end "; code = code.replace(startTag, headerString); } // ### END HEADER ### // ### BODY ### String endTag = "${contentletEnd}"; boolean containsEndTag = code.contains(endTag); if (containsEndTag) { String footerString = "#if($EDIT_MODE && ${contentletId.indexOf(\".structure\")}==-1)" + "$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')" + "#end" + "#if($EDIT_MODE)" + "<div class=\"dotClear\"></div></div>" + "#end "; code = code.replace(endTag, footerString); } sb.append("#if($isWidget == true)"); sb.append("$widgetCode"); sb.append(" #else"); sb.append(code); sb.append(" #end "); // The empty div added for styling issue in Internet Explorer is closed here // http://jira.dotmarketing.net/browse/DOTCMS-1974 sb.append("#if($EDIT_MODE)"); sb.append("</div>"); sb.append("#end "); // ### END BODY ### // ### FOOTER ### if (!containsEndTag) { sb.append("#if($EDIT_MODE && ${contentletId.indexOf(\".structure\")}==-1)"); sb.append("#getContentDetail($contentletId)"); sb.append("$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')"); sb.append("#end "); sb.append("#if($EDIT_MODE) "); sb.append("<div class=\"dotClear\"></div></div>"); sb.append("#end "); } // ### END FOOTER ### if (!EDIT_MODE) { // ##End of checking permission to see content sb.append("#end "); } // ##Ends the inner canParse call sb.append("#end "); // ##Case the contentlet is not parseable and throwing errors if (EDIT_MODE) { sb.append("#else "); sb.append("#set($CONTENT_INODE =\"$webapi.getContentInode($contentletId)\")"); sb.append( "#set($EDIT_CONTENT_PERMISSION =\"$webapi.getContentPermissions($contentletId)\")"); sb.append("<div class=\"dotContentlet\">"); sb.append(" Content Parse Error. Check your Content Code. "); sb.append("$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')"); sb.append("<div class=\"dotClear\"></div></div>"); sb.append("#end "); } // ##End of foreach loop sb.append("#end "); // post loop if it exists if (UtilMethods.isSet(container.getPostLoop())) { sb.append(container.getPostLoop()); } // close our container preview mode div sb.append("#if($EDIT_MODE)"); sb.append("$velutil.mergeTemplate('static/preview_mode/container_controls.vtl')"); sb.append("</div>"); sb.append("#end "); } else { sb.append(container.getCode()); } try { String folderPath = (!EDIT_MODE) ? "live" + File.separator : "working" + File.separator; String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT"); if (velocityRootPath.startsWith("/WEB-INF")) { velocityRootPath = Config.CONTEXT.getRealPath(velocityRootPath); } velocityRootPath += File.separator; String filePath = folderPath + identifier.getInode() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"); if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) { java.io.BufferedOutputStream tmpOut = new java.io.BufferedOutputStream( new java.io.FileOutputStream( new java.io.File( ConfigUtils.getDynamicVelocityPath() + 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(ContentletServices.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; }
@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; }