Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
src/main/java/com/github/junrar/Archive.java
### 代码内容：
package com.github.junrar;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.github.junrar.exception.RarException;
import com.github.junrar.exception.RarException.RarExceptionType;
import com.github.junrar.impl.FileVolumeManager;
import com.github.junrar.io.IReadOnlyAccess;
import com.github.junrar.rarfile.AVHeader;
import com.github.junrar.rarfile.BaseBlock;
import com.github.junrar.rarfile.BlockHeader;
import com.github.junrar.rarfile.CommentHeader;
import com.github.junrar.rarfile.EAHeader;
import com.github.junrar.rarfile.EndArcHeader;
import com.github.junrar.rarfile.FileHeader;
import com.github.junrar.rarfile.MacInfoHeader;
import com.github.junrar.rarfile.MainHeader;
import com.github.junrar.rarfile.MarkHeader;
import com.github.junrar.rarfile.ProtectHeader;
import com.github.junrar.rarfile.SignHeader;
import com.github.junrar.rarfile.SubBlockHeader;
import com.github.junrar.rarfile.UnixOwnersHeader;
import com.github.junrar.rarfile.UnrarHeadertype;
import com.github.junrar.unpack.ComprDataIO;
import com.github.junrar.unpack.Unpack;

/**
 * The Main Rar Class; represents a rar Archive
 *
 * @author $LastChangedBy$
 * @version $LastChangedRevision$
 */
public class Archive implements Closeable {
	private static Logger logger = Logger.getLogger(Archive.class.getName());

	private IReadOnlyAccess rof;

	private final UnrarCallback unrarCallback;

	private final ComprDataIO dataIO;

	private final List<BaseBlock> headers = new ArrayList<BaseBlock>();

	private MarkHeader markHead = null;

	private MainHeader newMhd = null;

	private Unpack unpack;

	private int currentHeaderIndex;

	/** Size of packed data in current file. */
	private long totalPackedSize = 0L;

	/** Number of bytes of compressed data read from current file. */
	private long totalPackedRead = 0L;

	private VolumeManager volumeManager;
	private Volume volume;

	public Archive(VolumeManager volumeManager) throws RarException,
			IOException {
		this(volumeManager, null);
	}

	/**
	 * create a new archive object using the given {@link VolumeManager}
	 *
	 * @param volumeManager
	 *            the the {@link VolumeManager} that will provide volume stream
	 *            data
	 * @throws RarException
	 */
	public Archive(VolumeManager volumeManager, UnrarCallback unrarCallback)
			throws RarException, IOException {
		this.volumeManager = volumeManager;
		this.unrarCallback = unrarCallback;

		setVolume(this.volumeManager.nextArchive(this, null));
		dataIO = new ComprDataIO(this);
	}

	public Archive(File firstVolume) throws RarException, IOException {
		this(new FileVolumeManager(firstVolume), null);
	}

	public Archive(File firstVolume, UnrarCallback unrarCallback)
			throws RarException, IOException {
		this(new FileVolumeManager(firstVolume), unrarCallback);
	}

	// public File getFile() {
	// return file;
	// }
	//
	// void setFile(File file) throws IOException {
	// this.file = file;
	// setFile(new ReadOnlyAccessFile(file), file.length());
	// }

	private void setFile(IReadOnlyAccess file, long length) throws IOException {
		totalPackedSize = 0L;
		totalPackedRead = 0L;
		close();
		rof = file;
		try {
			readHeaders(length);
		} catch (Exception e) {
			logger.log(Level.WARNING,
					"exception in archive constructor maybe file is encrypted "
							+ "or currupt", e);
			// ignore exceptions to allow exraction of working files in
			// corrupt archive
		}
		// Calculate size of packed data
		for (BaseBlock block : headers) {
			if (block.getHeaderType() == UnrarHeadertype.FileHeader) {
				totalPackedSize += ((FileHeader) block).getFullPackSize();
			}
		}
		if (unrarCallback != null) {
			unrarCallback.volumeProgressChanged(totalPackedRead,
					totalPackedSize);
		}
	}

	public void bytesReadRead(int count) {
		if (count > 0) {
			totalPackedRead += count;
			if (unrarCallback != null) {
				unrarCallback.volumeProgressChanged(totalPackedRead,
						totalPackedSize);
			}
		}
	}

	public IReadOnlyAccess getRof() {
		return rof;
	}

	/**
	 * Gets all of the headers in the archive.
	 *
	 * @return returns the headers.
	 */
	public List<BaseBlock> getHeaders() {
		return new ArrayList<BaseBlock>(headers);
	}

	/**
	 * @return returns all file headers of the archive
	 */
	public List<FileHeader> getFileHeaders() {
		List<FileHeader> list = new ArrayList<FileHeader>();
		for (BaseBlock block : headers) {
			if (block.getHeaderType().equals(UnrarHeadertype.FileHeader)) {
				list.add((FileHeader) block);
			}
		}
		return list;
	}

	public FileHeader nextFileHeader() {
		int n = headers.size();
		while (currentHeaderIndex < n) {
			BaseBlock block = headers.get(currentHeaderIndex++);
			if (block.getHeaderType() == UnrarHeadertype.FileHeader) {
				return (FileHeader) block;
			}
		}
		return null;
	}

	public UnrarCallback getUnrarCallback() {
		return unrarCallback;
	}

	/**
	 *
	 * @return whether the archive is encrypted
	 */
	public boolean isEncrypted() {
		if (newMhd != null) {
			return newMhd.isEncrypted();
		} else {
			throw new NullPointerException("mainheader is null");
		}
	}

	/**
	 * Read the headers of the archive
	 *
	 * @param fileLength
	 *            Length of file.
	 * @throws RarException
	 */
	private void readHeaders(long fileLength) throws IOException, RarException {
		markHead = null;
		newMhd = null;
		headers.clear();
		currentHeaderIndex = 0;
		int toRead = 0;

		while (true) {
			int size = 0;
			long newpos = 0;
			byte[] baseBlockBuffer = new byte[BaseBlock.BaseBlockSize];

			long position = rof.getPosition();

			// Weird, but is trying to read beyond the end of the file
			if (position >= fileLength) {
				break;
			}

			// logger.info("\n--------reading header--------");
			size = rof.readFully(baseBlockBuffer, BaseBlock.BaseBlockSize);
			if (size == 0) {
				break;
			}
			BaseBlock block = new BaseBlock(baseBlockBuffer);

			block.setPositionInFile(position);

			switch (block.getHeaderType()) {

			case MarkHeader:
				markHead = new MarkHeader(block);
				if (!markHead.isSignature()) {
					throw new RarException(
							RarException.RarExceptionType.badRarArchive);
				}
				headers.add(markHead);
				// markHead.print();
				break;

			case MainHeader:
				toRead = block.hasEncryptVersion() ? MainHeader.mainHeaderSizeWithEnc
						: MainHeader.mainHeaderSize;
				byte[] mainbuff = new byte[toRead];
				rof.readFully(mainbuff, toRead);
				MainHeader mainhead = new MainHeader(block, mainbuff);
				headers.add(mainhead);
				this.newMhd = mainhead;
				if (newMhd.isEncrypted()) {
					throw new RarException(
							RarExceptionType.rarEncryptedException);
				}
				// mainhead.print();
				break;

			case SignHeader:
				toRead = SignHeader.signHeaderSize;
				byte[] signBuff = new byte[toRead];
				rof.readFully(signBuff, toRead);
				SignHeader signHead = new SignHeader(block, signBuff);
				headers.add(signHead);
				// logger.info("HeaderType: SignHeader");

				break;

			case AvHeader:
				toRead = AVHeader.avHeaderSize;
				byte[] avBuff = new byte[toRead];
				rof.readFully(avBuff, toRead);
				AVHeader avHead = new AVHeader(block, avBuff);
				headers.add(avHead);
				// logger.info("headertype: AVHeader");
				break;

			case CommHeader:
				toRead = CommentHeader.commentHeaderSize;
				byte[] commBuff = new byte[toRead];
				rof.readFully(commBuff, toRead);
				CommentHeader commHead = new CommentHeader(block, commBuff);
				headers.add(commHead);
				// logger.info("method: "+commHead.getUnpMethod()+"; 0x"+
				// Integer.toHexString(commHead.getUnpMethod()));
				newpos = commHead.getPositionInFile()
						+ commHead.getHeaderSize();
				rof.setPosition(newpos);

				break;
			case EndArcHeader:

				toRead = 0;
				if (block.hasArchiveDataCRC()) {
					toRead += EndArcHeader.endArcArchiveDataCrcSize;
				}
				if (block.hasVolumeNumber()) {
					toRead += EndArcHeader.endArcVolumeNumberSize;
				}
				EndArcHeader endArcHead;
				if (toRead > 0) {
					byte[] endArchBuff = new byte[toRead];
					rof.readFully(endArchBuff, toRead);
					endArcHead = new EndArcHeader(block, endArchBuff);
					// logger.info("HeaderType: endarch\ndatacrc:"+
					// endArcHead.getArchiveDataCRC());
				} else {
					// logger.info("HeaderType: endarch - no Data");
					endArcHead = new EndArcHeader(block, null);
				}
				headers.add(endArcHead);
				// logger.info("\n--------end header--------");
				return;

			default:
				byte[] blockHeaderBuffer = new byte[BlockHeader.blockHeaderSize];
				rof.readFully(blockHeaderBuffer, BlockHeader.blockHeaderSize);
				BlockHeader blockHead = new BlockHeader(block,
						blockHeaderBuffer);

				switch (blockHead.getHeaderType()) {
				case NewSubHeader:
				case FileHeader:
					toRead = blockHead.getHeaderSize()
							- BlockHeader.BaseBlockSize
							- BlockHeader.blockHeaderSize;
					byte[] fileHeaderBuffer = new byte[toRead];
					rof.readFully(fileHeaderBuffer, toRead);

					FileHeader fh = new FileHeader(blockHead, fileHeaderBuffer);
					headers.add(fh);
					newpos = fh.getPositionInFile() + fh.getHeaderSize()
							+ fh.getFullPackSize();
					rof.setPosition(newpos);
					break;

				case ProtectHeader:
					toRead = blockHead.getHeaderSize()
							- BlockHeader.BaseBlockSize
							- BlockHeader.blockHeaderSize;
					byte[] protectHeaderBuffer = new byte[toRead];
					rof.readFully(protectHeaderBuffer, toRead);
					ProtectHeader ph = new ProtectHeader(blockHead,
							protectHeaderBuffer);

					newpos = ph.getPositionInFile() + ph.getHeaderSize()
							+ ph.getDataSize();
					rof.setPosition(newpos);
					break;

				case SubHeader: {
					byte[] subHeadbuffer = new byte[SubBlockHeader.SubBlockHeaderSize];
					rof.readFully(subHeadbuffer,
							SubBlockHeader.SubBlockHeaderSize);
					SubBlockHeader subHead = new SubBlockHeader(blockHead,
							subHeadbuffer);
					subHead.print();
					switch (subHead.getSubType()) {
					case MAC_HEAD: {
						byte[] macHeaderbuffer = new byte[MacInfoHeader.MacInfoHeaderSize];
						rof.readFully(macHeaderbuffer,
								MacInfoHeader.MacInfoHeaderSize);
						MacInfoHeader macHeader = new MacInfoHeader(subHead,
								macHeaderbuffer);
						macHeader.print();
						headers.add(macHeader);

						break;
					}
					// TODO implement other subheaders
					case BEEA_HEAD:
						break;
					case EA_HEAD: {
						byte[] eaHeaderBuffer = new byte[EAHeader.EAHeaderSize];
						rof.readFully(eaHeaderBuffer, EAHeader.EAHeaderSize);
						EAHeader eaHeader = new EAHeader(subHead,
								eaHeaderBuffer);
						eaHeader.print();
						headers.add(eaHeader);

						break;
					}
					case NTACL_HEAD:
						break;
					case STREAM_HEAD:
						break;
					case UO_HEAD:
						toRead = subHead.getHeaderSize();
						toRead -= BaseBlock.BaseBlockSize;
						toRead -= BlockHeader.blockHeaderSize;
						toRead -= SubBlockHeader.SubBlockHeaderSize;
						byte[] uoHeaderBuffer = new byte[toRead];
						rof.readFully(uoHeaderBuffer, toRead);
						UnixOwnersHeader uoHeader = new UnixOwnersHeader(
								subHead, uoHeaderBuffer);
						uoHeader.print();
						headers.add(uoHeader);
						break;
					default:
						break;
					}

					break;
				}
				default:
					logger.warning("Unknown Header");
					throw new RarException(RarExceptionType.notRarArchive);

				}
			}
			// logger.info("\n--------end header--------");
		}
	}

