FormsHelper.java 43.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.xss.XSSAPI
 *  com.day.cq.wcm.api.LanguageManager
 *  com.day.cq.wcm.api.WCMMode
 *  com.day.cq.wcm.api.components.ComponentContext
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.servlet.RequestDispatcher
 *  javax.servlet.ServletException
 *  javax.servlet.ServletRequest
 *  javax.servlet.ServletResponse
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.jsp.JspWriter
 *  javax.servlet.jsp.PageContext
 *  org.apache.commons.lang.StringUtils
 *  org.apache.commons.lang3.StringEscapeUtils
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.request.RequestDispatcherOptions
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.request.RequestParameterMap
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ResourceWrapper
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.api.scripting.SlingBindings
 *  org.apache.sling.api.scripting.SlingScriptHelper
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.jcr.JsonItemWriter
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.foundation.forms;

import com.adobe.granite.xss.XSSAPI;
import com.day.cq.wcm.api.LanguageManager;
import com.day.cq.wcm.api.WCMMode;
import com.day.cq.wcm.api.components.ComponentContext;
import com.day.cq.wcm.foundation.ELEvaluator;
import com.day.cq.wcm.foundation.forms.FieldHelper;
import com.day.cq.wcm.foundation.forms.FormResourceEdit;
import com.day.cq.wcm.foundation.forms.FormsConstants;
import com.day.cq.wcm.foundation.forms.ValidationInfo;
import com.day.cq.wcm.foundation.forms.impl.FormsUtil;
import com.day.cq.wcm.foundation.forms.impl.JspSlingHttpServletResponseWrapper;
import com.day.cq.wcm.foundation.forms.impl.ResourceWrapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestDispatcherOptions;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.request.RequestParameterMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.jcr.JsonItemWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FormsHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger((String)FormsHelper.class.getName());
    public static final String REQ_ATTR_GLOBAL_LOAD_MAP = "cq.form.loadmap";
    public static final String REQ_ATTR_GLOBAL_LOAD_RESOURCE = "cq.form.loadresource";
    public static final String REQ_ATTR_EDIT_RESOURCES = "cq.form.editresources";
    public static final String REQ_ATTR_CLIENT_VALIDATION = "cq.form.clientvalidation";
    public static final String REQ_ATTR_FORMID = "cq.form.id";
    public static final String REQ_ATTR_WRITTEN_JAVASCRIPT = "cq.form.javascript";
    public static final String REQ_ATTR_ACTION_SUFFIX = "cq.form.action.suffix";
    public static final String REQ_ATTR_FORWARD_PATH = "cq.form.forward.path";
    public static final String REQ_ATTR_FORWARD_OPTIONS = "cq.form.forward.options";
    public static final String REQ_ATTR_IS_INIT = "cq.form.init";
    public static final String REQ_ATTR_READ_ONLY = "cq.form.readonly";
    public static final String REQ_ATTR_REDIRECT = "cq.form.redirect";
    public static final String REQ_ATTR_REDIRECT_TO_REFERRER = FormsConstants.REQUEST_ATTR_REDIRECT_TO_REFERRER;
    public static final String REQ_ATTR_PROP_WHITELIST = "cq.form.prop.whitelist";
    public static final String REQ_ATTR_EXPRESSIONS_ENABLED = "cq.form.expressions.enabled";

    private FormsHelper() {
    }

    @Deprecated
    public static void startForm(SlingHttpServletRequest request, SlingHttpServletResponse response, JspWriter out) throws IOException, ServletException {
        FormsHelper.startForm(request, (SlingHttpServletResponse)new JspSlingHttpServletResponseWrapper(response, out));
    }

    public static void startForm(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException {
        String actionType;
        Resource formResource = request.getResource();
        FormsHelper.initialize(request, formResource, response);
        FormsHelper.writeJavaScript(request, response, formResource);
        ValueMap properties = ResourceUtil.getValueMap((Resource)formResource);
        String formId = (String)properties.get("id", (Object)"");
        if (StringUtils.isEmpty((String)formId)) {
            formId = FormsHelper.getFormId(request);
        }
        PrintWriter out = response.getWriter();
        String url = request.getRequestURI();
        String suffix = FormsHelper.getActionSuffix(request);
        if (StringUtils.isNotBlank((String)suffix)) {
            url = url + (suffix.startsWith("/") ? suffix : new StringBuilder().append("/").append(suffix).toString());
        }
        SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());
        XSSAPI xssAPI = ((XSSAPI)bindings.getSling().getService(XSSAPI.class)).getRequestSpecificAPI(request);
        String cssClass = (String)properties.get("css", (Object)"");
        out.print("<form method=\"POST\" action=\"");
        out.print(xssAPI.getValidHref(url));
        out.print("\" id=\"");
        out.print(xssAPI.encodeForHTMLAttr(formId));
        out.print("\" name=\"");
        out.print(xssAPI.encodeForHTMLAttr(formId));
        if (!StringUtils.isEmpty((String)cssClass)) {
            out.print("\" class=\"");
            out.print(xssAPI.encodeForHTMLAttr(cssClass));
        }
        out.print("\" enctype=\"multipart/form-data\">");
        out.print("<input type=\"hidden\" name=\"");
        out.print(":formid");
        out.print("\" value=\"");
        out.print(xssAPI.encodeForHTMLAttr(formId));
        out.print("\"/>");
        out.print("<input type=\"hidden\" name=\"");
        out.print(":formstart");
        out.print("\" value=\"");
        if (formResource.getPath().startsWith(url)) {
            out.print(xssAPI.encodeForHTMLAttr(formResource.getPath().substring(url.length() + 1)));
        } else {
            out.print(xssAPI.encodeForHTMLAttr(formResource.getPath()));
        }
        out.print("\"/>");
        out.print("<input type=\"hidden\" name=\"_charset_\" value=\"UTF-8\"/>");
        String redirect = (String)properties.get("redirect", (Object)"");
        if (redirect.length() > 0) {
            int lastSlash;
            redirect = request.getResourceResolver().map((HttpServletRequest)request, redirect);
            if (redirect.indexOf(46, lastSlash = redirect.lastIndexOf(47)) == -1) {
                redirect = redirect + ".html";
            }
            out.print("<input type=\"hidden\" name=\":redirect\" value=\"");
            out.print(xssAPI.encodeForHTMLAttr(redirect));
            out.print("\"/>");
        }
        if ((actionType = (String)properties.get("actionType", (Object)"")).length() > 0) {
            FormsHelper.runAction(actionType, "addfields", formResource, request, response);
        }
    }

    private static void initialize(SlingHttpServletRequest request, Resource formResource, SlingHttpServletResponse response) throws IOException, ServletException {
        String actionType;
        ValueMap properties = ResourceUtil.getValueMap((Resource)formResource);
        Boolean clientValidation = (Boolean)properties.get("clientValidation", (Object)Boolean.FALSE);
        request.setAttribute("cq.form.clientvalidation", (Object)clientValidation);
        request.setAttribute("cq.form.id", properties.get("formid", (Object)"new_form"));
        request.setAttribute("cq.form.init", (Object)"true");
        if (response != null && (actionType = (String)properties.get("actionType", (Object)"foundation/components/form/actions/store")).length() != 0) {
            FormsHelper.runAction(actionType, "init", formResource, request, response);
        }
        if (request.getAttribute("cq.form.loadmap") == null) {
            Resource loadResource = null;
            String loadPath = (String)properties.get("loadPath", (Object)"");
            if (loadPath.length() > 0) {
                loadResource = formResource.getResourceResolver().getResource(loadPath);
            }
            FormsHelper.setFormLoadResource(request, loadResource);
        }
    }

    public static void runAction(String actionType, String scriptName, Resource formResource, SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException {
        String rt = actionType;
        if (actionType.indexOf(47) == -1) {
            rt = "foundation/components/form/actions/" + actionType;
        }
        ResourceWrapper includeResource = new ResourceWrapper(formResource, rt, "foundation/components/form/defaults/action");
        FormsHelper.includeResource(request, response, (Resource)includeResource, scriptName);
    }

    private static void checkInit(SlingHttpServletRequest request) {
        if (request.getAttribute("cq.form.init") == null) {
            Resource formStart = FormsHelper.searchFormStart(request.getResource());
            try {
                FormsHelper.initialize(request, formStart, null);
            }
            catch (IOException e) {
            }
            catch (ServletException e) {
                // empty catch block
            }
        }
    }

    private static Resource searchFormStart(Resource resource) {
        Resource current;
        if (ResourceUtil.getName((Resource)resource).equals("jcr:content")) {
            return null;
        }
        if (resource.getPath().lastIndexOf("/") == 0) {
            return null;
        }
        if (FormsHelper.checkResourceType(resource, "foundation/components/form/start")) {
            return resource;
        }
        Resource parent = ResourceUtil.getParent((Resource)resource);
        ArrayList<Resource> predecessor = new ArrayList<Resource>();
        Iterator i = ResourceUtil.listChildren((Resource)parent);
        while (i.hasNext() && !(current = (Resource)i.next()).getPath().equals(resource.getPath())) {
            predecessor.add(current);
        }
        Collections.reverse(predecessor);
        for (Resource current2 : predecessor) {
            if (FormsHelper.checkResourceType(current2, "foundation/components/form/start")) {
                return resource;
            }
            if (!FormsHelper.checkResourceType(current2, "foundation/components/form/end")) continue;
            return null;
        }
        return FormsHelper.searchFormStart(parent);
    }

    private static boolean checkResourceType(Resource resource, String type) {
        return ResourceUtil.isA((Resource)resource, (String)type);
    }

    public static void endForm(SlingHttpServletRequest req) {
        FormsHelper.setFormLoadResource(req, null);
        req.removeAttribute("cq.form.clientvalidation");
        req.removeAttribute("cq.form.id");
        req.removeAttribute("cq.form.init");
    }

    public static void setForwardPath(SlingHttpServletRequest req, String path) {
        FormsHelper.setForwardPath(req, path, false);
    }

    public static void setForwardPath(SlingHttpServletRequest req, String path, boolean clearFormSelector) {
        req.setAttribute("cq.form.forward.path", (Object)path);
        if (clearFormSelector) {
            RequestDispatcherOptions options = new RequestDispatcherOptions();
            options.setReplaceSelectors("");
            FormsHelper.setForwardOptions((ServletRequest)req, options);
        }
    }

    public static String getForwardPath(SlingHttpServletRequest req) {
        return (String)req.getAttribute("cq.form.forward.path");
    }

    public static void setForwardOptions(ServletRequest req, RequestDispatcherOptions options) {
        req.setAttribute("cq.form.forward.options", (Object)options);
    }

    public static RequestDispatcherOptions getForwardOptions(ServletRequest req) {
        return (RequestDispatcherOptions)req.getAttribute("cq.form.forward.options");
    }

    public static void setForwardRedirect(ServletRequest request, String redirect) {
        request.setAttribute("cq.form.redirect", (Object)redirect);
    }

    public static String getForwardRedirect(ServletRequest request) {
        return (String)request.getAttribute("cq.form.redirect");
    }

    public static void setActionSuffix(SlingHttpServletRequest req, String suffix) {
        req.setAttribute("cq.form.action.suffix", (Object)suffix);
    }

    public static String getActionSuffix(SlingHttpServletRequest req) {
        return (String)req.getAttribute("cq.form.action.suffix");
    }

    public static void setFormLoadResource(SlingHttpServletRequest req, Resource rsrc) {
        req.removeAttribute("cq.form.loadmap");
        req.removeAttribute("cq.form.loadresource");
        if (rsrc != null) {
            req.setAttribute("cq.form.loadresource", (Object)rsrc);
            ValueMap map = ResourceUtil.getValueMap((Resource)rsrc);
            req.setAttribute("cq.form.loadmap", (Object)map);
        }
    }

    public static Resource getFormLoadResource(SlingHttpServletRequest req) {
        return (Resource)req.getAttribute("cq.form.loadresource");
    }

    public static ValueMap getGlobalFormValues(SlingHttpServletRequest req) {
        FormsHelper.checkInit(req);
        return (ValueMap)req.getAttribute("cq.form.loadmap");
    }

    public static void setFormEditResources(SlingHttpServletRequest req, List<Resource> resources) {
        FormResourceEdit.setResources((ServletRequest)req, resources);
    }

    public static List<Resource> getFormEditResources(SlingHttpServletRequest req) {
        return FormResourceEdit.getResources((ServletRequest)req);
    }

    public static String getFormsPreCheckMethodName(SlingHttpServletRequest req) {
        String formId = FormsHelper.getFormId(req);
        SlingBindings bindings = (SlingBindings)req.getAttribute(SlingBindings.class.getName());
        XSSAPI xssAPI = ((XSSAPI)bindings.getSling().getService(XSSAPI.class)).getRequestSpecificAPI(req);
        if (formId != null) {
            formId = xssAPI.getValidJSToken(formId, "defaultForm");
        }
        return "cq5forms_preCheck_" + formId;
    }

    private static void writeJavaScript(SlingHttpServletRequest req, SlingHttpServletResponse response, final Resource formResource) throws IOException, ServletException {
        if (FormsHelper.doClientValidation(req)) {
            PrintWriter out = response.getWriter();
            out.println("<script type=\"text/javascript\">");
            if (WCMMode.fromRequest((ServletRequest)req) != WCMMode.DISABLED) {
                out.println("  cq5forms_reloadForPreview = true;");
            }
            out.println("  function " + FormsHelper.getFormsPreCheckMethodName(req) + "(submitid) {");
            out.println("    var dMsgs = \"Please fill out the required field.\";");
            Iterator<Resource> iter = FormsHelper.getFormElements(formResource);
            while (iter.hasNext()) {
                Resource formsField = iter.next();
                FieldHelper.initializeField(req, response, formsField);
                FormsHelper.includeResource(req, response, formsField, "clientvalidation");
            }
            ValueMap properties = ResourceUtil.getValueMap((Resource)formResource);
            final String valScriptRT = (String)properties.get("validationRT", (Object)formResource.getResourceType());
            if (valScriptRT != null && valScriptRT.length() > 0) {
                Object valScriptResource = formResource;
                if (!formResource.getResourceType().equals(valScriptRT)) {
                    valScriptResource = new org.apache.sling.api.resource.ResourceWrapper(formResource){

                        public String getResourceType() {
                            return valScriptRT;
                        }

                        public String getResourceSuperType() {
                            return formResource.getResourceType();
                        }
                    };
                }
                FormsHelper.includeResource(req, response, (Resource)valScriptResource, "formclientvalidation");
            }
            out.println("    return true;");
            out.println("  }");
            out.println("</script>");
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static void includeResource(SlingHttpServletRequest request, SlingHttpServletResponse response, Resource resource, String selectorString) throws IOException, ServletException {
        Object oldValue = request.getAttribute(ComponentContext.BYPASS_COMPONENT_HANDLING_ON_INCLUDE_ATTRIBUTE);
        try {
            request.setAttribute(ComponentContext.BYPASS_COMPONENT_HANDLING_ON_INCLUDE_ATTRIBUTE, (Object)"true");
            RequestDispatcherOptions options = new RequestDispatcherOptions();
            options.setReplaceSelectors(selectorString);
            request.getRequestDispatcher(resource, options).include((ServletRequest)request, (ServletResponse)response);
        }
        finally {
            if (oldValue == null) {
                request.removeAttribute(ComponentContext.BYPASS_COMPONENT_HANDLING_ON_INCLUDE_ATTRIBUTE);
            } else {
                request.setAttribute(ComponentContext.BYPASS_COMPONENT_HANDLING_ON_INCLUDE_ATTRIBUTE, oldValue);
            }
        }
    }

    public static boolean doClientValidation(SlingHttpServletRequest req) {
        FormsHelper.checkInit(req);
        Boolean value = (Boolean)req.getAttribute("cq.form.clientvalidation");
        if (value == null) {
            value = Boolean.FALSE;
        }
        return value;
    }

    public static String getFormId(SlingHttpServletRequest req) {
        FormsHelper.checkInit(req);
        return (String)req.getAttribute("cq.form.id");
    }

    public static String getParameterName(Resource rsrc) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)rsrc);
        String name = (String)properties.get("name", (Object)"");
        if (name.length() == 0) {
            name = ResourceUtil.getName((Resource)rsrc);
            name = FormsUtil.filterElementName(name);
        }
        return name;
    }

    public static String getFieldId(SlingHttpServletRequest req, Resource rsrc) {
        return FormsHelper.getFormId(req) + '_' + FormsHelper.getParameterName(rsrc);
    }

    public static Iterator<Resource> getFormElements(Resource formResource) {
        ArrayList<Resource> list = new ArrayList<Resource>();
        Iterator iter = ResourceUtil.listChildren((Resource)ResourceUtil.getParent((Resource)formResource));
        while (!((Resource)iter.next()).getPath().equals(formResource.getPath())) {
        }
        FormsHelper.collectFormElements(list, iter);
        return list.iterator();
    }

    public static Iterator<String> getContentRequestParameterNames(SlingHttpServletRequest req) {
        ArrayList<String> names = new ArrayList<String>();
        Enumeration paramNames = req.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name = (String)paramNames.nextElement();
            if (name.startsWith(":") || name.equals("_charset_")) continue;
            names.add(name);
        }
        return names.iterator();
    }

    private static boolean collectFormElements(List<Resource> list, Iterator<Resource> iter) {
        boolean stop = false;
        while (!stop && iter.hasNext()) {
            Resource n = iter.next();
            if (FormsHelper.checkResourceType(n, "foundation/components/form/end")) {
                stop = true;
                break;
            }
            if (n.getResourceType().startsWith("foundation/components/form/") || n.getResourceSuperType() != null && n.getResourceSuperType().startsWith("foundation/components/form/")) {
                list.add(n);
                continue;
            }
            Iterator cI = ResourceUtil.listChildren((Resource)n);
            if (cI == null) continue;
            stop = FormsHelper.collectFormElements(list, cI);
        }
        return stop;
    }

    public static Resource getResource(SlingHttpServletRequest request, Resource elementResource, String relPath) {
        ArrayList<Resource> resources = new ArrayList<Resource>();
        List<Resource> editRes = FormResourceEdit.getResources((ServletRequest)request);
        if (editRes != null) {
            resources.addAll(editRes);
        }
        resources.add(elementResource);
        ResourceResolver resolver = request.getResourceResolver();
        for (Resource r : resources) {
            Resource res = resolver.getResource(r, relPath);
            if (res == null) continue;
            return res;
        }
        return null;
    }

    public static String getValue(SlingHttpServletRequest request, Resource elementResource) {
        return FormsHelper.getValue(request, elementResource, null);
    }

    public static String getValue(SlingHttpServletRequest request, Resource elementResource, String nameParam) {
        String[] values = FormsHelper.getValues(request, elementResource, nameParam);
        if (values != null && values.length > 0) {
            return values[0];
        }
        return null;
    }

    public static String[] getValues(SlingHttpServletRequest request, Resource elementResource) {
        return FormsHelper.getValues(request, elementResource, null);
    }

    public static String[] getValues(SlingHttpServletRequest request, Resource elementResource, String nameParam) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)elementResource);
        String name = nameParam != null ? nameParam : FormsHelper.getParameterName(elementResource);
        ValidationInfo info = ValidationInfo.getValidationInfo((HttpServletRequest)request);
        if (info != null) {
            return info.getValues(name);
        }
        ValueMap globalFormValues = FormsHelper.getGlobalFormValues(request);
        String[] defaultValues = null;
        String loadPath = (String)properties.get("loadPath", (Object)"");
        if (loadPath.length() > 0) {
            Resource rsrc = request.getResourceResolver().getResource(loadPath);
            if (rsrc != null) {
                defaultValues = (String[])rsrc.adaptTo(String[].class);
            } else if (globalFormValues != null && globalFormValues.get((Object)loadPath) != null) {
                defaultValues = (String[])globalFormValues.get(loadPath, String[].class);
            }
        } else if (globalFormValues != null && globalFormValues.get((Object)name) != null) {
            defaultValues = (String[])globalFormValues.get(name, String[].class);
        }
        if (defaultValues == null) {
            defaultValues = (String[])properties.get("defaultValue", String[].class);
        }
        return defaultValues;
    }

    public static List<String> getValuesAsList(SlingHttpServletRequest request, Resource elementResource) {
        String[] values = FormsHelper.getValues(request, elementResource);
        if (values == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(values);
    }

    public static String getValue(SlingHttpServletRequest request, String name, String defaultValue) {
        String[] values = FormsHelper.getValues(request, name, null);
        if (values == null || values.length == 0) {
            return defaultValue;
        }
        return values[0];
    }

    public static String[] getValues(SlingHttpServletRequest request, String name, String[] defaultValues) {
        ValueMap globalFormValues = FormsHelper.getGlobalFormValues(request);
        if (globalFormValues == null || globalFormValues.get((Object)name) == null) {
            return defaultValues;
        }
        return (String[])globalFormValues.get(name, String[].class);
    }

    public static void inlineValuesAsJson(SlingHttpServletRequest request, Writer out, String path) throws IOException, RepositoryException, JSONException {
        FormsHelper.inlineValuesAsJson(request, out, path, -1);
    }

    /*
     * Enabled aggressive block sorting
     */
    public static void inlineValuesAsJson(SlingHttpServletRequest request, Writer out, String path, int nodeDepth) throws IOException, RepositoryException, JSONException {
        Node node;
        out.flush();
        Session session = (Session)request.getResourceResolver().adaptTo(Session.class);
        if (path.startsWith("/")) {
            if (!session.nodeExists(path)) {
                out.append("{}");
                return;
            }
            node = session.getNode(path);
        } else {
            Resource loadResource = FormsHelper.getFormLoadResource(request);
            if (loadResource == null) {
                out.append("{}");
                return;
            }
            node = (Node)loadResource.adaptTo(Node.class);
            if (node == null) {
                out.append("{}");
                return;
            }
            if (!node.hasNode(path)) {
                out.append("{}");
                return;
            }
            node = node.getNode(path);
        }
        JsonItemWriter jsonWriter = new JsonItemWriter(null);
        jsonWriter.dump(node, (Writer)new PrintWriter(out), nodeDepth);
        out.flush();
    }

    private static void accumulateShowHideExpressions(Node node, Map<String, String> map) throws RepositoryException {
        if (node.hasProperty("showHideExpression")) {
            map.put(node.hasProperty("name") ? node.getProperty("name").getString() : node.getName(), node.getProperty("showHideExpression").getString());
        }
        NodeIterator iterator = node.getNodes();
        while (iterator.hasNext()) {
            FormsHelper.accumulateShowHideExpressions(iterator.nextNode(), map);
        }
    }

    public static Map<String, String> getShowHideExpressions(Resource resource) throws RepositoryException {
        Node node = (Node)resource.adaptTo(Node.class);
        HashMap<String, String> map = new HashMap<String, String>();
        FormsHelper.accumulateShowHideExpressions(node, map);
        return map;
    }

    public static Map<String, String> getOptions(SlingHttpServletRequest request, Resource elementResource) {
        Resource rsrc;
        ValueMap properties = ResourceUtil.getValueMap((Resource)elementResource);
        String[] options = null;
        String loadPath = (String)properties.get("optionsLoadPath", (Object)"");
        if (loadPath.length() > 0 && (rsrc = request.getResourceResolver().getResource(loadPath)) != null) {
            options = (String[])rsrc.adaptTo(String[].class);
        }
        if (options == null) {
            options = (String[])properties.get("options", String[].class);
        }
        if (options == null) {
            return null;
        }
        LinkedHashMap<String, String> splitValues = new LinkedHashMap<String, String>();
        for (int i = 0; i < options.length; ++i) {
            String value = options[i].trim();
            if (value.length() > 0) {
                String t;
                String v;
                boolean endLoop = true;
                int pos = -1;
                int start = 0;
                do {
                    if ((pos = value.indexOf(61, start)) > 0 && value.charAt(pos - 1) == '\\') {
                        start = pos + 1;
                        endLoop = false;
                        continue;
                    }
                    endLoop = true;
                } while (!endLoop);
                if (pos == -1) {
                    v = value;
                    t = value;
                } else {
                    v = value.substring(0, pos);
                    t = value.substring(pos + 1);
                }
                v = v.replace("\\=", "=");
                t = t.replace("\\=", "=");
                splitValues.put(v, t);
                continue;
            }
            splitValues.put("", "");
        }
        if (splitValues.size() == 0) {
            return null;
        }
        return splitValues;
    }

    public static boolean isRequired(Resource formElement) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)formElement);
        return (Boolean)properties.get("required", (Object)Boolean.FALSE);
    }

    public static void setFormReadOnly(SlingHttpServletRequest request) {
        request.setAttribute("cq.form.readonly", (Object)true);
    }

    public static Object pushFormReadOnly(SlingHttpServletRequest request) {
        boolean previousState = FormsHelper.isReadOnly(request);
        request.setAttribute("cq.form.readonly", (Object)true);
        return previousState;
    }

    public static void popFormReadOnly(SlingHttpServletRequest request, Object previousState) {
        if (!((Boolean)previousState).booleanValue()) {
            request.removeAttribute("cq.form.readonly");
        }
    }

    public static boolean isReadOnly(SlingHttpServletRequest request, Resource formElement) {
        if (request.getAttribute("cq.form.readonly") != null) {
            return true;
        }
        ValueMap properties = ResourceUtil.getValueMap((Resource)formElement);
        return (Boolean)properties.get("readOnly", (Object)Boolean.FALSE);
    }

    public static boolean isReadOnly(SlingHttpServletRequest request) {
        return request.getAttribute("cq.form.readonly") != null;
    }

    @Deprecated
    public static boolean isReadOnly(Resource formElement) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)formElement);
        return (Boolean)properties.get("readOnly", (Object)Boolean.FALSE);
    }

    public static boolean checkRule(Resource resource, SlingHttpServletRequest req, PageContext pageContext, String propName) {
        ValueMap valueMap = ResourceUtil.getValueMap((Resource)resource);
        String rule = (String)valueMap.get(propName, (Object)null);
        if (rule == null) {
            return true;
        }
        String[] ruleParts = (rule = ELEvaluator.evaluate(rule, req, pageContext)).split(":");
        if (ruleParts.length < 2) {
            return true;
        }
        if (ruleParts[0].equals("access")) {
            if (ruleParts.length != 3) {
                return true;
            }
            String path = ruleParts[1];
            String permission = ruleParts[2];
            try {
                Node node = (Node)resource.adaptTo(Node.class);
                Session session = node.getSession();
                session.checkPermission(path, permission);
            }
            catch (AccessControlException ace) {
                return false;
            }
            catch (RepositoryException re) {
                LOGGER.error("Could not determine access rights for path '" + path + "'", (Throwable)re);
                return false;
            }
        }
        return true;
    }

    public static String getTitle(Resource formElement, String defaultTitle) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)formElement);
        return (String)properties.get("jcr:title", (Object)defaultTitle);
    }

    public static String getDescription(Resource formElement, String defaultDescription) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)formElement);
        return (String)properties.get("jcr:description", (Object)defaultDescription);
    }

    public static boolean hasMultiSelection(Resource formElement) {
        ValueMap properties = ResourceUtil.getValueMap((Resource)formElement);
        return (Boolean)properties.get("multiSelection", (Object)Boolean.FALSE);
    }

    public static void redirectToReferrer(SlingHttpServletRequest req, SlingHttpServletResponse res, Map<String, String[]> params) throws IOException {
        String referrer = FormsHelper.getReferrer((HttpServletRequest)req);
        if (params != null && params.size() > 0) {
            StringBuilder buffer = new StringBuilder(referrer);
            boolean hasParams = referrer.indexOf(63) > 0;
            for (Map.Entry<String, String[]> entry : params.entrySet()) {
                for (String value : entry.getValue()) {
                    buffer.append(hasParams ? '&' : '?');
                    hasParams = true;
                    buffer.append(entry.getKey());
                    buffer.append('=');
                    buffer.append(URLEncoder.encode(value, "utf-8"));
                }
            }
            res.sendRedirect(buffer.toString());
        } else {
            res.sendRedirect(referrer);
        }
    }

    public static void redirectToReferrer(SlingHttpServletRequest request, SlingHttpServletResponse res) throws IOException {
        String referrer = FormsHelper.getReferrer((HttpServletRequest)request);
        int pos = referrer.indexOf(63);
        if (pos > 0) {
            referrer = referrer.substring(0, pos);
        }
        StringBuilder buffer = new StringBuilder(referrer);
        RequestParameterMap params = request.getRequestParameterMap();
        if (params.entrySet().size() > 0) {
            buffer.append("?");
            boolean first = true;
            for (Map.Entry current : params.entrySet()) {
                RequestParameter[] values = (RequestParameter[])current.getValue();
                for (int i = 0; i < values.length; ++i) {
                    if (first) {
                        first = false;
                    } else {
                        buffer.append("&");
                    }
                    buffer.append((String)current.getKey());
                    buffer.append("=");
                    buffer.append(values[i].getString());
                }
            }
        }
        res.sendRedirect(buffer.toString());
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static Resource checkFormStructure(Resource rsrc) {
        Resource formStart;
        if (FormsHelper.checkResourceType(rsrc, "foundation/components/form/start")) {
            Node start = (Node)rsrc.adaptTo(Node.class);
            if (start != null) {
                try {
                    if (!start.hasProperty("actionType")) {
                        start.setProperty("actionType", "foundation/components/form/actions/store");
                        String defaultContentPath = "/content/usergenerated" + rsrc.getPath().replaceAll("^.content", "").replaceAll("jcr.content.*", "") + "cq-gen" + System.currentTimeMillis() + "/";
                        start.setProperty("action", defaultContentPath);
                    }
                    if (!start.hasProperty("formid")) {
                        start.setProperty("formid", rsrc.getPath().replaceAll("[/:.]", "_"));
                    }
                    start.getSession().save();
                }
                catch (RepositoryException e) {
                    LOGGER.error("Unable to add default action type and form id " + (Object)rsrc, (Throwable)e);
                }
            } else {
                LOGGER.error("Resource is not adaptable to node - unable to add default action type and form id for " + (Object)rsrc);
            }
            Iterator iter = ResourceUtil.listChildren((Resource)ResourceUtil.getParent((Resource)rsrc));
            while (!((Resource)iter.next()).getPath().equals(rsrc.getPath())) {
            }
            Resource formEnd = null;
            Resource nextPar = null;
            boolean stop = false;
            while (iter.hasNext() && formEnd == null && !stop) {
                Resource current = (Resource)iter.next();
                if (nextPar == null) {
                    nextPar = current;
                }
                if (FormsHelper.checkResourceType(current, "foundation/components/form/end")) {
                    formEnd = current;
                    continue;
                }
                if (!FormsHelper.checkResourceType(current, "foundation/components/form/start")) continue;
                stop = true;
            }
            if (formEnd == null) {
                Node parent = (Node)ResourceUtil.getParent((Resource)rsrc).adaptTo(Node.class);
                if (parent != null) {
                    try {
                        String nodeName = "form_end_" + System.currentTimeMillis();
                        Node node = parent.addNode(nodeName);
                        ValueMap props = ResourceUtil.getValueMap((Resource)rsrc);
                        String resourceType = "foundation/components/form/end";
                        if (props != null) {
                            resourceType = (String)props.get("endResourceType", (Object)resourceType);
                        }
                        node.setProperty("sling:resourceType", resourceType);
                        if (!resourceType.equals("foundation/components/form/end")) {
                            node.setProperty("sling:resourceSuperType", "foundation/components/form/end");
                        }
                        if (nextPar != null) {
                            parent.orderBefore(node.getName(), ResourceUtil.getName((Resource)nextPar));
                        }
                        parent.getSession().save();
                        Iterator i = ResourceUtil.listChildren((Resource)ResourceUtil.getParent((Resource)rsrc));
                        while (i.hasNext()) {
                            Resource r = (Resource)i.next();
                            if (!nodeName.equals(ResourceUtil.getName((Resource)r))) continue;
                            Resource resource = r;
                            return resource;
                        }
                    }
                    catch (RepositoryException re) {
                        LOGGER.error("Unable to create missing form end element for form start " + (Object)rsrc, (Throwable)re);
                    }
                    finally {
                        try {
                            if (parent.getSession().hasPendingChanges()) {
                                parent.getSession().refresh(false);
                            }
                        }
                        catch (RepositoryException re) {}
                    }
                } else {
                    LOGGER.error("Resource is not adaptable to node - unable to add missing form end element for " + (Object)rsrc);
                }
            }
        } else if (FormsHelper.checkResourceType(rsrc, "foundation/components/form/end") && (formStart = FormsHelper.searchFormStart(rsrc)) == null) {
            Node node = (Node)rsrc.adaptTo(Node.class);
            Node parent = (Node)ResourceUtil.getParent((Resource)rsrc).adaptTo(Node.class);
            if (node != null && parent != null) {
                try {
                    node.remove();
                    parent.getSession().save();
                    Resource nextPar = rsrc;
                    return nextPar;
                }
                catch (RepositoryException re) {
                    LOGGER.error("Unable to create missing form end element for form start " + (Object)rsrc, (Throwable)re);
                }
                finally {
                    try {
                        if (node.getSession().hasPendingChanges()) {
                            node.getSession().refresh(false);
                        }
                    }
                    catch (RepositoryException re) {}
                }
            }
            LOGGER.error("Resource is not adaptable to node - unable to remove form element " + (Object)rsrc);
        }
        return null;
    }

    public static String encodeValue(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            return value;
        }
    }

    public static String decodeValue(String value) {
        try {
            return URLDecoder.decode(value, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            return value;
        }
    }

    public static String getCss(ValueMap props, String defaultCss) {
        String configCss = (String)props.get("css", null);
        if (configCss == null) {
            return defaultCss;
        }
        return defaultCss + ' ' + StringEscapeUtils.escapeHtml4((String)configCss);
    }

    public static String getReferrer(HttpServletRequest request) {
        return request.getHeader("Referer") != null ? request.getHeader("Referer") : request.getHeader("Referrer");
    }

    public static void setRedirectToReferrer(ServletRequest request, boolean redirectToReferrer) {
        if (redirectToReferrer) {
            request.setAttribute(REQ_ATTR_REDIRECT_TO_REFERRER, (Object)"true");
        } else {
            request.removeAttribute(REQ_ATTR_REDIRECT_TO_REFERRER);
        }
    }

    public static boolean isRedirectToReferrer(ServletRequest request) {
        return "true".equals(request.getAttribute(REQ_ATTR_REDIRECT_TO_REFERRER));
    }

    public static Locale getLocale(SlingHttpServletRequest request) {
        SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());
        if (bindings == null) {
            LOGGER.debug("The request does not provide a SlingBindings attribute: the method returns null.");
            return null;
        }
        SlingScriptHelper scriptHelper = bindings.getSling();
        LanguageManager langMgr = (LanguageManager)scriptHelper.getService(LanguageManager.class);
        if (langMgr == null) {
            LOGGER.debug("The LanguageManager service is not available: the method returns null.");
            return null;
        }
        Resource resource = request.getResource();
        Locale locale = langMgr.getLanguage(resource);
        return locale;
    }

    public static String getLocalizedMessage(String msg, SlingHttpServletRequest request) {
        Locale locale = FormsHelper.getLocale(request);
        ResourceBundle resBundle = request.getResourceBundle(locale);
        if (resBundle == null || msg == null || resBundle.getString(msg) == null) {
            LOGGER.debug("The message cannot be localized: the method returns the original message.");
            return msg;
        }
        return resBundle.getString(msg);
    }

    public static String[] getWhitelistPatterns(SlingHttpServletRequest req) {
        return (String[])req.getAttribute("cq.form.prop.whitelist");
    }

    public static boolean allowExpressions(SlingHttpServletRequest req) {
        Boolean expressionsEnabledAttr = (Boolean)req.getAttribute("cq.form.expressions.enabled");
        if (expressionsEnabledAttr == null) {
            return true;
        }
        return expressionsEnabledAttr;
    }

}