/** * Copy a file into the given directory OR host * * @param file File to be copied * @param parent Destination Folder * @param host Destination host * @return true if copy success, false otherwise * @throws IOException * @throws DotHibernateException */ private File copyFile(File file, Folder parent, Host host) throws DotDataException, IOException { File newFile = new File(); newFile.copy(file); // gets filename before extension String fileName = com.dotmarketing.util.UtilMethods.getFileName(file.getFileName()); // gets file extension String fileExtension = com.dotmarketing.util.UtilMethods.getFileExtension(file.getFileName()); Boolean fileNameExists; if (parent != null) { fileNameExists = fileNameExists(parent, file.getFileName()); } else { fileNameExists = fileNameExists(APILocator.getFolderAPI().findSystemFolder(), file.getFileName()); } // Setting file name if (fileNameExists) { // adds "copy" word to the filename newFile.setFileName(fileName + "_copy." + fileExtension); newFile.setFriendlyName(file.getFriendlyName() + " (COPY) "); } else { newFile.setFileName(fileName + "." + fileExtension); } Identifier identifier; if (parent != null) { identifier = APILocator.getIdentifierAPI().createNew(newFile, parent); } else { identifier = APILocator.getIdentifierAPI().createNew(newFile, host); } newFile.setIdentifier(identifier.getInode()); // persists the webasset HibernateUtil.saveOrUpdate(newFile); saveFileData(file, newFile, null); Logger.debug(FileFactory.class, "identifier=" + identifier.getURI()); WorkingCache.removeAssetFromCache(newFile); WorkingCache.addToWorkingAssetToCache(newFile); PermissionAPI permissionAPI = APILocator.getPermissionAPI(); try { APILocator.getVersionableAPI().setWorking(newFile); if (file.isLive()) APILocator.getVersionableAPI().setLive(newFile); } catch (DotStateException e) { Logger.error(this, e.getMessage()); } catch (DotSecurityException e) { Logger.error(this, e.getMessage()); } // Copy permissions permissionAPI.copyPermissions(file, newFile); return newFile; }
protected void doAdminMode(HttpServletRequest request, HttpServletResponse response) throws Exception { // LIVE MODE - LIVE PAGE com.liferay.portal.model.User backendUser = null; backendUser = com.liferay.portal.util.PortalUtil.getUser(request); response.setContentType(CHARSET); Context context = VelocityUtil.getWebContext(request, response); String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration()); uri = UtilMethods.cleanURI(uri); Host host = hostWebAPI.getCurrentHost(request); Identifier id = APILocator.getIdentifierAPI().find(host, uri); request.setAttribute("idInode", id.getInode()); HTMLPage htmlPage = (HTMLPage) APILocator.getVersionableAPI() .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); VelocityUtil.makeBackendContext( context, htmlPage, "", id.getURI(), request, true, false, false, host); boolean canUserWriteOnTemplate = permissionAPI.doesUserHavePermission( htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, backendUser); context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate); Template template = null; if (request.getParameter("leftMenu") != null) { template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl"); } else if (request.getParameter("mainFrame") != null) { template = VelocityUtil.getEngine() .getTemplate("/live/" + id.getInode() + "." + VELOCITY_HTMLPAGE_EXTENSION); } else { template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl"); } Logger.debug(VelocityServlet.class, "Got the template!!!!" + id.getInode()); PrintWriter out = response.getWriter(); request.setAttribute(VELOCITY_CONTEXT, context); try { template.merge(context, out); } catch (ParseErrorException e) { out.append(e.getMessage()); } }
public Map<String, Object> getEvent(String id, boolean live) throws DotDataException, DotSecurityException, PortalException, SystemException { WebContext ctx = WebContextFactory.get(); HttpServletRequest request = ctx.getHttpServletRequest(); // Retrieving the current user User user = userAPI.getLoggedInUser(request); boolean respectFrontendRoles = true; Event ev = eventAPI.find(id, live, user, respectFrontendRoles); Map<String, Object> eventMap = ev.getMap(); // Loading categories List<Map<String, Object>> categoryMaps = new ArrayList<Map<String, Object>>(); List<Category> eventCategories = categoryAPI.getParents(ev, user, respectFrontendRoles); for (Category cat : eventCategories) { categoryMaps.add(cat.getMap()); } eventMap.put("categories", categoryMaps); eventMap.put("rating", RatingAPI.getAverageRating(ev.getIdentifier())); eventMap.put("votes", RatingAPI.getRatingVotesNumber(ev.getIdentifier())); eventMap.put( "hasReadPermission", perAPI.doesUserHavePermission( ev, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles)); eventMap.put( "hasWritePermission", perAPI.doesUserHavePermission( ev, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles)); eventMap.put( "hasPublishPermission", perAPI.doesUserHavePermission( ev, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles)); eventMap.put( "readPermission", perAPI.doesUserHavePermission( ev, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles)); eventMap.put( "writePermission", perAPI.doesUserHavePermission( ev, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles)); eventMap.put( "publishPermission", perAPI.doesUserHavePermission( ev, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles)); eventMap.put("isDisconnected", UtilMethods.isSet(ev.getDisconnectedFrom())); CommentsWebAPI cAPI = new CommentsWebAPI(); cAPI.setUser(user); cAPI.setRespectFrontendRoles(respectFrontendRoles); eventMap.put("commentsCount", cAPI.getCommentsCount(ev.getInode())); return eventMap; }
public void unarchiveEvent(String identifier) throws PortalException, SystemException, DotDataException, DotSecurityException { HibernateUtil.startTransaction(); WebContext ctx = WebContextFactory.get(); HttpServletRequest request = ctx.getHttpServletRequest(); // Retrieving the current user User user = userAPI.getLoggedInUser(request); boolean respectFrontendRoles = true; Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles); try { if (UtilMethods.isSet(ev.getDisconnectedFrom())) { Event baseEvent = null; try { baseEvent = eventAPI.find(ev.getDisconnectedFrom(), false, user, respectFrontendRoles); } catch (Exception e) { Logger.error(this, "Base event not found"); } if (baseEvent != null) { try { Date originalStartDate = ev.getOriginalStartDate(); baseEvent.addDateToIgnore(originalStartDate); APILocator.getContentletAPI() .checkin( baseEvent, categoryAPI.getParents(baseEvent, user, true), perAPI.getPermissions(baseEvent), user, false); } catch (Exception e) { Logger.error(this, "Could not delete event from recurrence"); } } } contAPI.unarchive(ev, user, respectFrontendRoles); } catch (Exception e) { Logger.error(this, e.getMessage()); } HibernateUtil.commitTransaction(); if (!contAPI.isInodeIndexed(ev.getInode())) { Logger.error(this, "Timed out while waiting for index to return"); } }
public List<File> findFiles( User user, boolean includeArchived, Map<String, Object> params, String hostId, String inode, String identifier, String parent, int offset, int limit, String orderBy) throws DotSecurityException, DotDataException { PaginatedArrayList<File> assets = new PaginatedArrayList<File>(); List<Permissionable> toReturn = new ArrayList<Permissionable>(); int internalLimit = 500; int internalOffset = 0; boolean done = false; StringBuilder conditionBuffer = new StringBuilder().append(" asset.inode=versioninfo.workingInode "); String condition = !includeArchived ? " and versioninfo.deleted = " + DbConnectionFactory.getDBFalse() : " "; conditionBuffer.append(condition); List<Object> paramValues = null; if (params != null && params.size() > 0) { conditionBuffer.append(" and ("); paramValues = new ArrayList<Object>(); int counter = 0; for (Map.Entry<String, Object> entry : params.entrySet()) { if (counter == 0) { if (entry.getValue() instanceof String) { if (entry.getKey().equalsIgnoreCase("inode")) { conditionBuffer .append(" asset.") .append(entry.getKey()) .append(" = '") .append(entry.getValue()) .append("'"); } else { conditionBuffer.append(" lower(asset.").append(entry.getKey()).append(") like ? "); paramValues.add("%" + ((String) entry.getValue()).toLowerCase() + "%"); } } else { conditionBuffer .append(" asset.") .append(entry.getKey()) .append(" = ") .append(entry.getValue()); } } else { if (entry.getValue() instanceof String) { if (entry.getKey().equalsIgnoreCase("inode")) { conditionBuffer .append(" OR asset.") .append(entry.getKey()) .append(" = '") .append(entry.getValue()) .append("'"); } else { conditionBuffer.append(" OR lower(asset.").append(entry.getKey()).append(") like ? "); paramValues.add("%" + ((String) entry.getValue()).toLowerCase() + "%"); } } else { conditionBuffer .append(" OR asset.") .append(entry.getKey()) .append(" = ") .append(entry.getValue()); } } counter += 1; } conditionBuffer.append(" ) "); } StringBuilder query = new StringBuilder(); query .append("select asset from asset in class ") .append(File.class.getName()) .append(", ") .append("inode in class ") .append(Inode.class.getName()) .append(", identifier in class ") .append(Identifier.class.getName()) .append(", versioninfo in class ") .append(FileAssetVersionInfo.class.getName()); if (UtilMethods.isSet(parent)) { query .append(" ,tree in class ") .append(Tree.class.getName()) .append(" where asset.inode=inode.inode ") .append("and asset.identifier = identifier.id and tree.parent = '") .append(parent) .append("' and tree.child=asset.inode"); } else { query.append(" where asset.inode=inode.inode and asset.identifier = identifier.id"); } query.append(" and versioninfo.identifier=identifier.id "); if (UtilMethods.isSet(hostId)) { query.append(" and identifier.hostId = '").append(hostId).append("'"); } if (UtilMethods.isSet(inode)) { query.append(" and asset.inode = '").append(inode).append("'"); } if (UtilMethods.isSet(identifier)) { query.append(" and asset.identifier = '").append(identifier).append("'"); } if (!UtilMethods.isSet(orderBy)) { orderBy = "modDate desc"; } List<File> resultList = new ArrayList<File>(); HibernateUtil dh = new HibernateUtil(File.class); String type; int countLimit = 100; int size = 0; try { type = ((Inode) File.class.newInstance()).getType(); query.append(" and asset.type='").append(type).append("' "); final String conditions = conditionBuffer.toString().trim(); if (conditions.length() > 0) query.append(" and ").append(conditions); query.append(" order by asset.").append(orderBy); dh.setQuery(query.toString()); if (paramValues != null && paramValues.size() > 0) { for (Object value : paramValues) { dh.setParam((String) value); } } while (!done) { dh.setFirstResult(internalOffset); dh.setMaxResults(internalLimit); resultList = dh.list(); PermissionAPI permAPI = APILocator.getPermissionAPI(); toReturn.addAll( permAPI.filterCollection(resultList, PermissionAPI.PERMISSION_READ, false, user)); if (countLimit > 0 && toReturn.size() >= countLimit + offset) done = true; else if (resultList.size() < internalLimit) done = true; internalOffset += internalLimit; } if (offset > toReturn.size()) { size = 0; } else if (countLimit > 0) { int toIndex = offset + countLimit > toReturn.size() ? toReturn.size() : offset + countLimit; size = toReturn.subList(offset, toIndex).size(); } else if (offset > 0) { size = toReturn.subList(offset, toReturn.size()).size(); } assets.setTotalResults(size); if (limit != -1) { int from = offset < toReturn.size() ? offset : 0; int pageLimit = 0; for (int i = from; i < toReturn.size(); i++) { if (pageLimit < limit) { assets.add((File) toReturn.get(i)); pageLimit += 1; } else { break; } } } else { for (int i = 0; i < toReturn.size(); i++) { assets.add((File) toReturn.get(i)); } } } catch (Exception e) { Logger.error(FileFactoryImpl.class, "findFiles failed:" + e, e); throw new DotRuntimeException(e.toString()); } return assets; }
@SuppressWarnings("unchecked") public static Contentlet createContent( Structure st, ArrayList<Category> cats, String userId, List<String> parametersName, List<String[]> values, String options, List<Map<String, Object>> fileParameters, boolean autoPublish, Host formHost, String moderatorRole) throws DotContentletStateException, DotDataException, DotSecurityException { Contentlet contentlet = null; /*try {*/ /** Get the current user */ User user = getUserFromId(userId); /** Content inherit structure permissions */ List<Permission> permissionList = perAPI.getPermissions(st); /** Set the content values */ contentlet = SubmitContentUtil.setAllFields(st.getName(), parametersName, values); /** Get the required relationships */ Map<Relationship, List<Contentlet>> relationships = SubmitContentUtil.getRelationships(st, contentlet, options, user); /** Validating content fields */ // conAPI.validateContentlet(contentlet,relationships,cats); /** Set the binary field values http://jira.dotmarketing.net/browse/DOTCMS-3463 */ if (fileParameters.size() > 0) { for (Map<String, Object> value : fileParameters) { Field field = (Field) value.get("field"); java.io.File file = (java.io.File) value.get(field.getVelocityVarName()); if (file != null) { try { contentlet.setBinary(field.getVelocityVarName(), file); } catch (IOException e) { } } } } if (st.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { contentlet.setHost(formHost.getIdentifier()); Host host = APILocator.getHostAPI() .find(formHost.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false); if (!perAPI.doesUserHavePermissions( host, "PARENT:" + PermissionAPI.PERMISSION_READ + ", CONTENTLETS:" + PermissionAPI.PERMISSION_WRITE + "", user)) { throw new DotSecurityException("User doesn't have write permissions to Contentlet"); } } /** If the moderator field is set, a work flow task is created */ if (UtilMethods.isSet(moderatorRole)) { if (!UtilMethods.isSet(contentlet.getStringProperty(Contentlet.WORKFLOW_ACTION_KEY))) contentlet.setStringProperty( Contentlet.WORKFLOW_ACTION_KEY, APILocator.getWorkflowAPI().findEntryAction(contentlet, user).getId()); String contentletTitle = ""; List<Field> fields = FieldsCache.getFieldsByStructureInode(contentlet.getStructureInode()); for (Field fld : fields) { if (fld.isListed()) { contentletTitle = contentlet.getMap().get(fld.getVelocityVarName()).toString(); contentletTitle = contentletTitle.length() > 250 ? contentletTitle.substring(0, 250) : contentletTitle; } } contentlet.setStringProperty( Contentlet.WORKFLOW_COMMENTS_KEY, "A new content titled \"" + UtilHTML.escapeHTMLSpecialChars(contentletTitle.trim()) + "\" has been posted by " + UtilHTML.escapeHTMLSpecialChars(user.getFullName()) + " (" + user.getEmailAddress() + ")"); contentlet.setStringProperty( Contentlet.WORKFLOW_ASSIGN_KEY, roleAPI.loadRoleByKey(moderatorRole).getId()); } /** Saving Content */ contentlet = conAPI.checkin(contentlet, relationships, cats, permissionList, user, true); APILocator.getVersionableAPI().setWorking(contentlet); if (autoPublish) APILocator.getVersionableAPI().setLive(contentlet); /** Saving file and images */ if (fileParameters.size() > 0) { for (Map<String, Object> value : fileParameters) { Field field = (Field) value.get("field"); // http://jira.dotmarketing.net/browse/DOTCMS-3463 if (field.getFieldType().equals(Field.FieldType.IMAGE.toString()) || field.getFieldType().equals(Field.FieldType.FILE.toString())) { java.io.File uploadedFile = (java.io.File) value.get("file"); try { if (!UtilMethods.isSet(FileUtil.getBytes(uploadedFile))) continue; } catch (IOException e) { Logger.error(SubmitContentUtil.class, e.getMessage()); } String title = (String) value.get("title"); Host host = (Host) value.get("host"); contentlet = addFileToContentlet(contentlet, field, host, uploadedFile, user, title); } } if (autoPublish) { // DOTCMS-5188 contentlet = conAPI.checkinWithoutVersioning( contentlet, relationships, cats, permissionList, user, true); conAPI.publish(contentlet, APILocator.getUserAPI().getSystemUser(), false); } else { contentlet = conAPI.checkinWithoutVersioning( contentlet, relationships, cats, permissionList, user, true); conAPI.unpublish(contentlet, APILocator.getUserAPI().getSystemUser(), false); } } /*}catch(Exception e){ Logger.error(SubmitContentUtil.class, e.getMessage()); throw new DotContentletStateException("Unable to perform checkin. "+e.getMessage()); }*/ return contentlet; }
@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()); } }
@SuppressWarnings("unchecked") public void doPreviewMode(HttpServletRequest request, HttpServletResponse response) throws Exception { String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration()); 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 user = null; HttpSession session = request.getSession(false); try { if (session != null) user = (com.liferay.portal.model.User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } catch (Exception nsue) { Logger.warn(this, "Exception trying getUser: "******"idInode", 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, user, true); HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); // to check user has permission to write on this page boolean hasWritePermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user); boolean hasPublishPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, user); context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage)); context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage)); boolean canUserWriteOnTemplate = permissionAPI.doesUserHavePermission( htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, user, true); context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate); com.dotmarketing.portlets.templates.model.Template cmsTemplate = com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate( htmlPage, true); 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, false, true, host); context.put("previewPage", "2"); context.put("livePage", "0"); // 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")); context.put( "EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, user, true)); // 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, user, true); 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(); boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery()); List<Contentlet> contentlets = null; // 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, user, true); Logger.debug( VelocityServlet.class, "Getting contentlets for language=" + (String) request .getSession() .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE) + " contentlets =" + contentlets.size()); } 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 && contentlets.size() > 0) { 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, user, true); 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())); } } 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(), user.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 { 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()); } }
public void doLiveMode(HttpServletRequest request, HttpServletResponse response) throws Exception { String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration()); uri = UtilMethods.cleanURI(uri); Host host = hostWebAPI.getCurrentHost(request); // Map with all identifier inodes for a given uri. String idInode = APILocator.getIdentifierAPI().find(host, uri).getInode(); // Checking the path is really live using the livecache String cachedUri = LiveCache.getPathFromCache(uri, host); // if we still have nothing. if (!InodeUtils.isSet(idInode) || cachedUri == null) { throw new ResourceNotFoundException( String.format("Resource %s not found in Live mode!", uri)); } response.setContentType(CHARSET); request.setAttribute("idInode", String.valueOf(idInode)); Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + idInode); /* * JIRA http://jira.dotmarketing.net/browse/DOTCMS-4659 //Set long lived cookie regardless of who this is */ String _dotCMSID = UtilMethods.getCookieValue( request.getCookies(), com.dotmarketing.util.WebKeys.LONG_LIVED_DOTCMS_ID_COOKIE); if (!UtilMethods.isSet(_dotCMSID)) { // create unique generator engine Cookie idCookie = CookieUtil.createCookie(); response.addCookie(idCookie); } com.liferay.portal.model.User user = null; HttpSession session = request.getSession(false); try { if (session != null) user = (com.liferay.portal.model.User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } catch (Exception nsue) { Logger.warn(this, "Exception trying to getUser: "******"Page Permissions for URI=" + uri); HTMLPage page = null; try { // we get the page and check permissions below page = APILocator.getHTMLPageAPI() .loadLivePageById(idInode, APILocator.getUserAPI().getSystemUser(), false); } catch (Exception e) { Logger.error( HTMLPageWebAPI.class, "unable to load live version of page: " + idInode + " because " + e.getMessage()); return; } // Check if the page is visible by a CMS Anonymous role if (!permissionAPI.doesUserHavePermission(page, PERMISSION_READ, user, true)) { // this page is protected. not anonymous access /** * ***************************************************************** If we need to redirect * someone somewhere to login before seeing a page, we need to edit the /portal/401.jsp page * to sendRedirect the user to the proper login page. We are not using the REDIRECT_TO_LOGIN * variable in the config any longer. * **************************************************************** */ if (!signedIn) { // No need for the below LAST_PATH attribute on the front end // http://jira.dotmarketing.net/browse/DOTCMS-2675 // request.getSession().setAttribute(WebKeys.LAST_PATH, // new ObjectValuePair(uri, request.getParameterMap())); request.getSession().setAttribute(com.dotmarketing.util.WebKeys.REDIRECT_AFTER_LOGIN, uri); Logger.debug( VelocityServlet.class, "VELOCITY CHECKING PERMISSION: Page doesn't have anonymous access" + uri); Logger.debug(VelocityServlet.class, "401 URI = " + uri); Logger.debug(VelocityServlet.class, "Unauthorized URI = " + uri); response.sendError(401, "The requested page/file is unauthorized"); return; } else if (!permissionAPI .getReadRoles(ident) .contains(APILocator.getRoleAPI().loadLoggedinSiteRole())) { // user is logged in need to check user permissions Logger.debug(VelocityServlet.class, "VELOCITY CHECKING PERMISSION: User signed in"); // check user permissions on this asset if (!permissionAPI.doesUserHavePermission(ident, PERMISSION_READ, user, true)) { // the user doesn't have permissions to see this page // go to unauthorized page Logger.warn( VelocityServlet.class, "VELOCITY CHECKING PERMISSION: Page doesn't have any access for this user"); response.sendError(403, "The requested page/file is forbidden"); return; } } } Logger.debug(VelocityServlet.class, "Recording the ClickStream"); if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) { if (user != null) { UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI() .getUserProxy(user, APILocator.getUserAPI().getSystemUser(), false); if (!userProxy.isNoclicktracking()) { ClickstreamFactory.addRequest( (HttpServletRequest) request, ((HttpServletResponse) response), host); } } else { ClickstreamFactory.addRequest( (HttpServletRequest) request, ((HttpServletResponse) response), host); } } // Begin Page Caching boolean buildCache = false; String key = getPageCacheKey(request); if (key != null) { String cachedPage = CacheLocator.getBlockDirectiveCache().get(key, (int) page.getCacheTTL()); if (cachedPage == null || "refresh".equals(request.getParameter("dotcache")) || "refresh".equals(request.getAttribute("dotcache")) || "refresh".equals(request.getSession().getAttribute("dotcache"))) { // build cached response buildCache = true; } else { // have cached response and are not refreshing, send it response.getWriter().write(cachedPage); return; } } Writer out = (buildCache) ? new StringWriter(4096) : new VelocityFilterWriter(response.getWriter()); // get the context from the requst if possible Context context = VelocityUtil.getWebContext(request, response); request.setAttribute("velocityContext", context); Logger.debug(VelocityServlet.class, "HTMLPage Identifier:" + idInode); try { VelocityUtil.getEngine() .getTemplate("/live/" + idInode + "." + VELOCITY_HTMLPAGE_EXTENSION) .merge(context, out); } catch (ParseErrorException e) { // out.append(e.getMessage()); } context = null; if (buildCache) { String trimmedPage = out.toString().trim(); response.getWriter().write(trimmedPage); response.getWriter().close(); synchronized (key) { String x = CacheLocator.getBlockDirectiveCache().get(key, (int) page.getCacheTTL()); if (x != null) { return; } CacheLocator.getBlockDirectiveCache() .add(getPageCacheKey(request), trimmedPage, (int) page.getCacheTTL()); } } else { out.close(); } }
private void _deleteStructure(ActionForm form, ActionRequest req, ActionResponse res) throws Exception { try { Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE); User user = _getUser(req); HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest(); // Checking permissions _checkDeletePermissions(structure, user, httpReq); // checking if there is containers using this structure List<Container> containers = APILocator.getContainerAPI().findContainersForStructure(structure.getInode()); if (containers.size() > 0) { StringBuilder names = new StringBuilder(); for (int i = 0; i < containers.size(); i++) names.append(containers.get(i).getFriendlyName()).append(", "); Logger.warn( EditStructureAction.class, "Structure " + structure.getName() + " can't be deleted because the following containers are using it: " + names); SessionMessages.add(req, "message", "message.structure.notdeletestructure.container"); return; } if (!structure.isDefaultStructure()) { @SuppressWarnings("rawtypes") List fields = FieldFactory.getFieldsByStructure(structure.getInode()); @SuppressWarnings("rawtypes") Iterator fieldsIter = fields.iterator(); while (fieldsIter.hasNext()) { Field field = (Field) fieldsIter.next(); FieldFactory.deleteField(field); } int limit = 200; int offset = 0; List<Contentlet> contentlets = conAPI.findByStructure(structure, user, false, limit, offset); int size = contentlets.size(); while (size > 0) { conAPI.delete(contentlets, user, false); contentlets = conAPI.findByStructure(structure, user, false, limit, offset); size = contentlets.size(); } if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { @SuppressWarnings({"deprecation", "static-access"}) Structure st = StructureCache.getStructureByName(fAPI.FORM_WIDGET_STRUCTURE_NAME_FIELD_NAME); if (UtilMethods.isSet(st) && UtilMethods.isSet(st.getInode())) { @SuppressWarnings({"deprecation", "static-access"}) Field field = st.getField(fAPI.FORM_WIDGET_FORM_ID_FIELD_NAME); List<Contentlet> widgetresults = conAPI.search( "+structureInode:" + st.getInode() + " +" + field.getFieldContentlet() + ":" + structure.getInode(), 0, 0, "", user, false); if (widgetresults.size() > 0) { conAPI.delete(widgetresults, user, false); } } } // http://jira.dotmarketing.net/browse/DOTCMS-6435 if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) { StructureFactory.updateFolderFileAssetReferences(structure); } List<Relationship> relationships = RelationshipFactory.getRelationshipsByParent(structure); for (Relationship rel : relationships) { RelationshipFactory.deleteRelationship(rel); } relationships = RelationshipFactory.getRelationshipsByChild(structure); for (Relationship rel : relationships) { RelationshipFactory.deleteRelationship(rel); } PermissionAPI perAPI = APILocator.getPermissionAPI(); perAPI.removePermissions(structure); StructureFactory.deleteStructure(structure); // Removing the structure from cache FieldsCache.removeFields(structure); StructureCache.removeStructure(structure); StructureServices.removeStructureFile(structure); SessionMessages.add(req, "message", "message.structure.deletestructure"); } else { SessionMessages.add(req, "message", "message.structure.notdeletestructure"); } } catch (Exception ex) { Logger.debug(EditStructureAction.class, ex.toString()); throw ex; } }
private void _saveStructure(ActionForm form, ActionRequest req, ActionResponse res) { try { boolean newStructure = false; StructureForm structureForm = (StructureForm) form; Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE); User user = _getUser(req); HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest(); if (!UtilMethods.isSet(structureForm.getHost()) && (!UtilMethods.isSet(structureForm.getFolder()) || structureForm.getFolder().equals("SYSTEM_FOLDER"))) { throw new DotDataException(LanguageUtil.get(user, "Host-or-folder-is-required")); } // Checking permissions _checkWritePermissions(structure, user, httpReq); // Check if another structure with the same name exist String auxStructureName = structureForm.getName(); auxStructureName = (auxStructureName != null ? auxStructureName.trim() : ""); @SuppressWarnings("deprecation") Structure auxStructure = StructureCache.getStructureByType(auxStructureName); if (InodeUtils.isSet(auxStructure.getInode()) && !auxStructure.getInode().equalsIgnoreCase(structure.getInode())) { throw new DotDataException( LanguageUtil.get(user, "There-is-another-structure-with-the-same-name")); } Arrays.sort(reservedStructureNames); if (!InodeUtils.isSet(structureForm.getInode()) && (Arrays.binarySearch(reservedStructureNames, auxStructureName) >= 0)) { throw new DotDataException("Invalid Reserved Structure Name : " + auxStructureName); } // Validate if is a new structure and if the name hasn't change if (!InodeUtils.isSet(structure.getInode())) { newStructure = true; } else { String structureName = structure.getName(); String structureFormName = structureForm.getName(); if (UtilMethods.isSet(structureName) && UtilMethods.isSet(structureFormName) && !structureName.equals(structureFormName) && !structure.isFixed()) { StructureCache.removeStructure(structure); } } // If the structure is fixed the name cannot be changed if (structure.isFixed()) { structureForm.setName(structure.getName()); } // if I'm editing a structure the structureType couldn't not be // change if (UtilMethods.isSet(structure.getInode()) && InodeUtils.isSet(structure.getInode())) { // reset the structure type to it's original value structureForm.setStructureType(structure.getStructureType()); } if (UtilMethods.isSet(structure.getVelocityVarName())) { structureForm.setVelocityVarName(structure.getVelocityVarName()); } if (UtilMethods.isSet(structureForm.getHost())) { if (!structureForm.getHost().equals(Host.SYSTEM_HOST) && hostAPI.findSystemHost().getIdentifier().equals(structureForm.getHost())) { structureForm.setHost(Host.SYSTEM_HOST); } structureForm.setFolder("SYSTEM_FOLDER"); } else if (UtilMethods.isSet(structureForm.getFolder())) { structureForm.setHost(folderAPI.find(structureForm.getFolder(), user, false).getHostId()); } if (UtilMethods.isSet(structureForm.getHost()) && (!UtilMethods.isSet(structureForm.getFolder()) || structureForm.getFolder().equals("SYSTEM_FOLDER"))) { Host host = hostAPI.find(structureForm.getHost(), user, false); if (host != null) { if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { if (!perAPI.doesUserHavePermissions( host, "PARENT:" + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN + ", STRUCTURES:" + PermissionAPI.PERMISSION_PUBLISH, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } else { if (!perAPI.doesUserHavePermission( host, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } } } if (UtilMethods.isSet(structureForm.getFolder()) && !structureForm.getFolder().equals("SYSTEM_FOLDER")) { Folder folder = folderAPI.find(structureForm.getFolder(), user, false); if (folder != null) { if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { if (!perAPI.doesUserHavePermissions( folder, "PARENT:" + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN + ", STRUCTURES:" + PermissionAPI.PERMISSION_PUBLISH, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } else { if (!perAPI.doesUserHavePermission( folder, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } } } BeanUtils.copyProperties(structure, structureForm); // if htmlpage doesn't exist page id should be an identifier. Should // be refactored once we get identifierAPI/HTMLPage API done String pageDetail = structureForm.getDetailPage(); if (newStructure) { String structureVelocityName = VelocityUtil.convertToVelocityVariable(structure.getName(), true); List<String> velocityvarnames = StructureFactory.getAllVelocityVariablesNames(); int found = 0; if (VelocityUtil.isNotAllowedVelocityVariableName(structureVelocityName)) { found++; } for (String velvar : velocityvarnames) { if (velvar != null) { if (structureVelocityName.equalsIgnoreCase(velvar)) { found++; } else if (velvar.toLowerCase().contains(structureVelocityName.toLowerCase())) { String number = velvar.substring(structureVelocityName.length()); if (RegEX.contains(number, "^[0-9]+$")) { found++; } } } } if (found > 0) { structureVelocityName = structureVelocityName + Integer.toString(found); } structure.setVelocityVarName(structureVelocityName); } if (UtilMethods.isSet(pageDetail)) { structure.setDetailPage(pageDetail); } // Saving interval review properties if (structureForm.isReviewContent()) { structure.setReviewInterval( structureForm.getReviewIntervalNum() + structureForm.getReviewIntervalSelect()); } else { structure.setReviewInterval(null); structure.setReviewerRole(null); } // If there is no default structure this would be Structure defaultStructure = StructureFactory.getDefaultStructure(); if (!InodeUtils.isSet(defaultStructure.getInode())) { structure.setDefaultStructure(true); } if (newStructure) { structure.setFixed(false); structure.setOwner(user.getUserId()); } // validate iit is a form structure set it as system by default if (structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { structure.setSystem(true); } StructureFactory.saveStructure(structure); structureForm.setUrlMapPattern(structure.getUrlMapPattern()); WorkflowScheme scheme = APILocator.getWorkflowAPI().findSchemeForStruct(structure); String schemeId = req.getParameter("workflowScheme"); if (scheme != null && UtilMethods.isSet(schemeId) && !schemeId.equals(scheme.getId())) { scheme = APILocator.getWorkflowAPI().findScheme(schemeId); APILocator.getWorkflowAPI().saveSchemeForStruct(structure, scheme); } // if the structure is a widget we need to add the base fields. if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { wAPI.createBaseWidgetFields(structure); } // if the structure is a form we need to add the base fields. if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { fAPI.createBaseFormFields(structure); } // if the structure is a form we need to add the base fields. if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) { APILocator.getFileAssetAPI().createBaseFileAssetFields(structure); } if (!newStructure) { perAPI.resetPermissionReferences(structure); } // Saving the structure in cache StructureCache.removeStructure(structure); StructureCache.addStructure(structure); StructureServices.removeStructureFile(structure); String message = "message.structure.savestructure"; if (structure.getStructureType() == 3) { message = "message.form.saveform"; } SessionMessages.add(req, "message", message); AdminLogger.log( EditStructureAction.class, "_saveStructure", "Structure saved : " + structure.getName(), user); } catch (Exception ex) { Logger.error(this.getClass(), ex.toString()); String message = ex.toString(); SessionMessages.add(req, "error", message); } }
public List<Map<String, Object>> findEventsByHostId( String hostId, Date fromDate, Date toDate, String[] tags, String[] keywords, String[] categoriesInodes, boolean live, boolean includeArchived, int offset, int limit) throws DotDataException, DotSecurityException, PortalException, SystemException { WebContext ctx = WebContextFactory.get(); HttpServletRequest request = ctx.getHttpServletRequest(); // Retrieving the current user User user = userAPI.getLoggedInUser(request); boolean respectFrontendRoles = true; List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>(); List<Category> categories = new ArrayList<Category>(); if (categoriesInodes != null) { for (String categoryInode : categoriesInodes) { Category cat = categoryAPI.find(categoryInode, user, respectFrontendRoles); if (cat != null) categories.add(cat); } } List<Event> events = eventAPI.find( hostId, fromDate, toDate, tags, keywords, categories, live, includeArchived, offset, limit, user, respectFrontendRoles); for (Event ev : events) { Map<String, Object> eventMap = ev.getMap(); // Loading categories List<Map<String, Object>> categoryMaps = new ArrayList<Map<String, Object>>(); List<Category> eventCategories = categoryAPI.getParents(ev, user, respectFrontendRoles); for (Category cat : eventCategories) { categoryMaps.add(cat.getMap()); } // http://jira.dotmarketing.net/browse/DOTCMS-6904 // we're missing [working, live, deleted] info // sometimes we mess with identifier adding recurrence info String origIdent = ev.getIdentifier(); String realIdent = APILocator.getIdentifierAPI().findFromInode(ev.getInode()).getId(); ev.setIdentifier(realIdent); eventMap.put("live", ev.isLive()); eventMap.put("working", ev.isWorking()); eventMap.put("archived", ev.isArchived()); eventMap.put("deleted", ev.isArchived()); eventMap.put("locked", ev.isLocked()); ev.setIdentifier(origIdent); eventMap.put("categories", categoryMaps); eventMap.put("rating", RatingAPI.getAverageRating(ev.getIdentifier())); eventMap.put("votes", RatingAPI.getRatingVotesNumber(ev.getIdentifier())); CommentsWebAPI cAPI = new CommentsWebAPI(); cAPI.setUser(user); cAPI.setRespectFrontendRoles(respectFrontendRoles); eventMap.put("commentsCount", cAPI.getCommentsCount(ev.getInode())); eventMap.put( "hasReadPermission", perAPI.doesUserHavePermission(ev, PermissionAPI.PERMISSION_READ, user)); eventMap.put( "hasWritePermission", perAPI.doesUserHavePermission(ev, PermissionAPI.PERMISSION_WRITE, user)); eventMap.put( "hasPublishPermission", perAPI.doesUserHavePermission(ev, PermissionAPI.PERMISSION_PUBLISH, user)); eventMap.put( "readPermission", perAPI.doesUserHavePermission(ev, PermissionAPI.PERMISSION_READ, user)); eventMap.put( "writePermission", perAPI.doesUserHavePermission(ev, PermissionAPI.PERMISSION_WRITE, user)); eventMap.put( "publishPermission", perAPI.doesUserHavePermission(ev, PermissionAPI.PERMISSION_PUBLISH, user)); eventMap.put("offSet", DateViewWebAPI.getOffSet(ev.getStartDate())); eventMap.put("isDisconnected", UtilMethods.isSet(ev.getDisconnectedFrom())); retList.add(eventMap); } return retList; }
public Map<String, Object> disconnectEvent(String inode, String startDateStr, String endDateStr) throws DotRuntimeException, PortalException, SystemException, DotDataException, DotSecurityException, java.text.ParseException { WebContext ctx = WebContextFactory.get(); HttpServletRequest request = ctx.getHttpServletRequest(); // Retrieving the current user User user = userAPI.getLoggedInUser(request); boolean respectFrontendRoles = true; Map<String, Object> eventMap = new HashMap<String, Object>(); List<String> disconnectEventErrors = new ArrayList<String>(); String inodeStr = (InodeUtils.isSet(inode) ? inode : ""); Contentlet contentlet = new Contentlet(); if (InodeUtils.isSet(inodeStr)) { contentlet = contAPI.find(inodeStr, user, false); } if (InodeUtils.isSet(contentlet.getInode())) { Event ev = null; try { ev = eventAPI.find(contentlet.getIdentifier(), false, user, respectFrontendRoles); } catch (Exception e) { disconnectEventErrors.add(e.getLocalizedMessage()); } finally { if (disconnectEventErrors.size() > 0) { eventMap.put("disconnectEventErrors", disconnectEventErrors); } } if (ev != null) { Date startDate = null; Date endDate = null; try { if (UtilMethods.isSet(startDateStr)) { String date = dateFormat.format(dateFormat2.parse(startDateStr)); startDate = dateFormat.parse(date); } if (UtilMethods.isSet(endDateStr)) { String date = dateFormat.format(dateFormat2.parse(endDateStr)); endDate = dateFormat.parse(date); } } catch (java.text.ParseException pe) { disconnectEventErrors.add(pe.getLocalizedMessage()); } finally { if (disconnectEventErrors.size() > 0) { eventMap.put("disconnectEventErrors", disconnectEventErrors); } } if (startDate != null && endDate != null) { Calendar originalStartDate = Calendar.getInstance(); Calendar originalEndDate = Calendar.getInstance(); Calendar newStartDate = Calendar.getInstance(); Calendar newEndDate = Calendar.getInstance(); originalStartDate.setTime(ev.getStartDate()); originalEndDate.setTime(ev.getEndDate()); newStartDate.setTime(startDate); newEndDate.setTime(endDate); originalStartDate.set(Calendar.YEAR, newStartDate.get(Calendar.YEAR)); originalStartDate.set(Calendar.MONTH, newStartDate.get(Calendar.MONTH)); originalStartDate.set(Calendar.DAY_OF_MONTH, newStartDate.get(Calendar.DAY_OF_MONTH)); originalEndDate.set(Calendar.YEAR, newEndDate.get(Calendar.YEAR)); originalEndDate.set(Calendar.MONTH, newEndDate.get(Calendar.MONTH)); originalEndDate.set(Calendar.DAY_OF_MONTH, newEndDate.get(Calendar.DAY_OF_MONTH)); Event newEvent = null; try { boolean autoCom = false; try { autoCom = DbConnectionFactory.getConnection().getAutoCommit(); } catch (Exception e) { throw new DotDataException(e.getMessage()); } if (autoCom) { HibernateUtil.startTransaction(); } newEvent = eventAPI.disconnectEvent( ev, user, originalStartDate.getTime(), originalEndDate.getTime()); eventMap = newEvent.getMap(); // Loading categories List<Map<String, Object>> categoryMaps = new ArrayList<Map<String, Object>>(); List<Category> eventCategories = categoryAPI.getParents(newEvent, user, respectFrontendRoles); for (Category cat : eventCategories) { categoryMaps.add(cat.getMap()); } eventMap.put("categories", categoryMaps); eventMap.put("rating", RatingAPI.getAverageRating(newEvent.getIdentifier())); eventMap.put("votes", RatingAPI.getRatingVotesNumber(newEvent.getIdentifier())); eventMap.put( "hasReadPermission", perAPI.doesUserHavePermission( newEvent, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles)); eventMap.put( "hasWritePermission", perAPI.doesUserHavePermission( newEvent, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles)); eventMap.put( "hasPublishPermission", perAPI.doesUserHavePermission( newEvent, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles)); eventMap.put( "readPermission", perAPI.doesUserHavePermission( newEvent, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles)); eventMap.put( "writePermission", perAPI.doesUserHavePermission( newEvent, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles)); eventMap.put( "publishPermission", perAPI.doesUserHavePermission( newEvent, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles)); eventMap.put("isDisconnected", UtilMethods.isSet(newEvent.getDisconnectedFrom())); CommentsWebAPI cAPI = new CommentsWebAPI(); cAPI.setUser(user); cAPI.setRespectFrontendRoles(respectFrontendRoles); eventMap.put("commentsCount", cAPI.getCommentsCount(newEvent.getInode())); HibernateUtil.commitTransaction(); } catch (Exception e) { HibernateUtil.rollbackTransaction(); disconnectEventErrors.add(e.getLocalizedMessage()); } finally { if (disconnectEventErrors.size() > 0) { eventMap.put("disconnectEventErrors", disconnectEventErrors); } } } } } return eventMap; }
public void processAction( ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { String cmd = req.getParameter("cmd"); String subcmd = ParamUtil.getString(req, "subcmd"); String referer = (req.getParameter("referer") != null) ? URLDecoder.decode(req.getParameter("referer"), "UTF-8") : "/c"; Logger.debug(DirectorAction.class, "DirectorAction :: referer=" + referer); // wraps request to get session object ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); // gets the session object for the messages HttpSession session = httpReq.getSession(); Logger.debug(DirectorAction.class, "I'm inside the Director cmd = " + cmd); Logger.debug(DirectorAction.class, "I'm inside the Director subcmd = " + subcmd); Logger.debug(DirectorAction.class, "I'm inside the Director referer = " + referer); // get the user User user = _getUser(req); // to order menu items if (cmd != null && cmd.equals("orderMenu")) { Logger.debug(DirectorAction.class, "Director :: orderMenu"); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/folders/order_menu"}); params.put("path", new String[] {req.getParameter("path")}); params.put("pagePath", new String[] {req.getParameter("pagePath")}); if (req.getParameter("openAll") != null) { params.put("openAll", new String[] {req.getParameter("openAll")}); } params.put("hostId", new String[] {req.getParameter("hostId")}); params.put("referer", new String[] {referer}); params.put("startLevel", new String[] {req.getParameter("startLevel")}); params.put("depth", new String[] {req.getParameter("depth")}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("orderContentlets")) { Logger.debug(DirectorAction.class, "Director :: orderContentlet"); Container container = (Container) InodeFactory.getInode(req.getParameter("containerId"), Container.class); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("pageId"), HTMLPage.class); boolean hasReadPermissionOnContainer = perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false); boolean hasWritePermissionOnPage = perAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user, false); if (!hasReadPermissionOnContainer || !hasWritePermissionOnPage) { throw new DotSecurityException( "User has no permission to reorder content on container = " + req.getParameter("container") + " on page = " + req.getParameter("htmlPage")); } java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/contentlet/order_contentlets"}); params.put("containerId", new String[] {req.getParameter("containerId")}); params.put("pageId", new String[] {req.getParameter("pageId")}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("newHTMLPage")) { Logger.debug(DirectorAction.class, "Director :: editHTMLPage"); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/htmlpages/edit_htmlpage"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {"0"}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("editHTMLPage")) { Logger.debug(DirectorAction.class, "Director :: editHTMLPage"); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); Identifier identifier = APILocator.getIdentifierAPI().find(htmlPage); // gets the current working asset WebAsset workingHTMLPage = (WebAsset) APILocator.getVersionableAPI() .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); if ("unlockHTMLPage".equals(subcmd)) { WebAssetFactory.unLockAsset(workingHTMLPage); } if (workingHTMLPage.isLocked() && !workingHTMLPage.getModUser().equals(user.getUserId())) { req.setAttribute(WebKeys.HTMLPAGE_EDIT, workingHTMLPage); setForward(req, "portlet.ext.director.unlock_htmlpage"); return; } else if (workingHTMLPage.isLocked()) { // it's locked by the same user WebAssetFactory.unLockAsset(workingHTMLPage); } java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/htmlpages/edit_htmlpage"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {workingHTMLPage.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("viewStatistics")) { Logger.debug(DirectorAction.class, "Director :: editHTMLPage"); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/htmlpageviews/view_htmlpage_views"}); params.put("htmlpage", new String[] {htmlPage.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getRenderURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("editFile")) { Logger.debug(DirectorAction.class, "Director :: editFile"); String fileAssetInode = ""; if (UtilMethods.isSet(req.getParameter("file"))) fileAssetInode = req.getParameter("file"); else return; Identifier identifier = APILocator.getIdentifierAPI().findFromInode(fileAssetInode); if (identifier.getAssetType().equals("contentlet")) { try { Contentlet cont = APILocator.getContentletAPI().find(fileAssetInode, user, false); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/contentlet/edit_contentlet"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {cont.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); } catch (DotSecurityException e) { Logger.error(this, e.getMessage()); return; } } else { try { // gets the current working asset WebAsset workingFile = (WebAsset) APILocator.getVersionableAPI() .findWorkingVersion( identifier, APILocator.getUserAPI().getSystemUser(), false); if ("unlockFile".equals(subcmd)) { WebAssetFactory.unLockAsset(workingFile); } if (workingFile.isLocked() && !workingFile.getModUser().equals(user.getUserId())) { req.setAttribute(WebKeys.FILE_EDIT, workingFile); setForward(req, "portlet.ext.director.unlock_file"); return; } else if (workingFile.isLocked()) { // it's locked by the same user WebAssetFactory.unLockAsset(workingFile); } java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/files/edit_file"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {workingFile.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); } catch (DotStateException e) { Logger.error(this, e.getMessage()); return; } catch (DotSecurityException e) { Logger.error(this, e.getMessage()); return; } } return; } if (cmd != null && cmd.equals("editTemplate")) { Logger.debug(DirectorAction.class, "Director :: editTemplate"); HTMLPage htmlPage = new HTMLPage(); WebAsset workingTemplate = new Template(); if (req.getParameter("htmlPage") != null) { htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); workingTemplate = HTMLPageFactory.getHTMLPageTemplate(htmlPage, true); } else if (req.getParameter("template") != null) { workingTemplate = (Template) InodeFactory.getInode(req.getParameter("template"), Template.class); } if ("unlockTemplate".equals(subcmd)) { WebAssetFactory.unLockAsset(workingTemplate); } if (workingTemplate.isLocked() && !workingTemplate.getModUser().equals(user.getUserId())) { req.setAttribute(WebKeys.HTMLPAGE_EDIT, htmlPage); req.setAttribute(WebKeys.TEMPLATE_EDIT, workingTemplate); setForward(req, "portlet.ext.director.unlock_template"); return; } else if (workingTemplate.isLocked()) { // it's locked by the same user WebAssetFactory.unLockAsset(workingTemplate); } java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/templates/edit_template"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {workingTemplate.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("publishHTMLPage")) { Logger.debug(DirectorAction.class, "Director :: publishHTMLPage"); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/htmlpages/publish_htmlpages"}); params.put("cmd", new String[] {"prepublish"}); params.put("publishInode", new String[] {htmlPage.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("editContainer")) { Logger.debug(DirectorAction.class, "Director :: editContainer" + subcmd); Container container = (Container) InodeFactory.getInode(req.getParameter("container"), Container.class); Identifier identifier = APILocator.getIdentifierAPI().find(container); // gets the current working asset WebAsset workingContainer = (WebAsset) APILocator.getVersionableAPI() .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); if ("unlockContainer".equals(subcmd)) { WebAssetFactory.unLockAsset(workingContainer); } if (workingContainer.isLocked() && !workingContainer.getModUser().equals(user.getUserId())) { req.setAttribute(WebKeys.CONTAINER_EDIT, workingContainer); setForward(req, "portlet.ext.director.unlock_container"); return; } else if (workingContainer.isLocked()) { // it's locked by the same user WebAssetFactory.unLockAsset(workingContainer); } java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/containers/edit_container"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {workingContainer.getInode() + ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("editLink")) { Logger.debug(DirectorAction.class, "Director :: editLink"); String popup = req.getParameter("popup"); Link link = (Link) InodeFactory.getInode(req.getParameter("link"), Link.class); Identifier identifier = APILocator.getIdentifierAPI().find(link); // gets the current working asset WebAsset workingLink = (WebAsset) APILocator.getVersionableAPI() .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); if ("unlockLink".equals(subcmd)) { WebAssetFactory.unLockAsset(workingLink); } if (workingLink.isLocked() && !workingLink.getModUser().equals(user.getUserId())) { req.setAttribute(WebKeys.LINK_EDIT, workingLink); if (UtilMethods.isSet(popup)) { Logger.debug(DirectorAction.class, "Going to SIX I have popup!!!!!!!!!!!!!!!!"); setForward(req, "portlet.ext.director.unlock_popup_link"); return; } else { Logger.debug(DirectorAction.class, "Going to FIVE I dont have popup!!!!!!!!!!!!!!!!"); setForward(req, "portlet.ext.director.unlock_link"); return; } } else if (workingLink.isLocked()) { // it's locked by the same user WebAssetFactory.unLockAsset(workingLink); } String popURL = ""; if (UtilMethods.isSet(popup)) { popURL = "_popup"; } java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/links/edit_link"}); params.put("cmd", new String[] {"edit"}); params.put("inode", new String[] {workingLink.getInode() + ""}); params.put("popup", new String[] {popup}); params.put("referer", new String[] {referer}); params.put( "child", new String[] {(req.getParameter("child") != null) ? req.getParameter("child") : ""}); params.put( "page_width", new String[] { (req.getParameter("page_width") != null) ? req.getParameter("page_width") : "" }); params.put( "browse", new String[] {(req.getParameter("browse") != null) ? req.getParameter("browse") : ""}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } if (cmd != null && cmd.equals("addChild")) { try { Logger.debug(DirectorAction.class, "Director :: addChild"); HibernateUtil.startTransaction(); Contentlet contentlet = new Contentlet(); String cInode = req.getParameter("contentlet"); if (InodeUtils.isSet(cInode)) { contentlet = conAPI.find(cInode, user, true); } Container container = (Container) InodeFactory.getInode(req.getParameter("container"), Container.class); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); boolean hasPermissionOnContainer = perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false); if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) hasPermissionOnContainer = true; boolean hasPermissionsOnPage = perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false); boolean duplicateContentCheck = false; if (!hasPermissionOnContainer || !hasPermissionsOnPage) { throw new DotSecurityException( "User has no permission to add content on container = " + req.getParameter("container") + " on page = " + req.getParameter("htmlPage")); } Identifier identifier = APILocator.getIdentifierAPI().find(contentlet); Identifier htmlPageIdentifier = APILocator.getIdentifierAPI().find(htmlPage); Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container); if (InodeUtils.isSet(identifier.getInode()) && InodeUtils.isSet(htmlPageIdentifier.getInode()) && InodeUtils.isSet(containerIdentifier.getInode())) { MultiTree mTree = new MultiTree( htmlPageIdentifier.getInode(), containerIdentifier.getInode(), identifier.getInode()); java.util.List<MultiTree> treeList = MultiTreeFactory.getMultiTree(htmlPage, container); for (int i = 0; i < treeList.size(); i++) { if (treeList.get(i).getChild().equals(identifier.getInode())) { duplicateContentCheck = true; session.setAttribute( "duplicatedErrorMessage", "Content already exists in the same container on the page"); } } if (!duplicateContentCheck) { MultiTreeFactory.saveMultiTree(mTree); // Updating the last mod user and last mod date of the page htmlPage.setModDate(new Date()); htmlPage.setModUser(user.getUserId()); HibernateUtil.saveOrUpdate(htmlPage); } } else { Logger.error( this, "Error found trying to associate the contentlet inode: " + contentlet.getInode() + "(iden: " + identifier.getInode() + ") " + "to the container: " + container.getInode() + "(iden: " + containerIdentifier.getInode() + ") " + "of the page: " + htmlPage.getInode() + "(iden: " + htmlPageIdentifier.getInode() + ") " + "the system was unable to find some the identifiers (tree error?)!"); } } catch (DotRuntimeException e) { Logger.error(this, "Unable to add content to page", e); } finally { try { HibernateUtil.commitTransaction(); } catch (Exception e) { session.setAttribute( "duplicatedErrorMessage", "Content already exists in the same container on the page"); // res.sendRedirect(referer); } } _sendToReferral(req, res, referer); return; } if (cmd != null && cmd.equals("removeChild")) { try { Logger.debug(DirectorAction.class, "Director :: removeChild"); HibernateUtil.startTransaction(); Contentlet contentlet = new Contentlet(); String cInode = req.getParameter("contentlet"); if (InodeUtils.isSet(cInode)) { contentlet = conAPI.find(cInode, user, true); } Container container = (Container) InodeFactory.getInode(req.getParameter("container"), Container.class); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); boolean hasPermissionOnPage = perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false); boolean hasPermissionOnContainer = perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false); if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) hasPermissionOnContainer = true; if (!hasPermissionOnContainer || !hasPermissionOnPage) { throw new DotSecurityException( "User has no permission to remove content from container = " + req.getParameter("container") + " on page = " + req.getParameter("htmlPage")); } Identifier identifier = APILocator.getIdentifierAPI().find(contentlet); Logger.debug( DirectorAction.class, "Identifier of Contentlet to be removed=" + identifier.getInode()); Contentlet contentletWorking = conAPI.findContentletByIdentifier( identifier.getInode(), false, contentlet.getLanguageId(), user, true); Contentlet liveContentlet = conAPI.findContentletByIdentifier( identifier.getInode(), false, contentlet.getLanguageId(), user, true); Logger.debug( DirectorAction.class, "\n\nContentlet Working to be removed=" + contentletWorking.getInode()); Identifier htmlPageIdentifier = APILocator.getIdentifierAPI().find(htmlPage); Identifier containerIdentifier = APILocator.getIdentifierAPI().find(container); MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier, identifier); Logger.debug(DirectorAction.class, "multiTree=" + multiTree); MultiTreeFactory.deleteMultiTree(multiTree); // Updating the last mod user and last mod date of the page htmlPage.setModDate(new Date()); htmlPage.setModUser(user.getUserId()); HibernateUtil.saveOrUpdate(htmlPage); } catch (DotRuntimeException e) { Logger.error(this, "Unable to remove content from page", e); } finally { HibernateUtil.commitTransaction(); } _sendToReferral(req, res, referer); return; } if (cmd != null && cmd.equals("makeHomePage")) { Logger.debug(DirectorAction.class, "Director :: makeHomePage"); if (InodeUtils.isSet(req.getParameter("htmlPage"))) { HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); Folder folder = APILocator.getFolderAPI().findParentFolder(htmlPage, user, false); UserPreference up = UserPreferencesFactory.getUserPreferenceValue( user.getUserId(), WebKeys.USER_PREFERENCE_HOME_PAGE); if (up.getId() > 0) { up.setValue(htmlPage.getURI(folder)); } else { up.setUserId(user.getUserId()); up.setPreference(WebKeys.USER_PREFERENCE_HOME_PAGE); up.setValue(htmlPage.getURI(folder)); } UserPreferencesFactory.saveUserPreference(up); } else { // the user clicked on set with no page that means unsetting the page UserPreferencesFactory.deleteUserPreference( user.getUserId(), WebKeys.USER_PREFERENCE_HOME_PAGE); } _sendToReferral(req, res, referer); return; } if (cmd != null && cmd.equals("moveUp")) { Logger.debug(DirectorAction.class, "Director :: moveUp"); Contentlet contentlet = new Contentlet(); String cInode = req.getParameter("contentlet"); if (InodeUtils.isSet(cInode)) { contentlet = conAPI.find(cInode, user, true); } Container container = (Container) InodeFactory.getInode(req.getParameter("container"), Container.class); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); boolean hasPermissionOnPage = perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false); boolean hasPermissionOnContainer = perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false); if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) hasPermissionOnContainer = true; if (!hasPermissionOnContainer || !hasPermissionOnPage) { throw new DotSecurityException( "User has no permission to reorder content on container = " + req.getParameter("container") + " on page = " + req.getParameter("htmlPage")); } String staticContainer = req.getParameter("static"); Logger.debug(DirectorAction.class, "staticContainer=" + staticContainer); java.util.List cletList = new ArrayList(); String sort = (container.getSortContentletsBy() == null) ? "tree_order" : container.getSortContentletsBy(); Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); Identifier idenContainer = APILocator.getIdentifierAPI().find(container); cletList = conAPI.findPageContentlets( idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, contentlet.getLanguageId(), user, false); Logger.debug(DirectorAction.class, "Number of contentlets = " + cletList.size()); int newPosition = cletList.indexOf(contentlet) - 1; if (newPosition >= 0) { idenContainer = APILocator.getIdentifierAPI().find(container); idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); int x = 0; Iterator i = cletList.iterator(); while (i.hasNext()) { Identifier iden; MultiTree multiTree; Contentlet c = (Contentlet) i.next(); Logger.debug(DirectorAction.class, "Contentlet inode = " + c.getInode()); if (newPosition == x) { iden = APILocator.getIdentifierAPI().find(contentlet); multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree); x++; } if (!c.getInode().equalsIgnoreCase(contentlet.getInode())) { iden = APILocator.getIdentifierAPI().find(c); multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree); x++; } } } _sendToReferral(req, res, referer); return; } if (cmd != null && cmd.equals("moveDown")) { Logger.debug(DirectorAction.class, "Director :: moveDown"); Contentlet contentlet = new Contentlet(); String cInode = req.getParameter("contentlet"); if (InodeUtils.isSet(cInode)) { contentlet = conAPI.find(cInode, user, true); } Container container = (Container) InodeFactory.getInode(req.getParameter("container"), Container.class); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); String staticContainer = req.getParameter("static"); boolean hasPermissionOnPage = perAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, user, false); boolean hasPermissionOnContainer = perAPI.doesUserHavePermission(container, PERMISSION_READ, user, false); if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) hasPermissionOnContainer = true; if (!hasPermissionOnContainer || !hasPermissionOnPage) { throw new DotSecurityException( "User has no permission to reorder content on container = " + req.getParameter("container") + " on page = " + req.getParameter("htmlPage")); } Logger.debug(DirectorAction.class, "staticContainer=" + staticContainer); java.util.List cletList = new ArrayList(); String sort = (container.getSortContentletsBy() == null) ? "tree_order" : container.getSortContentletsBy(); Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); Identifier idenContainer = APILocator.getIdentifierAPI().find(container); cletList = conAPI.findPageContentlets( idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, contentlet.getLanguageId(), user, false); Logger.debug(DirectorAction.class, "Number of contentlets = " + cletList.size()); int newPosition = cletList.indexOf(contentlet) + 1; if (newPosition < cletList.size()) { idenContainer = APILocator.getIdentifierAPI().find(container); idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); int x = 0; Iterator i = cletList.iterator(); while (i.hasNext()) { Identifier iden; MultiTree multiTree; Contentlet c = (Contentlet) i.next(); Logger.debug(DirectorAction.class, "Contentlet inode = " + c.getInode()); if (!c.getInode().equalsIgnoreCase(contentlet.getInode())) { iden = APILocator.getIdentifierAPI().find(c); multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree); x++; } if (newPosition == x) { iden = APILocator.getIdentifierAPI().find(contentlet); multiTree = MultiTreeFactory.getMultiTree(idenHtmlPage, idenContainer, iden); multiTree.setTreeOrder(x); MultiTreeFactory.saveMultiTree(multiTree); x++; } } } _sendToReferral(req, res, referer); return; } if (cmd != null && cmd.equals("unlock")) { Logger.debug(DirectorAction.class, "Director :: unlock Contentlet"); Contentlet contentlet = new Contentlet(); String cInode = req.getParameter("contentlet"); if (InodeUtils.isSet(cInode)) { contentlet = conAPI.find(cInode, user, true); } conAPI.unlock(contentlet, user, true); } if (cmd != null && cmd.equals("createForm")) { Logger.debug(DirectorAction.class, "Director :: createForrm"); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/structure/edit_structure"}); params.put("structureType", new String[] {Integer.toString(Structure.STRUCTURE_TYPE_FORM)}); params.put("cmd", new String[] {"null"}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; } Contentlet contentlet = new Contentlet(); String cInode = req.getParameter("contentlet"); if (InodeUtils.isSet(cInode)) { contentlet = conAPI.find(cInode, user, true); } if (contentlet == null) { throw new DotStateException("Trying to edit an invalid contentlet - inode:" + cInode); } Container container = (Container) InodeFactory.getInode(req.getParameter("container"), Container.class); HTMLPage htmlPage = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlPage"), HTMLPage.class); Logger.debug(DirectorAction.class, "contentlet=" + contentlet.getInode()); String contentletInode = ""; if (InodeUtils.isSet(contentlet.getInode())) { Identifier identifier = APILocator.getIdentifierAPI().find(contentlet); // gets the current working asset Contentlet workingContentlet = conAPI.findContentletByIdentifier( identifier.getInode(), false, contentlet.getLanguageId(), user, false); Logger.debug(DirectorAction.class, "workingContentlet=" + workingContentlet.getInode()); Logger.debug( DirectorAction.class, "workingContentlet.getModUser()=" + workingContentlet.getModUser()); Logger.debug( DirectorAction.class, "workingContentlet.isLocked()=" + workingContentlet.isLocked()); contentletInode = workingContentlet.getInode(); } else { contentletInode = contentlet.getInode(); } Logger.debug(DirectorAction.class, "Director :: Edit Contentlet"); java.util.Map params = new java.util.HashMap(); params.put("struts_action", new String[] {"/ext/contentlet/edit_contentlet"}); String cmdAux = (cmd.equals("newedit") ? cmd : "edit"); params.put("cmd", new String[] {cmdAux}); params.put("htmlpage_inode", new String[] {htmlPage.getInode() + ""}); params.put("contentcontainer_inode", new String[] {container.getInode() + ""}); params.put("inode", new String[] {contentletInode + ""}); if (InodeUtils.isSet(req.getParameter("selectedStructure"))) { params.put("selectedStructure", new String[] {req.getParameter("selectedStructure") + ""}); } params.put( "lang", new String[] {(req.getParameter("language") != null) ? req.getParameter("language") : ""}); params.put("referer", new String[] {referer}); String af = com.dotmarketing.util.PortletURLUtil.getActionURL( httpReq, WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, af); return; }