	/**
	 * Extract the file specified by the given header and write it to the
	 * supplied output stream
	 *
	 * @param hd
	 *            the header to be extracted
	 * @param os
	 *            the outputstream
	 * @throws RarException
	 */
	public void extractFile(FileHeader hd, OutputStream os) throws RarException {
		if (!headers.contains(hd)) {
			throw new RarException(RarExceptionType.headerNotInArchive);
		}
		try {
			doExtractFile(hd, os);
		} catch (Exception e) {
			if (e instanceof RarException) {
				throw (RarException) e;
			} else {
				throw new RarException(e);
			}
		}
	}

	/**
	 * Returns an {@link InputStream} that will allow to read the file and
	 * stream it. Please note that this method will create a new Thread and an a
	 * pair of Pipe streams.
	 *
	 * @param hd
	 *            the header to be extracted
	 * @throws RarException
	 * @throws IOException
	 *             if any IO error occur
	 */
	public InputStream getInputStream(final FileHeader hd) throws RarException,
			IOException {
		final PipedInputStream in = new PipedInputStream(32 * 1024);
		final PipedOutputStream out = new PipedOutputStream(in);

		// creates a new thread that will write data to the pipe. Data will be
		// available in another InputStream, connected to the OutputStream.
		new Thread(new Runnable() {
			public void run() {
				try {
					extractFile(hd, out);
				} catch (RarException e) {
				} finally {
					try {
						out.close();
					} catch (IOException e) {
					}
				}
			}
		}).start();

		return in;
	}

	private void doExtractFile(FileHeader hd, OutputStream os)
			throws RarException, IOException {
		dataIO.init(os);
		dataIO.init(hd);
		dataIO.setUnpFileCRC(this.isOldFormat() ? 0 : 0xffFFffFF);
		if (unpack == null) {
			unpack = new Unpack(dataIO);
		}
		if (!hd.isSolid()) {
			unpack.init(null);
		}
		unpack.setDestSize(hd.getFullUnpackSize());
		try {
			unpack.doUnpack(hd.getUnpVersion(), hd.isSolid());
			// Verify file CRC
			hd = dataIO.getSubHeader();
			long actualCRC = hd.isSplitAfter() ? ~dataIO.getPackedCRC()
					: ~dataIO.getUnpFileCRC();
			int expectedCRC = hd.getFileCRC();
			if (actualCRC != expectedCRC) {
				throw new RarException(RarExceptionType.crcError);
			}
			// if (!hd.isSplitAfter()) {
			// // Verify file CRC
			// if(~dataIO.getUnpFileCRC() != hd.getFileCRC()){
			// throw new RarException(RarExceptionType.crcError);
			// }
			// }
		} catch (Exception e) {
			unpack.cleanUp();
			if (e instanceof RarException) {
				// throw new RarException((RarException)e);
				throw (RarException) e;
			} else {
				throw new RarException(e);
			}
		}
	}

	/**
	 * @return returns the main header of this archive
	 */
	public MainHeader getMainHeader() {
		return newMhd;
	}

	/**
	 * @return whether the archive is old format
	 */
	public boolean isOldFormat() {
		return markHead.isOldFormat();
	}

	/** Close the underlying compressed file. */
	public void close() throws IOException {
		if (rof != null) {
			rof.close();
			rof = null;
		}
		if (unpack != null) {
			unpack.cleanUp();
		}
	}

	/**
	 * @return the volumeManager
	 */
	public VolumeManager getVolumeManager() {
		return volumeManager;
	}

	/**
	 * @param volumeManager
	 *            the volumeManager to set
	 */
	public void setVolumeManager(VolumeManager volumeManager) {
		this.volumeManager = volumeManager;
	}

	/**
	 * @return the volume
	 */
	public Volume getVolume() {
		return volume;
	}

	/**
	 * @param volume
	 *            the volume to set
	 * @throws IOException
	 */
	public void setVolume(Volume volume) throws IOException {
		this.volume = volume;
		setFile(volume.getReadOnlyAccess(), volume.getLength());
	}
}


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
src/com/dotmarketing/cms/webforms/action/SubmitWebFormAction.java
### 代码内容：
package com.dotmarketing.cms.webforms.action;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dotcms.enterprise.PasswordFactoryProxy;
import com.dotcms.repackage.nl.captcha.Captcha;
import com.dotcms.repackage.org.apache.struts.Globals;
import com.dotcms.repackage.org.apache.struts.action.ActionErrors;
import com.dotcms.repackage.org.apache.struts.action.ActionForm;
import com.dotcms.repackage.org.apache.struts.action.ActionForward;
import com.dotcms.repackage.org.apache.struts.action.ActionMapping;
import com.dotcms.repackage.org.apache.struts.action.ActionMessage;
import com.dotcms.repackage.org.apache.struts.actions.DispatchAction;
import com.dotcms.util.SecurityUtils;
import com.dotmarketing.beans.Host;
import com.dotmarketing.beans.UserProxy;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.Role;
import com.dotmarketing.business.web.HostWebAPI;
import com.dotmarketing.business.web.WebAPILocator;
import com.dotmarketing.cms.factories.PublicAddressFactory;
import com.dotmarketing.cms.factories.PublicCompanyFactory;
import com.dotmarketing.cms.factories.PublicEncryptionFactory;
import com.dotmarketing.db.HibernateUtil;
import com.dotmarketing.exception.DotRuntimeException;
import com.dotmarketing.factories.ClickstreamFactory;
import com.dotmarketing.factories.EmailFactory;
import com.dotmarketing.factories.InodeFactory;
import com.dotmarketing.portlets.categories.model.Category;
import com.dotmarketing.portlets.user.factories.UserCommentsFactory;
import com.dotmarketing.portlets.user.model.UserComment;
import com.dotmarketing.portlets.webforms.model.WebForm;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.InodeUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.WebKeys;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import com.liferay.util.servlet.UploadServletRequest;

/**
 *
 * @author David
 * @version $Revision: 1.5 $ $Date: 2007/07/18 16:48:42 $
 */
public final class SubmitWebFormAction extends DispatchAction {

	HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI();

	@SuppressWarnings("unchecked")
	public ActionForward unspecified(ActionMapping rMapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		ActionErrors errors = new ActionErrors();
		//Email parameters
		HttpSession session = request.getSession();
		Host currentHost = hostWebAPI.getCurrentHost(request);
		User currentUser = (User) session.getAttribute(WebKeys.CMS_USER);

		String method = request.getMethod();
		String errorURL = request.getParameter("errorURL");
		errorURL = (!UtilMethods.isSet(errorURL) ? request.getHeader("referer") : errorURL);
		if(errorURL.indexOf("?") > -1)
		{
			errorURL = errorURL.substring(0,errorURL.lastIndexOf("?"));
		}
		String x = request.getRequestURI();
		if(request.getParameterMap().size() <2){

			return null;

		}

		//Checking for captcha
		boolean useCaptcha = Config.getBooleanProperty("FORCE_CAPTCHA",true);
		if(!useCaptcha){
			useCaptcha = new Boolean(request.getParameter("useCaptcha")).booleanValue();
		}

		String captcha = request.getParameter("captcha");
		if (useCaptcha) {
		    Captcha captchaObj = (Captcha) session.getAttribute(Captcha.NAME);
            String captchaSession=captchaObj!=null ? captchaObj.getAnswer() : null;

			if(captcha ==null && Config.getBooleanProperty("FORCE_CAPTCHA",true)){
				response.getWriter().write("Captcha is required to submit this form ( FORCE_CAPTCHA=true ).<br>To change this, edit the dotmarketing-config.properties and set FORCE_CAPTCHA=false");
				return null;
			}

			if(!UtilMethods.isSet(captcha) || !UtilMethods.isSet(captchaSession) || !captcha.equals(captchaSession)) {
				errors.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", "Validation Image"));
				request.setAttribute(Globals.ERROR_KEY, errors);
				session.setAttribute(Globals.ERROR_KEY, errors);
				String queryString = request.getQueryString();
				String invalidCaptchaURL = request.getParameter("invalidCaptchaReturnUrl");
				if(!UtilMethods.isSet(invalidCaptchaURL)) {
					invalidCaptchaURL = errorURL;
				}
				ActionForward af = new ActionForward();
					af.setRedirect(true);
					if (UtilMethods.isSet(queryString)) {

						af.setPath(invalidCaptchaURL + "?" + queryString + "&error=Validation-Image");
					} else {
						af.setPath(invalidCaptchaURL + "?error=Validation-Image");
					}

				return af;
			}

		}

		Map<String, Object> parameters = null;
		if (request instanceof UploadServletRequest)
		{
			UploadServletRequest uploadReq = (UploadServletRequest) request;
			parameters = new HashMap<String, Object> (uploadReq.getParameterMap());
			for (Entry<String, Object> entry : parameters.entrySet())
			{
				if(entry.getKey().toLowerCase().indexOf("file") > -1 && !entry.getKey().equals("attachFiles"))
				{
					parameters.put(entry.getKey(), uploadReq.getFile(entry.getKey()));
				}
			}
		}
		else
		{
			parameters = new HashMap<String, Object> (request.getParameterMap());
		}

		Set<String> toValidate = new java.util.HashSet<String>(parameters.keySet());

		//Enhancing the ignored parameters not to be send in the email
		String ignoredParameters = (String) EmailFactory.getMapValue("ignore", parameters);
		if(ignoredParameters == null)
		{
			ignoredParameters = "";
		}
		ignoredParameters += ":useCaptcha:captcha:invalidCaptchaReturnUrl:return:returnUrl:errorURL:ignore:to:from:cc:bcc:dispatch:order:prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:";
		parameters.put("ignore", ignoredParameters);

		// getting categories from inodes
		// getting parent category name and child categories name
		// and replacing the "categories" parameter
		String categories = "";
		String[] categoriesArray = request.getParameterValues("categories");
		if (categoriesArray != null) {
			HashMap hashCategories = new HashMap<String, String>();
			for (int i = 0; i < categoriesArray.length; i++) {
				Category node = (Category) InodeFactory.getInode(categoriesArray[i], Category.class);
				Category parent = (Category) InodeFactory.getParentOfClass(node, Category.class);
				String parentCategoryName = parent.getCategoryName();

				if (hashCategories.containsKey(parentCategoryName)) {
					String childCategoryName = (String) hashCategories.get(parentCategoryName);
					if (UtilMethods.isSet(childCategoryName)) {
						childCategoryName += ", ";
					}
					childCategoryName += node.getCategoryName();
					hashCategories.put(parentCategoryName, childCategoryName);
				}
				else {
					hashCategories.put(parentCategoryName, node.getCategoryName());
				}
			}

			Set<String> keySet = hashCategories.keySet();
			for (String stringKey: keySet) {

				if (UtilMethods.isSet(categories)) {
					categories += "; ";
				}
				categories += stringKey + " : " + (String) hashCategories.get(stringKey);
				parameters.put(stringKey, (String) hashCategories.get(stringKey));
			}
			parameters.remove("categories");
		}

		WebForm webForm = new WebForm();
		try
		{
			/*validation parameter should ignore the returnUrl and erroURL field in the spam check*/
			String[] removeParams = ignoredParameters.split(":");
			for(String param : removeParams){
				toValidate.remove(param);
			}

			parameters.put("request", request);
			parameters.put("response", response);

			//Sending the email
			webForm = EmailFactory.sendParameterizedEmail(parameters, toValidate, currentHost, currentUser);

			webForm.setCategories(categories);

			if(UtilMethods.isSet(request.getParameter("createAccount")) && request.getParameter("createAccount").equals("true"))
			{
				//if we create account set to true we create a user account and add user comments.
				createAccount(webForm, request);
				try{
    				String userInode = webForm.getUserInode();
    				String customFields = webForm.getCustomFields();
    				customFields += " User Inode = " + String.valueOf(userInode) + " | ";
    				webForm.setCustomFields(customFields);
				}
				catch(Exception e){

				}

			}

            if(UtilMethods.isSet(webForm.getFormType())){
                HibernateUtil.saveOrUpdate(webForm);
            }

			if (request.getParameter("return") != null)
			{
				ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("return")));
				af.setRedirect(true);
				return af;
			}
			else if (request.getParameter("returnUrl") != null)
			{
				ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, request.getParameter("returnUrl")));
				af.setRedirect(true);
				return af;
			}
			else
			{
				return rMapping.findForward("thankYouPage");
			}

        }
        catch (DotRuntimeException e)
        {
            errors.add(Globals.ERROR_KEY, new ActionMessage("error.processing.your.email"));
            request.getSession().setAttribute(Globals.ERROR_KEY, errors);

            String queryString = request.getQueryString();

            if (queryString == null) {
                java.util.Enumeration<String> parameterNames = request.getParameterNames();
                queryString = "";
                String parameterName;
                for (; parameterNames.hasMoreElements();) {
                    parameterName = parameterNames.nextElement();

                    if (0 < queryString.length()) {
                        queryString = queryString + "&" + parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName));
                    } else {
                        queryString = parameterName + "=" + UtilMethods.encodeURL(request.getParameter(parameterName));
                    }
                }
            }

            ActionForward af;
            if (UtilMethods.isSet(queryString)) {
                af = new ActionForward(SecurityUtils.stripReferer(request, errorURL + "?" + queryString));
            } else {
                af = new ActionForward(SecurityUtils.stripReferer(request, errorURL));
            }

            af.setRedirect(true);

            return af;
        }

	}
	private void createAccount(WebForm form, HttpServletRequest request) throws Exception {

		User user = APILocator.getUserAPI().loadByUserByEmail(form.getEmail(), APILocator.getUserAPI().getSystemUser(), false);
		User defaultUser = APILocator.getUserAPI().getDefaultUser();
		Date today = new Date();

		if (user.isNew() || (!user.isNew() && user.getLastLoginDate() == null)) {

			// ### CREATE USER ###
			Company company = PublicCompanyFactory.getDefaultCompany();
			user.setEmailAddress(form.getEmail().trim().toLowerCase());
			user.setFirstName(form.getFirstName() == null ? "" : form.getFirstName());
			user.setMiddleName(form.getMiddleName() == null ? "" : form.getMiddleName());
			user.setLastName(form.getLastName() == null ? "" : form.getLastName());
			user.setNickName("");
			user.setCompanyId(company.getCompanyId());
			user.setGreeting("Welcome, " + user.getFullName() + "!");

			// Set defaults values
			if (user.isNew()) {
				//if it's a new user we set random password
				String pass = PublicEncryptionFactory.getRandomPassword();

                // Use new password hash method
                user.setPassword(PasswordFactoryProxy.generateHash(pass));

				user.setLanguageId(defaultUser.getLanguageId());
				user.setTimeZoneId(defaultUser.getTimeZoneId());
				user.setSkinId(defaultUser.getSkinId());
				user.setDottedSkins(defaultUser.isDottedSkins());
				user.setRoundedSkins(defaultUser.isRoundedSkins());
				user.setResolution(defaultUser.getResolution());
				user.setRefreshRate(defaultUser.getRefreshRate());
				user.setLayoutIds("");
				user.setActive(true);
				user.setCreateDate(today);
			}
			APILocator.getUserAPI().save(user,APILocator.getUserAPI().getSystemUser(),false);
			// ### END CREATE USER ###

			// ### CREATE USER_PROXY ###
			UserProxy userProxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user.getUserId(),APILocator.getUserAPI().getSystemUser(), false);
			userProxy.setPrefix("");
			userProxy.setTitle(form.getTitle());
			userProxy.setOrganization(form.getOrganization());
			userProxy.setUserId(user.getUserId());
			com.dotmarketing.business.APILocator.getUserProxyAPI().saveUserProxy(userProxy,APILocator.getUserAPI().getSystemUser(), false);
			// ### END CRETE USER_PROXY ###

			// saving user inode on web form
			form.setUserInode(userProxy.getInode());
			if(UtilMethods.isSet(form.getFormType())){
			HibernateUtil.saveOrUpdate(form);
			}

			///// WE CAN DO THIS! BUT WE NEED TO ADD CATEGORIES TO WEBFORM AND ALSO CHANGE THE PROCESSES THAT
			//// CREATE THE EXCEL DOWNLOAD FROM WEB FORMS. I DIDN'T ADD IT SO I COMMENTED THIS CODE FOR NOW
			//get the old categories, wipe them out
			/*
			List<Category> categories = InodeFactory.getParentsOfClass(userProxy, Category.class);
			for (int i = 0; i < categories.size(); i++) {
				categories.get(i).deleteChild(userProxy);
			}
			 */
			// Save the new categories
			/*String[] arr = form.getCategories();
			if (arr != null) {
				for (int i = 0; i < arr.length; i++) {
					Category node = (Category) InodeFactory.getInode(arr[i], Category.class);
					node.addChild(userProxy);
				}
			}*/

			// ### CREATE ADDRESS ###
			try {
				List<Address> addresses = PublicAddressFactory.getAddressesByUserId(user.getUserId());
				Address address = (addresses.size() > 0 ? addresses.get(0) : PublicAddressFactory.getInstance());
				address.setStreet1(form.getAddress1() == null ? "" : form.getAddress1());
				address.setStreet2(form.getAddress2() == null ? "" : form.getAddress2());
				address.setCity(form.getCity() == null ? "" : form.getCity());
				address.setState(form.getState() == null ? "" : form.getState());
				address.setZip(form.getZip() == null ? "" : form.getZip());
				String phone = form.getPhone();
				address.setPhone(phone == null ? "" : phone);
				address.setUserId(user.getUserId());
				address.setCompanyId(company.getCompanyId());
				PublicAddressFactory.save(address);
			} catch (Exception ex) {
				Logger.error(this,ex.getMessage(),ex);
			}

			Role defaultRole = com.dotmarketing.business.APILocator.getRoleAPI().loadRoleByKey(Config.getStringProperty("CMS_VIEWER_ROLE"));
			String roleId = defaultRole.getId();
			if (InodeUtils.isSet(roleId)) {
				com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, user);
			}
		}
		// ### END CREATE ADDRESS ###

		// ### BUILD THE USER COMMENT ###
		addUserComments(user.getUserId(),form,request);
		// ### END BUILD THE USER COMMENT ###

		/* associate user with their clickstream request */
		if(Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)){
			ClickstreamFactory.setClickStreamUser(user.getUserId(), request);
		}

	}

	private void addUserComments(String userid, WebForm webForm, HttpServletRequest request) throws Exception {

		Date now = new Date();
		String webFormType = webForm.getFormType();
		String webFormId = webForm.getWebFormId();

		UserComment userComments = new UserComment();
		userComments.setUserId(userid);
		userComments.setCommentUserId(userid);
		userComments.setDate(now);
		if (request.getParameter("comments")!=null) {
			userComments.setComment(request.getParameter("comments"));
		}
		else if(UtilMethods.isSet(webForm.getFormType())) {
		    userComments.setSubject("User submitted: " + webFormType);
			userComments.setComment("Web Form: " + webFormType + " - ID: " + webFormId);
		}
		else{
		    userComments.setSubject("User submitted Form: Open Entry ");
		    StringBuffer buffy = new StringBuffer();
		    Enumeration x = request.getParameterNames();
		    while(x.hasMoreElements()){
		        String key = (String) x.nextElement();
		        buffy.append(key);
		        buffy.append(":\t");
		        buffy.append(request.getParameter(key));
		        buffy.append("\n");
		        if(buffy.length() > 65000){
		            break;
		        }
		    }
		    userComments.setComment(buffy.toString());

		}

		userComments.setTypeComment(UserComment.TYPE_INCOMING);
		userComments.setMethod(UserComment.METHOD_WEB);
		userComments.setCommunicationId(null);
		UserCommentsFactory.saveUserComment(userComments);
	}

}

## 内容2
### 文件路径：
src/com/dotmarketing/factories/EmailFactory.java
### 代码内容：
package com.dotmarketing.factories;

//import com.dotmarketing.threads.DeliverNewsletterThread;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dotcms.repackage.org.apache.commons.beanutils.BeanUtils;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.dotmarketing.beans.Host;
import com.dotmarketing.beans.Identifier;
import com.dotmarketing.beans.UserProxy;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.cms.factories.PublicAddressFactory;
import com.dotmarketing.cms.factories.PublicCompanyFactory;
import com.dotmarketing.cms.factories.PublicEncryptionFactory;
import com.dotmarketing.db.HibernateUtil;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotHibernateException;
import com.dotmarketing.exception.DotRuntimeException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.exception.WebAssetException;
import com.dotmarketing.portlets.contentlet.business.HostAPI;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.fileassets.business.FileAssetAPI;
import com.dotmarketing.portlets.files.business.FileAPI;
import com.dotmarketing.portlets.folders.model.Folder;
import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory;
import com.dotmarketing.portlets.mailinglists.model.MailingList;
import com.dotmarketing.portlets.webforms.model.WebForm;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.FormSpamFilter;
import com.dotmarketing.util.InodeUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.Mailer;
import com.dotmarketing.util.Parameter;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.VelocityUtil;
import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.language.LanguageException;
import com.liferay.portal.language.LanguageUtil;
import com.liferay.portal.model.Address;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import com.liferay.util.FileUtil;

/**
 * DOCUMENT ME!
 *
 * @author $author$
 * @version $Revision: 1.10 $
 */
public class EmailFactory {

	private static Long emailTime = new Long(System.currentTimeMillis());

	/**
	 * Rewrites urls to point back to the redirection servlet to track links
	 * and then calls the alterBodyHtmlAbsolutizePaths method
	 */
	public static StringBuffer alterBodyHTML(StringBuffer HTML, String serverName) {
		return new StringBuffer(alterBodyHTML(HTML.toString(), serverName));
	}

	public static String alterBodyHTML(String HTML, String serverName) {
		//This is the new Regular Expression for white spaces ([ .\r\n&&[^>]]*)
		// Replacing links "a href" like tags axcluding the mail to links

		HTML = HTML.replaceAll("(?i)(?s)<a[^>]+href=\"([^/(http://)(https://)(#)(mailto:\")])(.*)\"[^>]*>",
		"<a href=\"http://$1$2\">");

		HTML = HTML.replaceAll(
				//"(?i)(?s)<a[^>]+href=\"([^>]+)\"[^>]*>(.*?)</[^>]*a[^>]*>",
				"(?i)(?s)<a href=\"([^#])([^>]+)\"[^>]*>(.*?)</[^>]*a[^>]*>",
				"<a href=\"http://"
				+ serverName
				//+ "/redirect?r=<rId>&redir=$1\">$2</a>")
				+ "/redirect?r=<rId>&redir=$1$2\">$3</a>")
				.replaceAll("<a href=\"http://" + serverName + "/redirect\\?r=<rId>&redir=(mailto:[^\"]+)\">", "<a href=\"$1\">");
		HTML = alterBodyHtmlAbsolutizePaths(HTML, serverName);
		return HTML;
	}

	/**
	 * Change all the relative paths in the email body to absolute paths
	 */
	public static StringBuffer alterBodyHtmlAbsolutizePaths(StringBuffer HTML, String serverName)
	{
		return new StringBuffer(alterBodyHtmlAbsolutizePaths(HTML.toString(), serverName));
	}

	public static String alterBodyHtmlAbsolutizePaths(String HTML, String serverName)
	{
		String message = HTML;

		//Replacing links "TD background" like tags
		message = message
		.replaceAll(
				"<\\s*td([^>]*)background\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<td$1background=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "TR background" like tags
		message = message
		.replaceAll(
				"<\\s*tr([^>]*)background\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<tr$1background=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "IMG SRC" like tags
		message = message.replaceAll(
				"<\\s*img([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<img$1src=\"http://" + serverName
				+ "$2\"$3>");
		// Replacing links "A HREF" like tags
		message = message
		.replaceAll(
				"<\\s*link([^>]*)href\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<link$1href=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "SCRIPT" like tags
		message = message
		.replaceAll(
				"<\\s*script([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<script$1src=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "APPLET" with codebase like tags
		message = message
		.replaceAll(
				"<\\s*applet([^>]*)codebase\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<applet$1codebase=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "APPLET" without codebase like tags
		message = message
		.replaceAll(
				"<\\s*applet(([^>][^(codebase)])*)code\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?(([^>][^(codebase)])*)>",
				"<applet$1code=\"http://"
				+ serverName
				+ "$4\"$5>");
		// Replacing links "IFRAME" src replacement
		message = message
		.replaceAll(
				"<\\s*iframe([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<iframe$1src=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "IFRAME" longdesc replacement
		message = message
		.replaceAll(
				"<\\s*iframe([^>]*)longdesc\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<iframe$1longdesc=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "FRAME" src replacement
		message = message
		.replaceAll(
				"<\\s*frame([^>]*)src\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<frame$1src=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing links "FRAME" longdesc replacement
		message = message
		.replaceAll(
				"<\\s*frame([^>]*)longdesc\\s*=\\s*[\"\']?([^\'\">]*)[\"\']?([^>]*)>",
				"<frame$1longdesc=\"http://"
				+ serverName
				+ "$2\"$3>");
		// Replacing some style URLs
		message = message
		.replaceAll(
				"<([^>]*)style\\s*=\\s*[\"\']?([^\'\">]*)url\\s*\\(\\s*([^>]*)\\s*\\)([^\'\">]*)[\"\']?([^>]*)>",
				"<$1style=\"$2url(http://"
				+ serverName
				+ "$3)$4\"$5>");
		// Fixing absolute paths
		message = message.replaceAll("http://"
				+ serverName + "\\s*http://",
		"http://");

		return message;
	}

	/**
	 * Sends the forgot password email with the new random generated password
	 * @throws DotSecurityException
	 * @throws DotDataException
	 */
	public static boolean sendForgotPassword(User user, String newPassword, String hostId) throws DotDataException, DotSecurityException {

		HostAPI hostAPI = APILocator.getHostAPI();

		// build a decent default context
		Context context = VelocityUtil.getBasicContext();
		context.put("user", user);
		context.put("UtilMethods", new UtilMethods());
		context.put("language", Long.toString(APILocator.getLanguageAPI().getDefaultLanguage().getId()));
		context.put("password", newPassword);

		Host host = hostAPI.find(hostId, user, true);
		context.put("host", host);

		StringWriter writer = new StringWriter();

		String idInode = APILocator.getIdentifierAPI().find(host, Config
				.getStringProperty("PATH_FORGOT_PASSWORD_EMAIL")).getInode();

		String languageStr = "_" + APILocator.getLanguageAPI().getDefaultLanguage().getId();

		try {
			String message = "";
			try {
				Template t = UtilMethods.getVelocityTemplate("live/"+ idInode+ languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION"));
				t.merge(context, writer);
				Logger
				.debug(EmailFactory.class, "writer:"
						+ writer.getBuffer());
				message = writer.toString().trim();
			} catch (ResourceNotFoundException ex) {
				message = "<center><b>And error has ocurred loading de message's page<b></center>";
			}

			Mailer m = new Mailer();
			m.setToEmail(user.getEmailAddress());
			m.setSubject("Your " + host.getHostname() + " Password");
			m.setHTMLBody(message);
			m.setFromEmail(Config.getStringProperty("EMAIL_SYSTEM_ADDRESS"));
			return m.sendMessage();
		} catch (Exception e) {
			Logger.warn(EmailFactory.class, e.toString(), e);
			return false;
		}

	}

	public static boolean isSubscribed(MailingList list, User s){

		UserProxy up;
		try {
			up = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(s,APILocator.getUserAPI().getSystemUser(), false);
		} catch (Exception e) {
			Logger.error(EmailFactory.class, e.getMessage(), e);
			throw new DotRuntimeException(e.getMessage(), e);
		}
		return MailingListFactory.isSubscribed(list, up);

	}

	/**
	 *
	 * Send emails based on the parameters given to the method, basically is used
	 * to send emails based on parameters received html forms but it can be used
	 * to send emails using parameters that come form any source
	 *
	 * Some parameters are required and need to be passed in order the method to work
	 * correctly, here it is the description of the predefined parameters and when they are
	 * required or not:
	 *
	 * formType/formName: 	The name of the form used to generate the reports and to save the files submitted
	 * 						as parameters, so if no formType or formName is supplied then no report
	 * 						or files will be saved.
	 * to:					Email address where the email will be sent
	 * from:				Email address will be used as the from address
	 * subject:				Subject of the email
	 * cc:					Carbon copy of the email
	 * bcc:					Hidden carbon copy of the email
	 * html:				Set it to false|0|f if you don't want to send an html kind of email
	 * dispatch:			Not used reserved for struts processing
	 * order:				Order how you want to present the parameters, the valid syntax of this
	 * 						parameter is like: param1,param2,...
	 * prettyOrder:			This property goes together with the order property to specify
	 * 						prettiest names to the parameters, these prettiest names are used
	 * 						when building the simple html table e-mail
	 * ignore:				Parameters you want to exclude from the email sent, the valid syntax of this
	 * 						parameter is like ;param1;param2;..., this is only used when building the
	 * 						simple html table email body and not when building the email from a given template
	 * emailTemplate: 		The path to the email template to be used to generate the email
	 * 						it can be a path in the dotCMS tree or a real path in the server file system
	 * 						under /liferay folder, dotCMS paths take precedence over filesystem paths
	 * attachFiles: 		A comma separated list of the file kind of fields you want the method include as
	 * 					    attachments to the email to send
	 * If the following parameters are included an auto reply message will be send
	 * to the from email
	 * autoReplyFrom:     Address to be used as the from
	 * autoReplySubject:  Subject of the message
	 * autoReplyText: 	  Message to send
	 * autoReplyTemplate: A path to an html template that can be used to generate this message
	 * 					  it can be a path in the dotCMS tree or a real path in the server file system
	 * 					  under /liferay folder
	 *
	 * @param parameters A map of the submitted fields, any kind of parameter can
	 * be used and will be passed to the email template to render the email body text used when
	 * sending the email but only string or file kind parameters will be used to generate the database
	 * reports and generate plain table html table like body text when no html template is passed
	 * in the parameters
	 *
	 * @param spamValidation List of fields that wants to be checked for possible spam
	 * @param otherIgnoredParams A list of other fields (more than the default ones) that you want to
	 * 							 be excluded from the list of fields to be sent in the email
	 * @param host Current dotCMS host used to submit the form
	 * @param user User how submits the form (can be null then the user parameters won't be excluded
	 * 				on the template substitution)
	 * @return The saved webform if a formType/formName parameter is specified if not returns null.
	 * @throws 	DotRuntimeException when spam is detected or any other mayor error occurs
	 * 	 		CreditCardDeniedException when the credit card gets denied
	 */
	public static WebForm sendParameterizedEmail(Map<String,Object> parameters, Set<String> spamValidation,
			Host host, User user) throws  DotRuntimeException
			{

		// check for possible spam
		if(spamValidation != null)
			if (FormSpamFilter.isSpamRequest(parameters, spamValidation)) {
				throw new DotRuntimeException("Spam detected");
			}

		//Variables initialization

		//Default parameters to be ignored when sending the email
		String ignoreString = ":formType:formName:to:from:subject:cc:bcc:html:dispatch:order:" +
		"prettyOrder:autoReplyTo:autoReplyFrom:autoReplyText:autoReplySubject:" +
		"ignore:emailTemplate:autoReplyTemplate:autoReplyHtml:chargeCreditCard:attachFiles:";
		if(UtilMethods.isSet(getMapValue("ignore", parameters))) {
			ignoreString += getMapValue("ignore", parameters).toString().replace(",", ":") + ":";
		}

		// Sort the forms' fields by the given order parameter
		String order = (String)getMapValue("order", parameters);
		Map<String, Object> orderedMap = new LinkedHashMap<String, Object>();

		// Parameter prettyOrder is used to map
		// the pretty names of the variables used in the order field
		// E.G: order = firstName, lastName
		//		prettyOrder = First Name, Last Name
		String prettyOrder = (String)getMapValue("prettyOrder", parameters);
		Map<String, String> prettyVariableNamesMap = new LinkedHashMap<String, String>();

		// Parameter attachFiles is used to specify the file kind of fields you want to attach
		// to the mail is sent by this method
		// E.G: attachFiles = file1, file2, ...
		String attachFiles = (String)getMapValue("attachFiles", parameters);

		//Building the parameters maps from the order and pretty order parameters
		if (order != null) {
			String[] orderArr = order.split("[;,]");
			String[] prettyOrderArr = prettyOrder!=null?prettyOrder.split("[;,]"):new String[0];

			for (int i = 0; i < orderArr.length; i++) {
				String orderParam = orderArr[i].trim();
				Object value = (getMapValue(orderParam, parameters) == null) ?
						null : getMapValue(orderParam, parameters);

				if(value != null) {
					//if pretty name is passed using it as a key value in the ordered map
					if (prettyOrderArr.length > i)
						prettyVariableNamesMap.put(orderArr[i].trim(), prettyOrderArr[i].trim());
					else
						prettyVariableNamesMap.put(orderArr[i].trim(), orderArr[i].trim());
					orderedMap.put(orderArr[i].trim(), value);
				}
			}

		}

		for (Entry<String, Object> param : parameters.entrySet()) {
			if(!orderedMap.containsKey(param.getKey())) {
				orderedMap.put(param.getKey(), param.getValue());
				prettyVariableNamesMap.put(param.getKey(), param.getKey());
			}
		}

		StringBuffer filesLinks = new StringBuffer();

		// Saving the form in the database and the submitted file to the dotCMS
		String formType = getMapValue("formType", parameters) != null?
				(String)getMapValue("formType", parameters):(String)getMapValue("formName", parameters);

				WebForm formBean = saveFormBean(parameters, host, formType, ignoreString, filesLinks);

				// Setting up the email
				// Email variables - decrypting crypted email addresses

				String from = UtilMethods.replace((String)getMapValue("from", parameters), "spamx", "");
				String to = UtilMethods.replace((String)getMapValue("to", parameters), "spamx", "");
				String cc = UtilMethods.replace((String)getMapValue("cc", parameters), "spamx", "");
				String bcc = UtilMethods.replace((String)getMapValue("bcc", parameters), "spamx", "");
				String fromName = UtilMethods.replace((String)getMapValue("fromName", parameters), "spamx", "");
				try { from = PublicEncryptionFactory.decryptString(from); } catch (Exception e) { }
				try { to = PublicEncryptionFactory.decryptString(to); } catch (Exception e) { }
				try { cc = PublicEncryptionFactory.decryptString(cc); } catch (Exception e) { }
				try { bcc = PublicEncryptionFactory.decryptString(bcc); } catch (Exception e) { }
				try { fromName = PublicEncryptionFactory.decryptString(fromName); } catch (Exception e) { }

				String subject = (String)getMapValue("subject", parameters);
				subject = (subject == null) ? "Mail from " + host.getHostname() + "" : subject;

				String emailFolder = (String)getMapValue("emailFolder", parameters);

				boolean html = getMapValue("html", parameters) != null?Parameter.getBooleanFromString((String)getMapValue("html", parameters)):true;

				String templatePath = (String) getMapValue("emailTemplate", parameters);

				// Building email message no template
				Map<String, String> emailBodies = null;

				try {
					emailBodies = buildEmail(templatePath, host, orderedMap, prettyVariableNamesMap, filesLinks.toString(), ignoreString, user);
				} catch (Exception e) {
					Logger.error(EmailFactory.class, "sendForm: Couldn't build the email body text.", e);
					throw new DotRuntimeException("sendForm: Couldn't build the email body text.", e);
				}

				// Saving email backup in a file
				try {
					String filePath = FileUtil.getRealPath(Config.getStringProperty("EMAIL_BACKUPS"));
					new File(filePath).mkdir();

					File file = null;
					synchronized (emailTime) {
						emailTime = new Long(emailTime.longValue() + 1);
						if (UtilMethods.isSet(emailFolder)) {
							new File(filePath + File.separator + emailFolder).mkdir();
							filePath = filePath + File.separator + emailFolder;
						}
						file = new File(filePath + File.separator + emailTime.toString()
								+ ".html");
					}
					if (file != null) {
						java.io.OutputStream os = new java.io.FileOutputStream(file);
						BufferedOutputStream bos = new BufferedOutputStream(os);
						if(emailBodies.get("emailHTMLBody") != null)
							bos.write(emailBodies.get("emailHTMLBody").getBytes());
						else if(emailBodies.get("emailHTMLTableBody") != null)
							bos.write(emailBodies.get("emailHTMLTableBody").getBytes());
						else
							bos.write(emailBodies.get("emailPlainTextBody").getBytes());
						bos.flush();
						bos.close();
						os.close();
					}
				} catch (Exception e) {
					Logger.warn(EmailFactory.class, "sendForm: Couldn't save the email backup in " + Config.getStringProperty("EMAIL_BACKUPS"));
				}

				// send the mail out;
				Mailer m = new Mailer();
				m.setToEmail(to);
				m.setFromEmail(from);
				m.setFromName(fromName);
				m.setCc(cc);
				m.setBcc(bcc);
				m.setSubject(subject);

				if (html) {
					if(UtilMethods.isSet(emailBodies.get("emailHTMLBody")))
						m.setHTMLBody(emailBodies.get("emailHTMLBody"));
					else
						m.setHTMLBody(emailBodies.get("emailHTMLTableBody"));
				}
				m.setTextBody(emailBodies.get("emailPlainTextBody"));

				//Attaching files requested to be attached to the email
				if(attachFiles != null) {
					attachFiles = "," + attachFiles.replaceAll("\\s", "") + ",";
					for(Entry<String, Object> entry : parameters.entrySet()) {
						if(entry.getValue() instanceof File && attachFiles.indexOf("," + entry.getKey() + ",") > -1) {
							File f = (File)entry.getValue();
							m.addAttachment(f, entry.getKey() + "." + UtilMethods.getFileExtension(f.getName()));
						}
					}
				}

				if (m.sendMessage()) {

					// there is an auto reply, send it on
					if ((UtilMethods.isSet((String)getMapValue("autoReplyTemplate", parameters)) ||
							UtilMethods.isSet((String)getMapValue("autoReplyText", parameters)))
							&& UtilMethods.isSet((String)getMapValue("autoReplySubject", parameters))
							&& UtilMethods.isSet((String)getMapValue("autoReplyFrom", parameters))) {

						templatePath = (String) getMapValue("autoReplyTemplate", parameters);

						if(UtilMethods.isSet(templatePath)) {
							try {
								emailBodies = buildEmail(templatePath, host, orderedMap, prettyVariableNamesMap, filesLinks.toString(), ignoreString, user);
							} catch (Exception e) {
								Logger.error(EmailFactory.class, "sendForm: Couldn't build the auto reply email body text. Sending plain text.", e);
							}
						}

						m = new Mailer();
						String autoReplyTo = (String)(getMapValue("autoReplyTo", parameters) == null?getMapValue("from", parameters):getMapValue("autoReplyTo", parameters));
						m.setToEmail(UtilMethods.replace(autoReplyTo, "spamx", ""));
						m.setFromEmail(UtilMethods.replace((String)getMapValue("autoReplyFrom", parameters), "spamx", ""));
						m.setSubject((String)getMapValue("autoReplySubject", parameters));

						String autoReplyText = (String)getMapValue("autoReplyText", parameters);
						boolean autoReplyHtml = getMapValue("autoReplyHtml", parameters) != null?Parameter.getBooleanFromString((String)getMapValue("autoReplyHtml", parameters)):html;
						if (autoReplyText != null)
						{
							if(autoReplyHtml)
							{
								m.setHTMLBody((String)getMapValue("autoReplyText", parameters));
							} else {
								m.setTextBody((String)getMapValue("autoReplyText", parameters));
							}
						}
						else
						{
							if (autoReplyHtml)
							{
								if(UtilMethods.isSet(emailBodies.get("emailHTMLBody")))
									m.setHTMLBody(emailBodies.get("emailHTMLBody"));
								else
									m.setHTMLBody(emailBodies.get("emailHTMLTableBody"));
							}
							m.setTextBody(emailBodies.get("emailPlainTextBody"));
						}
						m.sendMessage();
					}
				} else {
					if(formBean != null){
						try {
							HibernateUtil.delete(formBean);
						} catch (DotHibernateException e) {
							Logger.error(EmailFactory.class, e.getMessage(), e);
						}
					}
					throw new DotRuntimeException("Unable to send the email");
				}

				return formBean;

			}

	public static Map<String, String> buildEmail(String templatePath, Host host, Map<String,Object> parameters,
			Map<String, String> prettyParametersNamesMap, String filesLinks, String ignoreString, User user)
			throws WebAssetException, ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, DotDataException, DotSecurityException, PortalException, SystemException
			{
		StringBuffer emailHTMLBody = new StringBuffer();
		StringBuffer emailHTMLTableBody = new StringBuffer();
		StringBuffer emailPlainTextBody = new StringBuffer();

		//Case when a html page template is passed as parameter
		if(UtilMethods.isSet(templatePath))
		{
			Identifier id = APILocator.getIdentifierAPI().find(host,templatePath);
			String idInode = id.getInode();

			String languageId = Long.toString((APILocator.getLanguageAPI().getDefaultLanguage().getId()));

			try {
				if(UtilMethods.isSet(parameters.get("languageId"))) {
					languageId = (String) parameters.get("languageId");
				}
			} catch(ClassCastException e) {
				Logger.info(EmailFactory.class, "Error parsing languageId");
			}

			String languageStr = "_" + languageId;

			Template t = null;

			try {
				if(InodeUtils.isSet(idInode)) {
					t = UtilMethods.getVelocityTemplate("live/"+ idInode + languageStr + "."+ Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION"));
				} else {
					t = UtilMethods.getVelocityTemplate(templatePath);
				}
			} catch (Exception e) {
			}

			if (t != null) {

				HttpServletRequest request = (HttpServletRequest) parameters.get("request");
				HttpServletResponse response = (HttpServletResponse) parameters.get("response");
				Context context = null;
				if(InodeUtils.isSet(idInode) && request != null && response != null)
				{
					context = VelocityUtil.getWebContext(request,response);
				}
				else
				{
					context = VelocityUtil.getBasicContext();
				}

				//Copying the parameters to the context
				for(Entry<String, Object> entry : parameters.entrySet()) {
					Object value = getMapValue(entry.getKey(), parameters);
					if(entry.getKey().equals("ccNumber") && value instanceof String) {
						value = (String)UtilMethods.obfuscateCreditCard((String)value);
					}
					if(entry.getKey().contains("cvv") && value instanceof String) {
						String valueString = (String)value;
						if(valueString.length() > 3){
							value = (String)UtilMethods.obfuscateString(valueString,2);
						}
						else {
							value = (String)UtilMethods.obfuscateString(valueString,1);
						}
					}
					context.put(entry.getKey(), value);
				}
				context.put("utilMethods", new UtilMethods());
				context.put("UtilMethods", new UtilMethods());
				context.put("host", host);
				if(user != null)
					context.put("user", user);

				StringWriter writer = new StringWriter();

				//Rendering the html template with the parameters
				t.merge(context, writer);
				String textVar = writer.toString();
				emailHTMLBody = new StringBuffer(alterBodyHtmlAbsolutizePaths(replaceTextVar(textVar, parameters, user), host.getHostname()));
			}
		}

		String subject = (String)getMapValue("subject", parameters);
		subject = (subject == null) ? "Mail from " + host.getHostname(): subject;

		emailHTMLTableBody.append("<html><style>td{font-family:arial;font-size:10pt;}</style><BODY>");
		emailHTMLTableBody.append("<TABLE bgcolor=eeeeee width=95%>");
		emailHTMLTableBody.append("<TR><TD colspan=2><strong>Information from "
				+ host.getHostname() + ": " + subject
				+ "</strong></TD></TR>");
		emailPlainTextBody.append("Information from " + host.getHostname()
				+ ": \t" + subject + "\n\n");

		// Loop over the request Map or the ordered Map
		Iterator<Entry<String,Object>> it = parameters.entrySet().iterator();

		while (it.hasNext()) {

			Entry<String, Object> e = (Entry<String, Object>) it.next();
			String key = e.getKey();
			Object mapvalue = getMapValue(key, parameters);
			if (mapvalue instanceof String) {
				String value = (String)mapvalue;
				if(key.equals("ccNumber") && value instanceof String) {
					value = (String)UtilMethods.obfuscateCreditCard((String)value);
				}
				if(key.contains("cvv") && value instanceof String) {
					String valueString = (String)value;
					if(valueString.length() > 3){
						value = (String)UtilMethods.obfuscateString(valueString,2);
					}
					else {
						value = (String)UtilMethods.obfuscateString(valueString,1);
					}
				}
				if (ignoreString.indexOf(":" + key + ":") < 0 && UtilMethods.isSet(value)) {
					String prettyKey = prettyParametersNamesMap.get(key);
					String capKey = prettyKey != null?prettyKey:UtilMethods.capitalize(key);
					emailHTMLTableBody.append("<TR><TD bgcolor=white valign=top nowrap> " + capKey + " </TD>");
					emailHTMLTableBody.append("<TD bgcolor=white valign=top width=100%>" + value + "</TD></TR>");
					emailPlainTextBody.append(capKey + ":\t" + value + "\n");
				}
			}
		}

		if (UtilMethods.isSet(filesLinks)) {
			emailHTMLTableBody.append("<TR><TD bgcolor=white valign=top nowrap> Files </TD>");
			emailHTMLTableBody.append("<TD bgcolor=white valign=top width=100%>" + filesLinks + "</TD></TR>");
			emailPlainTextBody.append("Files:\t" + filesLinks + "\n");
		}

		emailHTMLTableBody.append("</TABLE></BODY></HTML>");

		Map<String, String> returnMap = new HashMap<String, String>();
		if(UtilMethods.isSet(emailHTMLBody.toString()))
			returnMap.put("emailHTMLBody", emailHTMLBody.toString());
		if(UtilMethods.isSet(emailHTMLTableBody.toString()))
			returnMap.put("emailHTMLTableBody", emailHTMLTableBody.toString());
		returnMap.put("emailPlainTextBody", emailPlainTextBody.toString());

		return returnMap;
			}

	private static WebForm saveFormBean (Map<String, Object> parameters, Host host, String formType, String ignoreString, StringBuffer filesLinks) {

		//Fields predefined for the form reports
		String predefinedFields = ":prefix:title:firstName:middleInitial:middleName:lastName:fullName:organization:address:address1:address2:city:state:zip:country:phone:email:";

		//Return variable
		WebForm formBean = new WebForm();
		formBean.setFormType(formType);

		// Copy the common fields set in the form
		try {
			for (Entry<String, Object> param : parameters.entrySet()) {
				BeanUtils.setProperty(formBean, param.getKey(), getMapValue(param.getKey(), parameters));
			}
		} catch (Exception e1) {
			Logger.error(EmailFactory.class, "sendForm: Error ocurred trying to copy the form bean parameters", e1);
		}

		try {
			HibernateUtil.save(formBean);
		} catch (DotHibernateException e) {
			Logger.error(EmailFactory.class, e.getMessage(), e);
		}
		String formId = formBean.getWebFormId();

		// Loop over the request Map or the ordered Map to set the custom
		// fields and also saving the submitted files
		StringBuffer customFields = new StringBuffer();

		Set<Entry<String, Object>> paramSet = parameters.entrySet();

		for (Entry<String, Object> param : paramSet) {

			String key = (String) param.getKey();

			String value = null;

			Object paramValue = getMapValue(key, parameters);
			if (paramValue instanceof File) {

				File f = (File) param.getValue();
				String submittedFileName = f.getName();
				String fileName = key + "." + UtilMethods.getFileExtension(submittedFileName);
				if(getMapValue(fileName.substring(4, key.length()) + "FName", parameters) != null) {
					fileName = getMapValue(fileName.substring(4, key.length()) + "FName", parameters) +
						"." + UtilMethods.getFileExtension(submittedFileName);
				}

				//Saving the file
				try {
					if(f.exists()) {
						String filesFolder = getMapValue("formFolder", parameters) instanceof String?(String)getMapValue("formFolder", parameters):null;

						String fileLink = saveFormFile(formId, formType, fileName, f, host, filesFolder);
						filesLinks.append(filesLinks.toString().equals("")? "http://" + host.getHostname() + fileLink : ",http://" + host.getHostname() + fileLink);
					}
				} catch (Exception e) {
					Logger.error(EmailFactory.class, "sendForm: couldn't saved the submitted file into the cms = " + fileName, e);
					try {
						HibernateUtil.delete(formBean);
					} catch (DotHibernateException e1) {
						Logger.error(EmailFactory.class, e1.getMessage(), e1);
					}
					throw new DotRuntimeException("sendForm: couldn't saved the submitted file into the cms = " + fileName, e);
				}

			} else if (paramValue instanceof String)
				value = (String)paramValue;

			List<String> cFields = new ArrayList<String>();
			if (predefinedFields.indexOf(":" + key + ":") < 0
					&& ignoreString.indexOf(":" + key + ":") < 0
					&& UtilMethods.isSet(value)) {
				value = value.replaceAll("\\|", " ").replaceAll("=", " ");
				if(key.equals("ccNumber"))
					value = UtilMethods.obfuscateCreditCard(value);

				String capKey = UtilMethods.capitalize(key);
				int aux = 2;
				String capKeyAux = capKey;
				while (cFields.contains(capKeyAux)) {
					capKeyAux = capKey + aux;
					++aux;
				}
				cFields.add(capKeyAux);
				String cField = capKeyAux + "=" + value;
				customFields.append(cField + "|");
			}
		}

		customFields.append("Files=" + filesLinks);

		//Setting the custom fields and saving them
		formBean.setCustomFields(customFields.toString());
		formBean.setSubmitDate(new Date());

		if(UtilMethods.isSet(formType)){
			try {
				HibernateUtil.saveOrUpdate(formBean);
			} catch (DotHibernateException e) {
				throw new DotRuntimeException("Webform Save Failed");
			}
		}
		else{
			Logger.debug(EmailFactory.class, "The web form doesn't have the required formType field, the form data will not be saved in the database.");
		}

		return formBean;
	}

	private static String getFormFileFolderPath (String formType, String formInode) {
		String path = Config.getStringProperty("SAVED_UPLOAD_FILES_PATH")
		+ "/" + formType.replace(" ", "_") + "/"
		+ String.valueOf(formInode).substring(0, 1) + "/" + formInode;
		return path;
	}

	private static String saveFormFile (String formInode, String formType,
			String fileName, File fileToSave, Host currentHost, String filesFolder) throws Exception {
		FileAPI fileAPI=APILocator.getFileAPI();
		String path;
		if(filesFolder != null)
			path = filesFolder;
		else
			path = getFormFileFolderPath(formType, formInode);
		Folder folder = APILocator.getFolderAPI().createFolders(path, currentHost, APILocator.getUserAPI().getSystemUser(), false);
		String baseFilename = fileName;
		int c = 1;
		while(fileAPI.fileNameExists(folder, fileName)) {
			fileName = UtilMethods.getFileName(baseFilename) + "-" + c + "." + UtilMethods.getFileExtension(baseFilename);
			c++;
		}
		Host host = APILocator.getHostAPI().find(folder.getHostId(), APILocator.getUserAPI().getSystemUser(), false);
		while(APILocator.getFileAssetAPI().fileNameExists(host,folder, fileName, "")) {
			fileName = UtilMethods.getFileName(baseFilename) + "-" + c + "." + UtilMethods.getFileExtension(baseFilename);
			c++;
		}

		Contentlet cont = new Contentlet();
		cont.setStructureInode(folder.getDefaultFileType());
		cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(fileName));
		cont.setFolder(folder.getInode());
		cont.setHost(host.getIdentifier());
		cont.setBinary(FileAssetAPI.BINARY_FIELD, fileToSave);
		APILocator.getContentletAPI().checkin(cont, APILocator.getUserAPI().getSystemUser(),false);

		return path + "/" + fileName;
	}

	private static String replaceTextVar(String template, Map<String, Object> parameters, User user)
	{
		String finalMessageStr = template;

		Set<String> keys = parameters.keySet();
		for(String key : keys)
		{
			if(getMapValue(key, parameters) instanceof String) {
				String value = (String)getMapValue(key, parameters);
				value = (value != null ? value : "");
				finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/"+ key +"(>|(>))", "");
				finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))" + key + "(\")?( )*/*( )*(>|(>))",value);
			}
		}

		if(UtilMethods.isSet(user))
		{
			Address address = new Address();
			try {
				List<Address> adds = PublicAddressFactory.getAddressesByUserId(user.getUserId());
				if (adds != null && adds.size() > 0) {
					address = (Address) adds.get(0);
				}
			}
			catch(Exception e) {
					Logger.error(EmailFactory.class, "Send To Friend Failed" + e);
			}

			//Variables replacement from user object
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varName(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varName(\")?( )*/*( )*(>|(>))", (user.getFirstName()!=null) ? user.getFirstName() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varEmail(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varEmail(\")?( )*/*( )*(>|(>))", (user.getEmailAddress()!=null) ? user.getEmailAddress() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varMiddleName(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varMiddleName(\")?( )*/*( )*(>|(>))", (user.getMiddleName()!=null) ? user.getMiddleName() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varLastName(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varLastName(\")?( )*/*( )*(>|(>))", (user.getLastName()!=null) ? user.getLastName() : "");

			UserProxy userproxy;
			try {
				userproxy = com.dotmarketing.business.APILocator.getUserProxyAPI().getUserProxy(user,APILocator.getUserAPI().getSystemUser(), false);
			} catch (Exception e) {
				Logger.error(EmailFactory.class, e.getMessage(), e);
				throw new DotRuntimeException(e.getMessage(), e);
			}
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varLastMessage(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varLastMessage(\")?( )*/*( )*(>|(>))", (userproxy.getLastMessage()!=null) ? userproxy.getLastMessage() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varAddress1(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varAddress1(\")?( )*/*( )*(>|(>))", (address.getStreet1()!=null) ? address.getStreet1() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varAddress2(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varAddress2(\")?( )*/*( )*(>|(>))", (address.getStreet2()!=null) ? address.getStreet2() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varPhone(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varPhone(\")?( )*/*( )*(>|(>))", (address.getPhone()!=null) ? address.getPhone() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varState(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varState(\")?( )*/*( )*(>|(>))", (address.getState()!=null) ? address.getState() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varCity(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varCity(\")?( )*/*( )*(>|(>))", (address.getCity()!=null) ? address.getCity() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varCountry(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varCountry(\")?( )*/*( )*(>|(>))", (address.getCountry()!=null) ? address.getCountry() : "");

			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/varZip(>|(>))", "");
			finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))varZip(\")?( )*/*( )*(>|(>))", (address.getZip()!=null) ? address.getZip() : "");

			//gets default company to get locale
			Company comp = PublicCompanyFactory.getDefaultCompany();

			try {

				int varCounter = 1;

				for (;varCounter < 26;varCounter++) {
					String var = LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + varCounter);
					if (var!=null) var = var.replaceAll(" ","_");

					String value = "";
					try {
						value = BeanUtils.getSimpleProperty(userproxy, "var" + varCounter);
					} catch (Exception e) {
						Logger.error(EmailFactory.class, "An error as ocurred trying to access the variable var" + varCounter + " from the user proxy.", e);
					}

					finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/"+var+"(>|(>))", "");
					finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))" + var + "(\")?( )*/*( )*(>|(>))", (value != null) ? value : "");

					finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))/var" + varCounter + "(>|(>))", "");
					finalMessageStr = finalMessageStr.replaceAll("(?i)(<|(<))var" + varCounter + "(\")?( )*/*( )*(>|(>))", (value != null) ? value : "");
				}

			} catch(LanguageException le) {
				Logger.error(EmailFactory.class, le.getMessage());
			}
		}
		return finalMessageStr;
	}

	public static Object getMapValue(String key, Map<String, Object> map) {

		try {
			try
			{
				if(((Object[]) map.get(key)).length > 1)
				{
					String returnValue = "";
					for(Object object : ((Object[]) map.get(key)))
					{
						returnValue += object.toString() + ", ";
					}
					returnValue = returnValue.substring(0,returnValue.lastIndexOf(","));
					return returnValue;
				}
			}
			catch(Exception ex)
			{}
			return ((Object[]) map.get(key))[0];

		} catch (Exception e) {
			try {
				return (Object) map.get(key);
			} catch (Exception ex) {
				return null;
			}

		}

	}

}

## 内容3
### 文件路径：
src/com/dotmarketing/portlets/workflows/model/WorkflowSearcher.java
### 代码内容：
package com.dotmarketing.portlets.workflows.model;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import com.dotmarketing.business.APILocator;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.util.UtilMethods;
import com.liferay.portal.model.User;

public class WorkflowSearcher {

	String schemeId;
	String assignedTo;
	String createdBy;
	String stepId;
	boolean open;
	boolean closed;
	boolean show4all;
	String keywords;
	String orderBy;
	int count = 20;
	int page = 0;
	User user;
	int totalCount;
	int daysOld=-1;

	public int getDaysOld() {
	    return daysOld;
	}

	public boolean getShow4All() {
	    return show4all;
	}

	public void setShow4All(boolean value) {
	    show4all=value;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public String getAssignedTo() {
		return assignedTo;
	}

	public void setAssignedTo(String assignedTo) {
		this.assignedTo = assignedTo;
	}

	public String getCreatedBy() {
		return createdBy;
	}

	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}

	private String getStringValue(String x, Map<String, Object> map) {
		Object obj = map.get(x);
		if (obj == null)
			return null;
		String ret = null;
		if (obj instanceof String[]) {
			ret = ((String[]) obj)[0];
		} else {
			ret = obj.toString();
		}
		return (UtilMethods.isSet(ret)) ? ret : null;

	}

	private boolean getBooleanValue(String x, Map<String, Object> map) {
		Object obj = map.get(x);
		String y = null;
		try {

			if (obj instanceof String[]) {
				y = ((String[]) obj)[0];
			} else {
				y = obj.toString();
			}
			return new Boolean(y);
		} catch (Exception e) {

		}
		return false;
	}

	public WorkflowSearcher() {
	}

	public WorkflowSearcher(Map<String, Object> map, User user) {

		schemeId = getStringValue("schemeId", map);
		assignedTo = getStringValue("assignedTo", map);
		createdBy = getStringValue("createdBy", map);
		stepId = getStringValue("stepId", map);
		keywords = getStringValue("keywords", map);
		orderBy = getStringValue("orderBy", map);
		show4all = getBooleanValue("show4all", map);
		open = getBooleanValue("open", map);
		closed = getBooleanValue("closed", map);
		String daysOldstr = getStringValue("daysold", map);

		if(UtilMethods.isSet(daysOldstr) && daysOldstr.matches("^\\d+$"))
		    daysOld = Integer.parseInt(daysOldstr);

		this.user = user;

		try {
			page = Integer.parseInt((String) getStringValue("page", map));
		} catch (Exception e) {
			page = 0;
		}
		if (page < 0)
			page = 0;
		try {
			count = Integer.parseInt((String) getStringValue("count", map));
		} catch (Exception e) {
			count = 20;
		}
		if (count < 0)
			count = 20;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public List<WorkflowTask> findTasks() throws DotDataException {

		totalCount = APILocator.getWorkflowAPI().countTasks(this);
		return APILocator.getWorkflowAPI().searchTasks(this);

	}

	public List<WorkflowTask> findAllTasks(WorkflowSearcher searcher) throws DotDataException {

		List<WorkflowTask> list = APILocator.getWorkflowAPI().searchAllTasks(searcher);
		totalCount = (APILocator.getWorkflowAPI().searchAllTasks(null)).size();
		return list;

	}

	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public String getSchemeId() {
		return schemeId;
	}

	public void setSchemeId(String schemeId) {
		this.schemeId = schemeId;
	}

	public String getStepId() {
		return stepId;
	}

	public void setStepId(String actionId) {
		this.stepId = actionId;
	}

	public boolean isOpen() {
		return open;
	}

	public void setOpen(boolean open) {
		this.open = open;
	}

	public boolean isClosed() {
		return closed;
	}

	public void setClosed(boolean closed) {
		this.closed = closed;
	}

	public String getKeywords() {
		return keywords;
	}

	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}

	public String getQueryString() {
		return   "&schemeId=" + UtilMethods.webifyString(schemeId)
		        + "&assignedTo=" + UtilMethods.webifyString(assignedTo)
		        + "&createdBy=" + UtilMethods.webifyString(createdBy)
				+ "&stepId=" + UtilMethods.webifyString(stepId)
				+ "&open=" + open
				+ "&closed=" + closed
				+ "&keywords=" + URLEncoder.encode(UtilMethods.webifyString(keywords))
				+ "&orderBy=" + orderBy
				+ "&count=" + count
				+ ((show4all) ? "&show4all=true" : "")
				+ "&page=" + page;

	}

	public String getQueryStringBis() {
		return "&count=" + count + "&page=" + page;

	}

	public boolean hasBack() {
		return page > 0;

	}

	public boolean hasNext() {
		return (count * (page + 1)) < totalCount;

	}

	public int getTotalPages() {

		return ((totalCount - 1) / count) + 1;
	}

	public int getStartPage() {
		int startPages = 0;
		int pages = getTotalPages();
		if (pages > 10 && page > pages - 10) {
			startPages = pages - 10;
		}
		return startPages;
	}

}


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
modules/apps/foundation/frontend-js/frontend-js-spa-web/src/main/resources/META-INF/resources/init.jsp
### 代码内容：
<%--

--%>

<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %><%@
taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>

<%@ page import="com.liferay.frontend.js.spa.web.internal.constants.SPAWebKeys" %><%@
page import="com.liferay.frontend.js.spa.web.internal.servlet.taglib.util.SPAUtil" %><%@
page import="com.liferay.portal.kernel.language.LanguageUtil" %>

<liferay-theme:defineObjects />

<%
SPAUtil spaUtil = (SPAUtil)request.getAttribute(SPAWebKeys.SPA_UTIL);
%>

<aui:script position="inline" require="frontend-js-spa-web/liferay/init.es">
	Liferay.SPA = Liferay.SPA || {};

	Liferay.SPA.cacheExpirationTime = <%= spaUtil.getCacheExpirationTime(themeDisplay.getCompanyId()) %>;
	Liferay.SPA.clearScreensCache = <%= spaUtil.isClearScreensCache(request, session) %>;
	Liferay.SPA.excludedPaths = <%= spaUtil.getExcludedPaths() %>;
	Liferay.SPA.loginRedirect = '<%= spaUtil.getLoginRedirect(request) %>';
	Liferay.SPA.requestTimeout = <%= spaUtil.getRequestTimeout() %>;
	Liferay.SPA.userNotification = {
		message: '<%= LanguageUtil.get(spaUtil.getLanguageResourceBundle(themeDisplay.getLocale()), "it-looks-like-this-is-taking-longer-than-expected") %>',
		timeout: <%= spaUtil.getUserNotificationTimeout() %>,
		title: '<%= LanguageUtil.get(spaUtil.getLanguageResourceBundle(themeDisplay.getLocale()), "oops") %>'
	};

	frontendJsSpaWebLiferayInitEs.default.init(
		function(app) {
			app.setPortletsBlacklist(<%= spaUtil.getPortletsBlacklist(themeDisplay) %>);
			app.setValidStatusCodes(<%= spaUtil.getValidStatusCodes() %>);
		}
	);
</aui:script>


Instruction:
作为 Java 安全专家，检测此代码中的安全漏洞：
## 内容1
### 文件路径：
templates/com/pugh/sockso/templates/web/browse/TPlaylist.jamon
### 代码内容：
<%import>
    com.pugh.sockso.Constants;
    com.pugh.sockso.Utils;
    com.pugh.sockso.Properties;
    com.pugh.sockso.music.Track;
    com.pugh.sockso.music.Playlist;
    com.pugh.sockso.resources.Locale;
    com.pugh.sockso.web.User;
    java.util.Vector;
</%import>

<%implements>
    com.pugh.sockso.web.PageTemplate;
</%implements>

<%args>
    Properties properties = null;
    Vector<Track> tracks = null;
    Playlist playlist = null;
    User user = null;
    Locale locale = null;
    Vector<User> recentUsers = null;
</%args>

<& ../IHeader; properties=properties; title="Playlist: " + playlist.getName(); user=user; locale=locale; &>

        <% Utils.u2e(playlist.getName()) #n %>

            <& IMusicLinks; type="pl"; id=playlist.getId(); name=playlist.getName(); shareLink=true; playRandomLink=true; locale=locale; properties=properties; &>

<%if tracks.size() > 0 %>
    <%for Track track : tracks %>

            <& IMusicLinks; type="tr"; id=track.getId(); name=track.getName(); locale=locale; properties=properties; &>
            <a href="<% properties.getUrl("/browse/artist/"+track.getArtist().getId()) #n %>"><% Utils.u2e(track.getArtist().getName()) #n %> -
            <a href="<% properties.getUrl("/browse/album/"+track.getAlbum().getId()) #n %>"><% Utils.u2e(track.getAlbum().getName()) #n %> -
            <% Utils.u2e(track.getName()) #n %>

    </%for>
<%else>

<% locale.getString("www.text.noResults") %>

</%if>

<& ../IFooter; user=user; locale=locale; properties=properties; recentUsers=recentUsers; &>

## 内容2
### 文件路径：
templates/com/pugh/sockso/templates/web/browse/TPlaylists.jamon
### 代码内容：
<%import>
    com.pugh.sockso.Constants;
    com.pugh.sockso.Utils;
    com.pugh.sockso.Properties;
    com.pugh.sockso.music.Playlist;
    com.pugh.sockso.web.User;
    com.pugh.sockso.resources.Locale;
    java.util.Vector;
</%import>

<%implements>
    com.pugh.sockso.web.PageTemplate;
</%implements>

<%args>
    Properties properties = null;
    Vector<Playlist> sitePlaylists = null;
    Vector<Playlist> userPlaylists = null;
    User user = null;
    Locale locale = null;
    Vector<User> recentUsers = null;
</%args>

<& ../IHeader; properties=properties; title="Playlists"; user=user; locale=locale; &>

<% locale.getString("www.title.sitePlaylists") %>

    <%if sitePlaylists.size() > 0 %>
        <%for Playlist playlist : sitePlaylists %>

                <& IMusicLinks; type="pl"; id=playlist.getId(); name=playlist.getName(); locale=locale; properties=properties; &>
                <a href="<% properties.getUrl("/browse/playlist/"+playlist.getId()) #n %>"><% Utils.u2e(playlist.getName()) #n %>
                (<% playlist.getTrackCount() %> track<%if playlist.getTrackCount() != 1 %>s</%if>)

        </%for>
    <%else>

<% locale.getString("www.text.noResults") %>

    </%if>

<% locale.getString("www.title.userPlaylists") %>

    <%if userPlaylists.size() > 0 %>
        <%for Playlist playlist : userPlaylists %>
            <li class="playlist" id="userPlaylist<% playlist.getId() %>">
                <& IMusicLinks; type="pl"; id=playlist.getId(); name=playlist.getName(); locale=locale; properties=properties; &>
                <a href="<% properties.getUrl("/browse/playlist/"+playlist.getId()) #n %>"><% Utils.u2e(playlist.getName()) #n %>
                by
                <%if user != null && (user.getId() == playlist.getUser().getId()) %>
                    you
                <%else>
                    <% Utils.u2e(playlist.getUser().getName()) #n %>
                </%if>
                (<% playlist.getTrackCount() %> track<%if playlist.getTrackCount() != 1 %>s</%if>)
                <%if user != null && (playlist.getUser().getId() == user.getId()) %>
                    <a href="javascript:;" class="delete" onclick="deletePlaylist('<% playlist.getId() %>');return false;"><img
                        src="<% properties.getUrl("/<skin>/images/remove.png") #n %>" title="<% locale.getString("www.label.deletePlaylist") %>" />
                </%if>

        </%for>
    <%else>

<% locale.getString("www.text.noResults") %>

    </%if>

<& ../IFooter; user=user; locale=locale; properties=properties; recentUsers=recentUsers; &>