API Docs for: WebTemplate API v2.0
Show:

File: /data/www/webtemplate/wtv2/codedoc/wtForm.php

<?php
/**
 *  WebTemplate Core
 *
 *  @version 2.0
 *  @module WebTemplate Core
 */


if(!isset($_SESSION["WTFORMIDS"])) {
  $_SESSION["WTFORMIDS"] = Array();
}

$GLOBALS["WTFORMHANDLERS"] = Array();

function wtFormJSCallback($data, $args = Array()) 
{
  $fieldID = "Field" . $data["__guid"];
  
  if($data["Field Type"] != "Hidden" && $data["Field Type"] != "Fieldset" && $data["Field Type"] != "Fieldset close") {
    if($data["Field Type"] != 'Static') {
      if($data["Required ID"] == 1) {
        $form->m_hasRequiredFields = true;
        if($data["Field Type"] == "Email Address") {
          return $fieldID . ":'requiredemail',";
//          $args["definition"][$fieldID] = "requiredemail";
        } else if($data["Field Type"] == "Phone Number") {
          return $fieldID . ":'Phone Number',";
        } else {
          return $fieldID . ":'required',";
//          $args["definition"][$fieldID] = "required";
        }
      } else if($data["Field Type"] == 'Email Address') {
        return $fieldID . ":'email',";
//        $args["definition"][$fieldID] = "email";
      } else if($data["Field Type"] == 'Phone Number') {
        return $fieldID . ":'phone',";
      }

/*else if($data["Field Type"] == 'File') {
        return $fieldID . ":'filefilter=jpg,jpeg',";
      }
*/
    }
  }
}

function wtFormFieldCallback($data, $args = Array()) 
{

  if(array_key_exists("hide", $args) && is_array($args["hide"])) {
    if(in_array($data["Label"], $args["hide"]) || in_array($data["__guid"], $args["hide"])) {
      return;
    }
  }
  $form = $args["form"];
  $fieldID = "Field" . $data["__guid"];
  $defaultValue = WTTemplate::compileAndEvaluate($data["Default Value"], Array());
  $settings = Array();
  parse_str($data["Settings"], $settings);
  if(get_magic_quotes_gpc()) {
    $settings = array_map("stripslashes", $settings);
  }
  $class = "";
  if(array_key_exists("class", $settings)) {
    $class = 'class="' . $settings["class"] . '"';
  }
  $style = "";
  if(array_key_exists("style", $settings)) {
    $style = ' style="' . $settings["style"] . '"';
  }



  if($data["Field Type"] == "Date" && array_key_exists("values", $args)) {


      $year = $args["values"][$fieldID . "Year"];
      $month = $args["values"][$fieldID . "Month"];
      $day = $args["values"][$fieldID . "Day"];

      if($year || $month || $day) {
        $args["values"][$fieldID] = $year . "-" . sprintf("%02d", $month) . "-" . sprintf("%02d", $day);
      }
  }

  if($data["Field Type"] == "Checkboxes" && array_key_exists("values", $args)) {
//    $args["values"][$fieldID] = "";
    if(strpos($data["Data"], "\n") !== false) {
      $options = array_map("trim", explode("\n", $data["Data"]));
    } else {
      $options = array_map("trim", explode(",", $data["Data"]));
    }


    $checkboxValue = "";
    for($i = 1; $i <= count($options); $i++) {
      if($args["values"][$fieldID . "_$i"] != "") {
        if($checkboxValue != "") {
          $checkboxValue .= ",";
        }
        $checkboxValue .= $args["values"][$fieldID . "_$i"];
      }
    }

    if($checkboxValue != "") {
      $args["values"][$fieldID] = $checkboxValue;
    }
/*
    if(array_key_exists("type", $settings) && $settings["type"] == "single" && $value == "") {
      $value = "No";
    }
*/

  }
 

  if(array_key_exists($fieldID, $args["values"])) {
    $value = $args["values"][$fieldID];

  } else if(array_key_exists("remember", $args) && array_key_exists("WTFORM$fieldID", $_SESSION)) {


    $value = $_SESSION["WTFORM$fieldID"];
  } else { 


    $value = $GLOBALS["WT"]->getRequestValue($fieldID, $defaultValue);
    if(array_key_exists("remember", $settings) && $settings["remember"] == "no") {
      $value = "";
    }
  }


  $html = '';

  if($data["Field Type"] != "Hidden" && $data["Field Type"] != "Fieldset" && $data["Field Type"] != "Fieldset close") {
    $accesskey = "";
    if($data["Access Key"] != '') {
      $accesskey = ' accesskey="' . $data["Access Key"] . '"';
    }

    $html .= '<div class="formrow" id="row' . $data["__guid"] . '">';

    if(($data["Field Type"] != 'Static' || $data["Label"] != "")  && !array_key_exists("nolabels", $args)) {
      $html .= '<label for="' . $fieldID . '" id="' . $fieldID . 'Label" class="fieldlabel" ' . $accesskey . '><span class="labelwrapper">';
      if($data["Field Type"] == "Checkboxes" && array_key_exists("type", $settings) && $settings["type"] == "single" && !array_key_exists("static", $args)) {
        $label .= "&nbsp;";
        if(array_key_exists("errorlabel", $settings)) {
          $label .= '<span style="display: none" id="' . $fieldID . 'ErrorLabel">' . $settings["errorlabel"] . '</span>';
        }
      } else {
        if($GLOBALS["WTLANGUAGEID"] != 0 && WTConfig::get("Multilingual") == "Yes") {
          $label .= $GLOBALS["WT"]->getTextTranslation($data["Label"], $GLOBALS["WTLANGUAGEID"]);
        } else {
          $label .= $data["Label"];
        }
      }
      if($data["Required ID"] == 1) {
        if(!array_key_exists("static", $args)) {
          $form->m_hasRequiredFields = true;
          $label .= '<span class="required">*</span>'; 
        }
        if($data["Field Type"] == "Phone Number") {
          $args["definition"][$fieldID] = "requiredphone";
        } else if($data["Field Type"] == "Email Address") {
          $args["definition"][$fieldID] = "requiredemail";
        } else {
          $args["definition"][$fieldID] = "required";
        }
      } else if($data["Field Type"] == 'Email Address') {
        $args["definition"][$fieldID] = "email";
      } else if($data["Field Type"] == 'Phone Number') {
        $args["definition"][$fieldID] = "phone";
      } else if($data["Field Type"] == 'File' && array_key_exists("filter", $settings) ) {
        $args["definition"][$fieldID] = "filefilter=" . $settings["filter"];
      }

      if($data["Label"] != '' && !($data["Field Type"] == "Checkboxes" && array_key_exists("type", $settings) && $settings["type"] == "single" && !array_key_exists("static", $args))) {
        $label .= ': ';
      }
      $html .= $label;
      $html .= '</span></label>';
      
    }
  }

  if(array_key_exists("static", $args)) {
    $html .= nl2br(htmlEntities($value));
  } else {

    if(array_key_exists("control", $settings)) {
      $info = Array("Attribute Settings" => "control=" . $settings["control"]);
      $html .= $GLOBALS["WT"]->getControlHTML($fieldID, $info, $value);

//      $html .= 'custom control' . $settings["control"];
    } else { 
    switch($data["Field Type"]) {
      case 'Fieldset close':
        $html .= '</fieldset>';
        $GLOBALS["WTOPENFIELDSETS"]--;
        break;
      case 'Fieldset':
        if($GLOBALS["WTOPENFIELDSETS"] > 0) {
          $html .= '</fieldset>';
          $GLOBALS["WTOPENFIELDSETS"]--;
        }
        $GLOBALS["WTOPENFIELDSETS"]++;

        
        $label = $data["Label"];
        if(WTConfig::get("Multilingual") == "Yes") {
          $label = wtTranslation(Array("text" => $label, "returntext" => "yes", "ignoredirection" => "yes"));
        }

        $html .= '<fieldset';
        if(array_key_exists("id", $settings)) {
          $html .= ' id="' . $settings["id"] . '"';
        } else {
          $html .= ' id="row' . $data["__guid"] . '"';
        }
        $html .= '>';
        $html .= '<legend><span>' . htmlspecialchars($label) . '</span></legend>';
        break;
      case 'Static':
        $value = WTTemplate::compileAndEvaluate($data["Data"], Array());
        if(WTConfig::get("Multilingual") == "Yes") {
          $value = wtTranslation(Array("text" => $value, "returntext" => "yes"));
        }


        $html .= '<p class="staticfield">' . $value . '</p>';
        break;
      case 'Hidden':
        $html .= '<input type="hidden" name="' . $fieldID . '" id="' . $fieldID . '" value="' . htmlEntities($value) . '">';
        break;
      case 'Single Line Text':
      case 'Email Address':
      case 'Phone Number':
        if($class == "") {
          $class = 'class="textinput"';
        }

        if(array_key_exists("fieldprefix", $settings)) {
          $html .= $settings["fieldprefix"];
        }

        $html .= '<input ';

        if(array_key_exists("type", $settings)) {
          switch($settings["type"]) {
            case 'phone':
              $html .= 'onkeypress="return wtCheckKeys(event, \'0123456789 .\\+\\-\\(\\)\')" size="5"';
              break;
            case 'number':
              $html .= 'onkeypress="return wtCheckKeys(event, \'0123456789\')" size="5"';
              break;
            case 'money':
              $html .= 'onkeypress="return wtCheckKeys(event, \'0123456789.\')" size="5"';
              break;
            case 'nocheckpassword':
              $html .= ' type="password" ';
            case 'password':
              $html .= ' type="password" ';
              $html .= ' onblur="wtCheckMemberField(\'password\', \'' . $fieldID . '\')" ';
              break;              
            case 'passwordconfirm':
              $confirm = $settings["confirm"];
              $passwordfield = $GLOBALS["WT"]->getNode($form->m_guid . "/Fields/$confirm"); 
              $confirmID = '';
              if($passwordfield) {
                $confirmID = 'Field' . $passwordfield->m_guid;
              }
              $html .= ' type="password" ';
              $html .= ' onblur="wtCheckPasswordConfirm(\'' . $fieldID . '\', \'' . $confirmID . '\')" ';
              break;
            case 'emailconfirm':
              $confirm = $settings["confirm"];
              $emailfield = $GLOBALS["WT"]->getNode($form->m_guid . "/Fields/$confirm");
              $confirmID = '';
              if($emailfield) {
                $confirmID = 'Field' . $emailfield->m_guid;
              }
              $html .= ' onblur="wtCheckEmailConfirm(\'' . $fieldID . '\', \'' . $confirmID . '\')" ';
              break;
            case 'username':
              $html .= ' onblur="wtCheckMemberField(\'username\', \'' . $fieldID . '\')" ';
              break;
            case 'memberemail':
              $html .= ' onblur="wtCheckMemberField(\'email\', \'' . $fieldID . '\')" ';
              break;
            case 'readonly':
              $html .= ' type="hidden" ';
          }
        }
       

        $html .= 'name="' . $fieldID . '" id="' . $fieldID . '" value="' . htmlspecialchars($value) . '" ' . $class . $style . '/>';

        if(array_key_exists("fieldpostfix", $settings)) {
          $html .= $settings["fieldpostfix"];
        }

        if(array_key_exists("type", $settings) && $settings["type"] == "readonly") {
          $html .= '<span class="readonlyfield">' . htmlspecialchars($value) . '</span>';
        }

	
        if(array_key_exists("type", $settings) && ($settings["type"] == "username" || $settings["type"] == "memberemail" || $settings["type"] == "password" || $settings["type"] == "passwordconfirm" || $settings["type"] == "emailconfirm")) {
          $note = "";
          if(isset($GLOBALS["WTFORMERROR"]) && $GLOBALS["WTFORMERROR"]) {
            switch($settings["type"]) {
              case 'password':
              case 'username':
                $note = WTMembership::checkMemberField($settings["type"], $value);
                break;
              case 'memberemail':
                $note = WTMembership::checkMemberField('email', $value);
                break;
              case 'emailconfirm':
                $confirmValue = "";
                $confirm = $settings["confirm"];
                $emailfield = $GLOBALS["WT"]->getNode($form->m_guid . "/Fields/$confirm");
                $confirmID = '';
                if($emailfield) {
                  $confirmID = 'Field' . $emailfield->m_guid;
                  $confirmValue = $GLOBALS["WT"]->getRequestValue($confirmID);
                }
                if($confirmValue == $value) {
                  $note = WTMembership::checkMemberField('emailconfirm', 'ok');
                } else {
                  $note = WTMembership::checkMemberField('emailconfirm', 'notok');
                }
                break;
              case 'passwordconfirm':
                $confirmValue = "";
                $confirm = $settings["confirm"];
                $passwordfield = $GLOBALS["WT"]->getNode($form->m_guid . "/Fields/$confirm");
                $confirmID = '';
                if($passwordfield) {
         
                  $confirmID = 'Field' . $passwordfield->m_guid;
                  $confirmValue = $GLOBALS["WT"]->getRequestValue($confirmID);
                }
                if($confirmValue == $value) {
                  $note = WTMembership::checkMemberField('passwordconfirm', 'ok');
                } else {
                  $note = WTMembership::checkMemberField('passwordconfirm', 'notok');
                }

                break;
            }
          }
          $html .= '<div class="formnote" id="' . $fieldID . 'note">' . $note . '</div>';
          
        }
        if(array_key_exists("Note", $data) && trim($data["Note"]) != "") {
          $note = WTTemplate::compileAndEvaluate($data["Note"], Array());
          $html .= '<div class="formnote" id="' . $fieldID . 'note">' . $note . '</div>';
        }
        break;
      case 'Multi Line Text':
        if($class == "") {
          $class = 'class="textareainput"';
        }
        $html .= '<textarea name="' . $fieldID . '" id="' . $fieldID . '" ' . $class . $style . '>' . htmlEntities($value) . '</textarea>';
        break;
      case 'Drop Down List':      
        if($class == "") {
          $class = 'class="selectinput"';
        }
        if(array_key_exists("options", $settings)) {

          $optionQuery = Array();
          if(array_key_exists("optionCriteria", $settings)) {
            $optionQuery["Criteria"] = $settings["optionCriteria"];
          }
          if(array_key_exists("optionType", $settings)) {
            $optionQuery["Node Type"] = $settings["optionType"];
          }
          if(array_key_exists("optionOrderBy", $settings)) {
            $optionQuery["Order By"] = $settings["optionOrderBy"];
          }



          $options = $GLOBALS["WT"]->getOptions($settings["options"], $optionQuery);
        } else {
          if(strpos($data["Data"], "\n") !== false) {
            $options = array_map("trim", explode("\n", $data["Data"]));
          } else {
            $options = array_map("trim", explode(",", $data["Data"]));
          }
        }
  //      $options = array_map("trim", $options);
        $html .= '<select name="' . $fieldID . '" id="' . $fieldID . '" ';
        $html .= ' onchange="wtOptionChanged(\'' . $fieldID . '\')" ';

//        $html .= ' style="font-family:Arial Unicode MS" ';
 
        $html.= $class . $style . '>';
        if($value == "") {
          $pleaseChoose = "Please Choose";
          if(WTConfig::get("Multilingual") == "Yes") {
            $pleaseChoose = wtTranslation(Array("text" => $pleaseChoose, "returntext" => "yes", "ignoredirection" => "yes"));
          }

          $html .= '<option value="">' . $pleaseChoose . '</option>';
        }
        //switch between value/label pairs or standard options
        if ( !preg_match('`[^&]+&[^=]+=`',$options[0]) ) {
          foreach($options as $option) {
            if($option != "") {
              $selected = '';
              if($value == $option) {
                $selected = 'selected="selected"';
              }
              if(WTConfig::get("Multilingual") == "Yes") {
                $option = wtTranslation(Array("text" => $option, "returntext" => "yes", "ignoredirection" => "yes"));
              }

              $html .= '<option value="' . htmlEntities($option) . '" ' . $selected . '>' . htmlspecialchars($option) . '</option>';
            }
          }
        }
        else {
          foreach($options as $option) {
            if($option != "") {
              parse_str($option,$option);
              $selected = '';
              if($value == $option['value']) {
                $selected = 'selected="selected"';
              }
              $label = $option['label'];
              if(WTConfig::get("Multilingual") == "Yes") {
                $label = wtTranslation(Array("text" => $label, "returntext" => "yes"));
              }

              $html .= '<option value="' . htmlEntities($option['value']) . '" ' . $selected . '>' . htmlspecialchars($label) . '</option>';
            }
          }
        }
        $html .= '</select>';

        if(array_key_exists("fieldpostfix", $settings)) {
          $html .= $settings["fieldpostfix"];
        }



        if($GLOBALS["WT"]->getMode() == "edit") {
          $html .= "&nbsp;" . WTForm::getEditOptionsButtonHTML($data["__guid"]);
        }

        break;
      case 'Radio Buttons':
        if(array_key_exists("options", $settings)) {

          $optionQuery = Array();
          if(array_key_exists("optionCriteria", $settings)) {
            $optionQuery["Criteria"] = $settings["optionCriteria"];
          }
          if(array_key_exists("optionType", $settings)) {
            $optionQuery["Node Type"] = $settings["optionType"];
          }
          if(array_key_exists("optionOrderBy", $settings)) {
            $optionQuery["Order By"] = $settings["optionOrderBy"];
          }

          $options = $GLOBALS["WT"]->getOptions($settings["options"], $optionQuery);
        } else {
          if(strpos($data["Data"], "\n") !== false) {
            $options = array_map("trim", explode("\n", $data["Data"]));
          } else {
            $options = array_map("trim", explode(",", $data["Data"]));
          }
        }
        $count = 0;
        if($class == "") {
          $class = 'class="radioinput"';
        }
        $html .= '<fieldset class="radiobuttonfieldset">';
        foreach($options as $id => $option) {
          if($option != "") {
            $label = $option;
             if(array_key_exists("label", $settings)) {
              $node = $GLOBALS["WT"]->getNode($id);
              if($node) {
                $label = WTTemplate::compileAndEvaluate($settings["label"], $node->getAttributes());
              }
            }


            if(WTConfig::get("Multilingual") == "Yes") {
              $label = wtTranslation(Array("text" => $label, "returntext" => "yes"));
            }

            $count++;
            $id = $fieldID . "_" . $count;
            $checked = '';
            if($value == $option) {
              $checked = 'checked="checked"';
            }
            $html .= '<span id="' . $id . '_radio">';
            $html .= '<input type="radio" name="' . $fieldID . '" value="' . htmlEntities($option) . '" id="' . $id . '" ';
            $html .= ' onclick="wtOptionChanged(\'' . $fieldID . '\')" ';
            $html .= $checked . ' ' . $class . $style . '/><label for="' . $id . '">' . $label . '</label>';
            $html .= '</span><br/>';
          }
        }

        if($GLOBALS["WT"]->getMode() == "edit") {
          $html .= WTForm::getEditOptionsButtonHTML($data["__guid"]);
        }

        $html .= '</fieldset>';
      
        break;
      case 'Checkboxes':
        $type = "";
        if(array_key_exists("type", $settings)) {
          $type = $settings["type"];
        }
        if(array_key_exists("options", $settings)) {

          $optionQuery = Array();
          if(array_key_exists("optionCriteria", $settings)) {
            $optionQuery["Criteria"] = $settings["optionCriteria"];
          }
          if(array_key_exists("optionType", $settings)) {
            $optionQuery["Node Type"] = $settings["optionType"];
          }
          if(array_key_exists("optionOrderBy", $settings)) {
            $optionQuery["Order By"] = $settings["optionOrderBy"];
          }

          $options = $GLOBALS["WT"]->getOptions($settings["options"], $optionQuery);
        } else {
          if(strpos($data["Data"], "\n") !== false) {
            $options = array_map("trim", explode("\n", $data["Data"]));
          } else {
            $options = array_map("trim", explode(",", $data["Data"]));
          }

//          $options = array_map("trim", explode(",", $data["Data"]));
        }

        $values = array_map("trim", explode(",", $value));
        $count = 0;
        if($class == "") {
          $class = 'class="checkboxinput"';
        }

        if($type == "") {
          $html .= '<fieldset class="checkboxfieldset">';
        }

        if(array_key_exists("Note", $data)) {
          $html .= '<div class="formnote" id="' . $fieldID . 'note">' . $data["Note"] . '</div>';
        }

        foreach($options as $id => $option) {
          
          if($option != "") {
            $label = $option;
            if($type == "single") {
              $label = $data["Label"];
            }
            if(array_key_exists("label", $settings)) {
              $node = $GLOBALS["WT"]->getNode($id);
              if($node) {
                $label = WTTemplate::compileAndEvaluate($settings["label"], $node->getAttributes());
              }
            }
            $count++;

            if(array_key_exists("optionUseIDs", $settings)) {
              $option = $id;
            }
            $id = $fieldID . "_" . $count;

            $checked = '';
            if(in_array($option, $values)) {
              $checked = 'checked="checked"';
            }

            if(WTConfig::get("Multilingual") == "Yes") {
              $label = wtTranslation(Array("text" => $label, "returntext" => "yes"));
            }

            $html .= '<span id="' . $id . '_checkbox">';
            $html .= '<input type="checkbox" value="' . htmlEntities($option) . '" name="' . $id . '" id="' . $id . '" ';
            $html .= ' onclick="wtOptionChanged(\'' . $fieldID . '\')" ';
            $html .= $checked . ' ' . $class . $style . '/><label for="' . $id . '">' . $label . '</label>';
            $html .= '</span><br/>';
          }
        }

        if($GLOBALS["WT"]->getMode() == "edit") {
          $html .= WTForm::getEditOptionsButtonHTML($data["__guid"]);
        }

        if($type == "") {
          $html .= '</fieldset>';
        }
        break;
      case 'Countries':

        $exclude = Array();
        if(array_key_exists("exclude", $settings)) {
          $exclude = explode(",", $settings["exclude"]);

        }

        if($class == "") {
          $class = 'class="selectinput"';
        }
        $html .= '<select name="' . $fieldID . '" id="' . $fieldID . '" ';
        $html .= ' onchange="wtOptionChanged(\'' . $fieldID . '\')" ';
        $html .= $class . $style . '>';
        $query = mysql_query("SELECT * FROM dbCountries.tblCountry ORDER BY countryName");
        if($value == "") {
          $pleaseChoose = "Please Choose";
          if(WTConfig::get("Multilingual") == "Yes") {
            $pleaseChoose = wtTranslation(Array("text" => $pleaseChoose, "returntext" => "yes"));
          }

          $html .= '<option value="">' . $pleaseChoose . '</option>';
        }
        while($row = mysql_fetch_array($query)) {
          if(in_array(trim($row["countryName"]), $exclude)) {
            continue; 
          }
          $selected = '';
          if($value == $row["countryName"]) {
            $selected = 'selected="selected"';
          }

          $html .= '<option value="' . htmlEntities($row["countryName"]) . '" ' . $selected . '>' . htmlEntities($row["countryName"]) . '</option>';
        }
        $html .= '</select>';

        if(array_key_exists("Note", $data) && trim($data["Note"]) != "") {
          $note = WTTemplate::compileAndEvaluate($data["Note"], Array());
          $html .= '<div class="formnote" id="' . $fieldID . 'note">' . $note . '</div>';
        }

        break;
      case 'Australian States':
      
        if($class == "") {
          $class = 'class="selectinput"';
        }
 
        $html .= '<select name="' . $fieldID . '" ' . $class . ' id="' . $fieldID . '" ' . $class . $style . '>';
        $states = Array("Australian Capital Territory", "New South Wales", "Northern Territory", "Queensland", "South Australia", "Tasmania", "Victoria", "Western Australia");
        $pleaseChoose = "Please Choose";
        if(WTConfig::get("Multilingual") == "Yes") {
          $pleaseChoose = wtTranslation(Array("text" => $pleaseChoose, "returntext" => "yes"));
        }

        $html .= '<option value="">' . $pleaseChoose . '</option>';
        foreach($states as $state) {
          $html .= '<option value="' . $state . '"';
          if($value == $state) {
            $html .= ' selected="selected" ';
          }
          $html .= '>' . $state . '</option>';
        }
        $html .= '</select>';
        break;
      case 'Countries/States':
        break;
      case 'Country':
        break;
      case 'Email Address':
        break;
      case 'File':
        $fieldset = false;
        if($value) {
          if(array_key_exists("type", $settings) && $settings["type"] == "image") {
            $file = $GLOBALS["WT"]->getNode($value);
            if($file) {
              $html .= '<fieldset class="imagefieldset">';
              $fieldset = true;
              $filename = $file->getFilename(Array("width" => 80, "height" => 80));
              $html .= '<div id="' . $fieldID . 'Image">';
              $html .= '<img src="files/' . $filename . '">';
              $html .= '<input type="button" value="Clear Image" onclick="wtClearFormImage(\'' . $fieldID . '\')"/>';
              $html .= '</div>';
            }
          }
          if(strpos($value, "http://") !== false) {
            $html .= $value . "&nbsp;";
          }
          $html .= '<input type="hidden" name="' .  $fieldID . 'value" id="' . $fieldID . 'value" value="' . htmlspecialchars($value) . '"/>';
        }
        $html .= '<input type="file" class="fileinput" name="' . $fieldID . '" id="' . $fieldID . '"/>';
 
 
        if(array_key_exists("Note", $data)) {
          $html .= $data["Note"];
        }
        if($fieldset) {
          $html .= '</fieldset>';
        }
        break;
      case 'Date':
        if(array_key_exists("type", $settings) && $settings["type"] == "ccexpiry") {
          $html .= '<label for="' . $fieldID . 'Month">Month</label>:';
          $html .= '<select  name="' . $fieldID . 'Month" id="' . $fieldID . 'Month">';
          for($i = 1; $i < 13; $i++) {
            $html .= '<option value="' . sprintf("%02d", $i) . '">' . sprintf("%02d", $i) . '</option>';
          } 
          $html .= '</select>';
          $html .= '&nbsp;&nbsp;<label for="' . $fieldID . 'Year">Year</label>:';
          $html .= '<select name="' . $fieldID . 'Year" id="' . $fieldID . 'Year">';
          for($i = (int)date("y"); $i < (int)date("y") + 10; $i++) {
            $html .= '<option  value="' . sprintf("%02d", $i) . '">' . sprintf("%02d", $i) . '</option>';
          } 
          $html .= '</select>';

        } else {
          $attributeSettings = "";
          if(array_key_exists("year", $settings) && $settings["year"] == "dropdown") {
            $attributeSettings = "year=dropdown";
          }
          if(array_key_exists("mindate", $settings)) {
            if($attributeSettings) {
              $attributeSettings .= "&";
            }
            $attributeSettings .= "mindate=" . $settings["mindate"];
          }
          if(array_key_exists("maxdate", $settings)) {
            if($attributeSettings) {
              $attributeSettings .= "&";
            }
            $attributeSettings .= "maxdate=" . $settings["maxdate"];
          }

          $html .= WTControl::getControlHTML($fieldID, Array("Attribute Type" => "Date", "Attribute Settings" => $attributeSettings), $value);
        }
        break;
    } 
    }
  }


  if($data["Field Type"] != "Hidden" && $data["Field Type"] != "Fieldset" && $data["Field Type"] != "Fieldset close") {
    $html .= '</div>' . "\n";
//   $html .= '<br/>';
//    $html .= '</td>';
//    $html .= '</tr>';
  }


  if($data["Visible Condition"] != "") {
    $condition = $data["Visible Condition"];
    $conditionLength = strlen($condition);
    $conditionStr = "";
    $i = 0;
    while($i < $conditionLength) {
      if($i + 3 < $conditionLength
         && $condition[$i] == '['
         && $condition[$i + 1] == 'w'
         && $condition[$i + 2] == 't'
         && $condition[$i + 3] == ':') {
        $i += 4;
        $attribute = "";
        while($i < $conditionLength && $condition[$i] != ']') {
          $attribute .= $condition[$i];
          $i++;
        }

        if(is_numeric($attribute)) {
          $attributeNode = $GLOBALS["WT"]->getNode($attribute);
        } else {
          $attributeNode = $GLOBALS["WT"]->getNode($form->m_guid . "/Fields/$attribute");
        }
        if($attributeNode) {
          $attribute = "Field" . $attributeNode->m_guid;
          $conditionStr .= "wtFormValue('$attribute')";

          if(!in_array($attribute, $GLOBALS["WTCHECKEDFIELDS"])) {
            $GLOBALS["WTFORMCONDITIONJS"] .= "g_fieldDependencies['$attribute'] = new Array()\n";
            $GLOBALS["WTCHECKEDFIELDS"][] = $attribute;
          }
          $GLOBALS["WTFORMCONDITIONJS"] .= "g_fieldDependencies['$attribute'][g_fieldDependencies['$attribute'].length] = '{$fieldID}';\n";
        }

      } else {
        $conditionStr .= $condition[$i];
      }
      $i++;
    }
    $GLOBALS["WTFORMCONDITIONJS"] .= "g_fieldConditions['{$fieldID}'] = '" . str_replace("'", "\\'", $conditionStr) . "';\n";
  }




  return $html;
}


/**
 *  The class representing wtForm Nodes
 *
 *  @class WTForm
 *  @extends WTNode
 */
class WTForm extends WTNode 
{
  var $m_hasRequiredFields;
  var $m_data = NULL;



  /**
   *  Return the HTML for the button to edit the options for a control in a form
   *
   *  @method getEditOptionsButtonHTML
   *  @static
   *  @private
   *  @param {int} guid The guid of the field
   *  @return {String} The HTML for the edit button
   *
   */
  static function getEditOptionsButtonHTML($guid) {
    $html = '';
      if($GLOBALS["WT"]->getMode() == "edit") {
        $args = Array();
        $args["guid"] = $guid;
        $args["noteditable"] = "Label,Store In,Settings,Access Key,Required,Field Type,Default Value";
        $args["forceeditable"] = "Data";
        $args["label"] = "Edit Options";
        $html = $GLOBALS["WT"]->getButtonHTML("edit", $args);
      }
    return $html;
  }


  /**
   *  Register a function to do custom processing on a form
   *
   *  @method registerFormHandler
   *  @static
   *  @param {String} action The form action the custom function will respond to
   *  @param {Function} function The custom form processing function
   */
  static function registerFormHandler($action, $function) 
  {
    $GLOBALS["WTFORMHANDLERS"][$action] = $function;
  }

  /**
   *  Return the request data from a form submission as an associative array
   *
   *  @method requestData
   *  @param {boolean} useLabels If true, then return the data with the form labels as keys
   *  @return {Array} The form data as an associative array
   */
  function requestData($useLabels = true) 
  {
    $data = Array();

    $results = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;

    $GLOBALS["WT"]->query($q);
    foreach($results as $field) {
      $settings = Array();
      parse_str($field["Settings"], $settings);
      if(get_magic_quotes_gpc()) {
        $settings = array_map("stripslashes", $settings);
      }

      $fieldID = "Field" . $field["__guid"];

      $value = $GLOBALS["WT"]->getRequestValue($fieldID);

      if($field["Field Type"] == "Date") {
        $year = $GLOBALS["WT"]->getRequestValue($fieldID . "Year");
        $month = $GLOBALS["WT"]->getRequestValue($fieldID . "Month");
        $day = $GLOBALS["WT"]->getRequestValue($fieldID . "Day");
        $value = $year . "-" . sprintf("%02d", $month) . "-" . sprintf("%02d", $day);
      } else if($field["Field Type"] == "Checkboxes") {
        $value = "";
        if(strpos($data["Data"], "\n") !== false) {
          $options = array_map("trim", explode("\n", $field["Data"]));
        } else {
          $options = array_map("trim", explode(",", $field["Data"]));
        }

//        $options = array_map("trim", explode(",", $field["Data"]));
        $this->m_data[$label] = "";
        for($i = 1; $i <= count($options); $i++) {
          if($GLOBALS["WT"]->getRequestValue($fieldID . "_$i") != "") {
            if($value != "") {
              $value .= ",";
            }
            $value .= $GLOBALS["WT"]->getRequestValue($fieldID . "_$i");
          }
        }
        if(array_key_exists("type", $settings) && $settings["type"] == "single" && $value == "") {
          $value = "No";
        }
      }

    

      if($useLabels) {
        $data[$field["Label"]] = $value;
      } else {
        $data[$fieldID] = $value;
      }
    }

    return $data;
  }


  /**
   *  Verify a form submission, check the reverse captcha, the format of data
   *
   *  @method verify
   *  @param {Array} data The data to verify
   *  @return {boolean} Returns true if the data passes verification
   */
  function verify($data) 
  {

    if($GLOBALS["WTSITEID"] != 11473) {
      if(!array_key_exists("FORM" . $this->m_guid, $_SESSION["WTFORMIDS"])) {
        return false;
      }
    }

/*
    $id = $GLOBALS["WT"]->getRequestValue("id");
    if($id != $_SESSION["WTFORMIDS"]["FORM" . $this->m_guid]) {
      print "Incorrect form id";
      return false;
    }
*/
    $captcha = $GLOBALS["WT"]->getRequestValue("email");

    if($captcha != "") {
//      print "possible spam";
      return false;
    }

    $results = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);

    $data = Array();
    foreach($results as $field) {
      $fieldID = "Field" . $field["__guid"];
      $_SESSION["WTFORM$fieldID"] = $GLOBALS["WT"]->getRequestValue($fieldID);
      $data[$fieldID] = $GLOBALS["WT"]->getRequestValue($fieldID);

      // validate the email address
      if($field["Field Type"] == "Email Address" && $data[$fieldID] != "") {
        if(!WTForm::checkEmail($data[$fieldID])) {
          // not a valid email address, possible spam
          return false;
        } 
      }

      // check for return characters in single lines
      if($field["Field Type"] == "Single Line Text" && $data[$fieldID] != "") {
        if(strpos($data[$fieldID], "\n") !== false) {
          // possible spam
          return false;
        }
      }

      if(strpos($data[$fieldID], '[/url]') !== false) {
        // possible spam
        return false;
      }
    }

    // TODO: check required fields


    return true;
  }

  function getFieldName($name) 
  {
    $fieldNode = $GLOBALS["WT"]->getNode($this->m_guid . "/Fields/$name");
    return "Field" . $fieldNode->m_guid;
  }

  function setData($data) 
  {
    $this->m_data = Array();

    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);

    foreach($results as $field) {
      if($field["Field Type"] != "Static" && $field["Field Type"] != "Fieldset" && $field["Field Type"] != "Fieldset close") {
        $fieldID = "Field" . $field["__guid"];
        $label = $field["Label"];

        if($field["Field Type"] == "Checkboxes") {
          if(strpos($data["Data"], "\n") !== false) {
            $options = array_map("trim", explode("\n", $field["Data"]));
          } else {
            $options = array_map("trim", explode(",", $field["Data"]));
          }

//          $options = array_map("trim", explode(",", $field["Data"]));
          $this->m_data[$label] = "";
          for($i = 1; $i <= count($options); $i++) {
            $value = $data[$fieldID . "_$i"];
            if($value != "") {
              if($this->m_data[$label] != "") {
                $this->m_data[$label] .= ",";
              }
              $this->m_data[$label] .= $value;
            }
          }
        } else {
          $this->m_data[$label] = $data[$fieldID];
        }
      }
    }

  }

  function getValue($name) 
  {
    if(!$this->m_data) {
      return false;
    }
    return $this->m_data[$name];

/*
    $results = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Criteria"] = "Label = '" . mysql_escape_string($name) . "'";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);


    if(count($results) > 0) {
      $result = $results[0];
      $fieldID = "Field" . $result["__guid"];
print "field = $fieldID<BR>";
      return $this->m_data[$fieldID];

    }
*/

  }

  /**
   *  Get the form data from a form submission as an associative array
   *
   *  @method getFormDataFromRequest
   *  @param {boolean} [useLabelsAsKeys=false] If true, use the form's labels as keys
   *  @return {Array} The data from the request
   */
  function getFormDataFromRequest($useLabelsAsKeys = false)
  {
    $data = Array();

    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);
    foreach($results as $field) {
      $fieldID = "Field" . $field["__guid"];
      $fieldType = $field["Field Type"];

      $settings = Array();
      parse_str($field["Settings"], $settings);
      if(get_magic_quotes_gpc()) {
        $settings = array_map("stripslashes", $settings);
      }

      $key = $fieldID;
      if($useLabelsAsKeys) {
        $key = $field["Label"];
      }

      if(array_key_exists("control", $settings)) {
        $info = Array("Attribute Settings" => "control=" . $settings["control"] );
        $data[$key] = $GLOBALS["WT"]->getControlFormValue($fieldID, $info, $_REQUEST);
      } else {
        if($fieldType == "Date") {
          $year = $GLOBALS["WT"]->getRequestValue($fieldID . "Year");
          $month = $GLOBALS["WT"]->getRequestValue($fieldID . "Month");
          $day = $GLOBALS["WT"]->getRequestValue($fieldID . "Day");
          $data[$key] = $year . "-" . sprintf("%02d", $month) . "-" . sprintf("%02d", $day);
        } else if($fieldType == "Checkboxes") {

          if(strpos($field["Data"], "\n") !== false) {
            $options = array_map("trim", explode("\n", $field["Data"]));
          } else {
            $options = array_map("trim", explode(",", $field["Data"]));
          }
          for($i = 1; $i <= count($options); $i++) {
            if($GLOBALS["WT"]->getRequestValue($fieldID . "_$i") != "") {
              if($data[$key] != "") {
                $data[$key] .= ",";
              }
              $data[$key] .= $GLOBALS["WT"]->getRequestValue($fieldID . "_$i");
            }

          }

        } else {
          $data[$key] = $GLOBALS["WT"]->getRequestValue($fieldID);
        }
      }
    }
    return $data;
  }

  /**
   *  If the form has confirm field (eg confirm password), check they hold the correct value
   *
   *  @method checkConfirmFields
   *
   */
  function checkConfirmFields() {
    $results = Array();  
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);

    foreach($results as $field) {
      $settings = Array();
      parse_str($field["Settings"], $settings);
      if(get_magic_quotes_gpc()) {
        $settings = array_map("stripslashes", $settings);
      }
      if(array_key_exists("confirm", $settings)) {
        $value = $GLOBALS["WT"]->getRequestValue('Field' . $field["__guid"]); 
        $confirmValue = "";
        $confirm = $settings["confirm"];
        $confirmfield = $GLOBALS["WT"]->getNode($this->m_guid . "/Fields/$confirm");
        $confirmID = '';
        if($confirmfield) {
          $confirmID = 'Field' . $confirmfield->m_guid;
          $confirmValue = $GLOBALS["WT"]->getRequestValue($confirmID);

        }       
        if($value != $confirmValue) {
          return false;
        }
      }
      
    }
    return true;
  }

  /**
   *  If the form fields are to be stored as a contact, return the form data as Contact attributes
   *
   *  @method getContactDataFromRequest
   *  @return {Array} The form request data as an associative array of Contact Attributes
   */
  function getContactDataFromRequest($args = Array()) {
    $results = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);

    $data = Array();
    foreach($results as $field) {
      if($field["Store In"] != "") {

        $settings = Array();
        parse_str($field["Settings"], $settings);
        if(get_magic_quotes_gpc()) {
          $settings = array_map("stripslashes", $settings);
        }

        $fieldID = "Field" . $field["__guid"];
        $value = $GLOBALS["WT"]->getRequestValue($fieldID);
        if($field["Field Type"] == "Checkboxes") {    
          $ids = "";

          if(array_key_exists("options", $settings)) {
            $optionQuery = Array();
            if(array_key_exists("optionCriteria", $settings)) {
              $optionQuery["Criteria"] = $settings["optionCriteria"];
            }
            if(array_key_exists("optionType", $settings)) {
              $optionQuery["Node Type"] = $settings["optionType"];
            }


            $options = $GLOBALS["WT"]->getOptions($settings["options"], $optionQuery);
          } else {
            if(strpos($field["Data"], "\n") !== false) {
              $options = array_map("trim", explode("\n", $field["Data"]));
            } else {
              $options = array_map("trim", explode(",", $field["Data"]));
            }
          }


          for($i = 1; $i <= count($options); $i++) {

            if($GLOBALS["WT"]->getRequestValue($fieldID . "_$i") != "") {

              if($value != "") {
                $value .= ",";
                $ids .= ",";
              }
              $value .= $GLOBALS["WT"]->getRequestValue($fieldID . "_$i");


              if(array_key_exists("options", $settings)) {
                foreach($options as $id => $setting) {
                  if($GLOBALS["WT"]->getRequestValue($fieldID . "_$i") == $setting) {
                    $ids .= $id;
                    break;
                  }
                }
              }
            }            
          }


//          $data[$field["Store In"]] = $value;
          if($value == "Yes" && $ids == "") {
            $data[$field["Store In"]] = $value;
            $data[$field["Store In"] . " IDs"] = 1;
          } else {
            $data[$field["Store In"] . " IDs"] = $ids;
          }


        } else if($field["Field Type"] == "File" && array_key_exists("Add Files To Library", $args) && $args["Add Files To Library"]) {
          if(array_key_exists($fieldID, $_FILES)  && $_FILES[$fieldID]['name'] != '') {
            $contactFiles = $GLOBALS["WT"]->getNode($args["Files Path"]);


            if($contactFiles) {
              $file = $contactFiles->createChild("wtFile", Array("Field Name" => $fieldID, "Allowed Extensions" => "jpg,jpeg,gif,png,bmp,doc,docx,dot,dotx,pps,pot,pdf,txt,ps,html,htm,avi,wmv,mov,mp4,mpg", "Max Width" => 1024));
              $value = $file->m_guid;
            }
          } else if(array_key_exists($fieldID . "value", $_REQUEST)) {
            $value = $GLOBALS["WT"]->getRequestValue($fieldID . "value");
          }

        } else if($field["Field Type"] == "Date") {
          $year = $GLOBALS["WT"]->getRequestValue($fieldID . "Year");
          $month = $GLOBALS["WT"]->getRequestValue($fieldID . "Month");
          $day = $GLOBALS["WT"]->getRequestValue($fieldID . "Day");
          $value = $year . "-" . sprintf("%02d", $month) . "-" . sprintf("%02d", $day);

        }

        $data[$field["Store In"]] = $value;

      }
    }


    return $data;
  }


  /**
   *  A function to be overridden by a subclass to custom handle form submissions
   *
   *  @method processFormSubmission
   *  @param {String} action The action of the form
   *  @param {Array} data The data submitted to the form
   *  @return {boolean} Return true if the form was processed
   *
   */
  function processFormSubmission($action, $data) {
    return false;
  }


  /**
   *  Submit a data as a form submission, performs the actions specified in form builder unless they have been overrided
   *
   *  @method submit
   *  @param {Array} The data to submit
   *  @param {boolean} [ignoreFormAction=false] If true, ignore the value of the action attribute in the wt:form tag
   *  @param {String} [action] Set an action here to override the action specified in form builder
   *  @return {Mixed} Returns a non false value if the form was processed. If a node was created, returns the object for the node
   */
  function submit($data, $ignoreFormAction = false, $action = "", $userData = Array(), $args = Array()) 
  {


    $GLOBALS["WTFORMERROR"] = false;
    $processed = false;
    $formaction = "";
    $encrypt = $this->getAttribute("Encrypt");
  

    if(!$ignoreFormAction) {
      $formaction = $GLOBALS["WT"]->getRequestValue("wtFormAction");
    }

    $extensionname = $GLOBALS["WT"]->getRequestValue("wtFormExtension");
    if($extensionname) {
      $extension = $GLOBALS["WT"]->getExtension($extensionname);
      if($extension) {
        $processed = $extension->processFormSubmission($formaction, $data);
      }
    }



    
    if(!$processed && array_key_exists($formaction, $GLOBALS["WTFORMHANDLERS"] )) {
      $processed = call_user_func($GLOBALS["WTFORMHANDLERS"][$formaction], $formaction, $data);
    }

    if(!$processed) {    
      $processed = $this->processFormSubmission($formaction, $data);
    }



   
    if($processed) {
      return $processed;
    }




   
    if($action == "") { 
      $action = $this->getAttribute("Action");
    }
    $results = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);
    $actions = array_map("trim", explode(",", $action));
    
  
    $data = Array();
    $emailData = Array();




   
    $templateNode = $GLOBALS["WT"]->getNode("/Templates/Emails/Form Submission Email");
    if(!$templateNode) {
      $templateNode = $GLOBALS["WT"]->getNode("/Templates/Emails/General");
    }

    if($templateNode) {
      $content = $templateNode->evaluate($data);
    } else {

      $templatePath = $GLOBALS["WTDIRECTORY"] . "templates/emails/formsubmission.wt";
      $templateSource = WTTemplate::load($templatePath);
      $content = WTTemplate::compileAndEvaluate($templateSource, $data);
    }

    $tablestyle = 'border-collapse: collapse';
    if(isset($GLOBALS["WTVARStablestyle"])) {
      $tablestyle = $GLOBALS["WTVARStablestyle"];
    }
    $thstyle = 'text-align: left; border: 1px solid #ccc; padding: 4px; font-weight: bold';
    if(isset($GLOBALS["WTVARSthstyle"])) {
      $thstyle = $GLOBALS["WTVARSthstyle"];
    }
    $tdstyle = 'border: 1px solid #ccc; padding: 4px';
    if(isset($GLOBALS["WTVARStdstyle"])) {
      $tdstyle = $GLOBALS["WTVARStdstyle"];
    }

    $dataHtml = '<table style="' . $tablestyle . '">';
    foreach($results as $field) {
      if($field["Field Type"] != "Static" && $field["Field Type"] != "Fieldset" && $field["Field Type"] != "Fieldset close") {
        $fieldID = "Field" . $field["__guid"];
        if($field["Field Type"] == "Checkboxes") {
          if(strpos($field["Data"], "\n") !== false) {
            $options = array_map("trim", explode("\n", $field["Data"]));

          } else {
            $options = array_map("trim", explode(",", $field["Data"]));
          }

          $settings = Array();
          parse_str($field["Settings"], $settings);
          if(get_magic_quotes_gpc()) {
            $settings = array_map("stripslashes", $settings);
          }



          if(array_key_exists("options", $settings)) {

            $optionQuery = Array();
            if(array_key_exists("optionCriteria", $settings)) {
              $optionQuery["Criteria"] = $settings["optionCriteria"];
            }
            if(array_key_exists("optionType", $settings)) {
              $optionQuery["Node Type"] = $settings["optionType"];
            }
            if(array_key_exists("optionOrderBy", $settings)) {
              $optionQuery["Order By"] = $settings["optionOrderBy"];
            }

            $options = $GLOBALS["WT"]->getOptions($settings["options"], $optionQuery);
          } 


//          $options = array_map("trim", explode(",", $field["Data"]));
          $data[$fieldID] = "";
          for($i = 1; $i <= count($options); $i++) {
            $value = $GLOBALS["WT"]->getRequestValue($fieldID . "_$i");
            if($value != "") {
              if($data[$fieldID] != "") {
                $data[$fieldID] .= ",";
              }
              $data[$fieldID] .= $value;
            }
          }


        } else if($field["Field Type"] == "File") {

          if(array_key_exists($fieldID, $userData)) {
            if($userData[$fieldID]["Path"]) {
              $filepath = $userData[$fieldID]["Path"];
              $filename = $userData[$fieldID]["Name"];
              if(file_exists($filepath)) {
                $uniquename = md5(uniqid(rand(), true));

                $submissionDir = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/submissions";
                if(!file_exists($submissionDir)) {
                  mkdir($submissionDir);
                }

                while(file_exists($filePath . "/$uniquename")) {
                  $uniquename = md5(uniqid(rand(), true));
                }
                rename($filepath, $submissionDir . "/$uniquename"); 
//                $data[$fieldID] = '<a href="' . $GLOBALS["WT"]->getSiteSetting("Site URL") . 'files/submissions/' . $filename . '">' . $filename . '</a>';
                $data[$fieldID] = '<a href="' . $GLOBALS["WT"]->getSiteSetting("Site URL") . '__form/filesubmissions/' . $uniquename . '/' . $filename . '">' . $filename . '</a>';              

              }
            }
          } else {
            $filename = $_FILES[$fieldID]['name'];
            if(get_magic_quotes_gpc()) {
              $filename = stripslashes($filename);
            }
            if($filename != "") {
              $info = pathinfo($filename);
              $extension = strtolower($info["extension"]);
              if($extension == "docx" || $extension == "doc" || $extension == "txt" || $extension == "pdf" || $extension == "jpg" || $extension == "gif" || $extension == "jpeg" || $extension == "txt" || $extension == "png" ||  $extension == "avi" ||  $extension == "wmv" ||  $extension == "mov" ||  $extension == "mp4" ||  $extension == "mpg") {
                $filePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/submissions";
                if(!file_exists($filePath)) { 
                  mkdir($filePath);
                }
                $i = 0;
                $uniquename = md5(uniqid(rand(), true));

                while(file_exists($filePath . "/$uniquename")) {
                  $uniquename = md5(uniqid(rand(), true));
                }
                move_uploaded_file($_FILES[$fieldID]['tmp_name'], $filePath . "/$uniquename");
//                $data[$fieldID] = '<a href="' . $GLOBALS["WT"]->getSiteSetting("Site URL") . 'files/submissions/' . $filename . '">' . $filename . '</a>';
                $data[$fieldID] = '<a href="' . $GLOBALS["WT"]->getSiteSetting("Site URL") . '__form/filesubmissions/' . $uniquename . '/' . $filename . '">' . $filename . '</a>';
              }
            }
          }
        } elseif ( $field['Field Type'] == 'Date' ) {
          if(array_key_exists("dateformat", $args)) {
            $data[$fieldID] = date($args["dateformat"], mktime(0, 0, 0, $GLOBALS["WT"]->getRequestValue($fieldID.'Month'), $GLOBALS["WT"]->getRequestValue($fieldID.'Day'), $GLOBALS["WT"]->getRequestValue($fieldID.'Year')));

          } else {
            $data[$fieldID] = $GLOBALS["WT"]->getRequestValue($fieldID.'Day').'/'.$GLOBALS["WT"]->getRequestValue($fieldID.'Month').'/'.$GLOBALS["WT"]->getRequestValue($fieldID.'Year');     
          }
        } else {
          $data[$fieldID] = $GLOBALS["WT"]->getRequestValue($fieldID);     
        }
        $dataHtml .= '<tr>';
        $dataHtml .= '<th style="' . $thstyle . '">' . $field["Label"] . ':</th>';
        if($field["Field Type"] == "Single Line Text") {
          $dataHtml .= '<td style="' . $tdstyle . '">' . htmlspecialchars($data[$fieldID]) . '</td>';

        } else if($field["Field Type"] == "Multi Line Text") {
          $dataHtml .= '<td style="' . $tdstyle . '">' . nl2br(htmlspecialchars($data[$fieldID])) . '</td>';
        } else {
          $dataHtml .= '<td style="' . $tdstyle . '">' . $data[$fieldID] . '</td>';
        }
        $dataHtml .= '</tr>';
        $emailData[$field["Label"]] = $data[$fieldID];
      }
    }
    $dataHtml .= '</table>';





    $emailData["Form Data"] = $dataHtml;

     
    if(in_array("Email", $actions)) { 
      $emailTo = $this->getAttribute("Email To");
      $emailTo = WTTemplate::compileAndEvaluate($emailTo, $emailData);


      $emailFrom = $this->getAttribute("Email From");
      $emailFrom = WTTemplate::compileAndEvaluate($emailFrom, $emailData);
      if(!$emailFrom) {
        $emailFrom = $this->getAttribute("Name") . " Form";
      }

      $emailFromAddress = $this->getAttribute("Email From Address");
      $emailFromAddress = WTTemplate::compileAndEvaluate($emailFromAddress, $emailData);
      if(!$emailFromAddress) {
        $emailFromAddress = "bouncer@webtemplate.com.au";
      }


      $subject = $this->getAttribute("Email Subject");
      $subject = WTTemplate::compileAndEvaluate($subject, $emailData);

      $message = $this->getAttribute("Email Message");
      $message = WTTemplate::compileAndEvaluate($message, $emailData);

      $replyTo = $this->getAttribute("Reply To");
      $replyTo = trim(WTTemplate::compileAndEvaluate($replyTo, $emailData));

      $templatedata = Array();
      $templatedata["Content"] = $message;

      if($templateNode) {
        $content = $templateNode->evaluate($templatedata);
      } else {
        $content = WTTemplate::compileAndEvaluate($templateSource, $templatedata);
      }



      $wtMail = new WTMail();

      if(array_key_exists("WTEMAILFORMSUBMISSIONSTO", $GLOBALS)) {
        $emailTo = $GLOBALS["WTEMAILFORMSUBMISSIONSTO"];
      }
      $wtMail->setTo($emailTo);

      $bccTo = $this->getAttribute("BCC To");
      if($bccTo) {
        $bccTo = WTTemplate::compileAndEvaluate($bccTo, $emailData);
        $wtMail->setBCC($bccTo);
      }


      if(array_key_exists("WTCCFORMSUBMISSIONSTO", $GLOBALS)) {
        $wtMail->setCC($GLOBALS["WTCCFORMSUBMISSIONSTO"]);
      }

      if(array_key_exists("WTBCCFORMSUBMISSIONSTO", $GLOBALS)) {
        $wtMail->setBCC($GLOBALS["WTBCCFORMSUBMISSIONSTO"]);
      }


//      $wtMail->setFrom("bouncer@webtemplate.com.au", $this->getAttribute("Name") . " Form");
      $wtMail->setFrom($emailFromAddress, $emailFrom);
      if($replyTo != "") {
        $wtMail->setReplyTo($replyTo);
      }
      $wtMail->setContent($subject, $content, true);
      $wtMail->send();

      $emailReceiptTo = $this->getAttribute("Email Receipt To");
      if($emailReceiptTo) {
        $emailReceiptTo = WTTemplate::compileAndEvaluate($emailReceiptTo, $emailData);

        $receiptSubject = $this->getAttribute("Receipt Email Subject");
        $receiptSubject = WTTemplate::compileAndEvaluate($receiptSubject, $emailData);

        $receiptMessage = $this->getAttribute("Receipt Email Message");
        $receiptMessage = WTTemplate::compileAndEvaluate($receiptMessage, $emailData);

        $templatedata["Content"] = $receiptMessage;
         
        if($templateNode) {
          $templateNode->evaluate($templatedata);
        } else {
          $content = WTTemplate::compileAndEvaluate($templateSource, $templatedata);
        }

        $wtMail = new WTMail();
        $wtMail->setTo($emailReceiptTo);
        $wtMail->setFrom("bouncer@webtemplate.com.au", $this->getAttribute("Name") . " Form");
        if($replyTo != "") {
          $wtMail->setReplyTo($replyTo);
        }
        $wtMail->setContent($receiptSubject, $content, true);
        $wtMail->send();

      }
    }
     
    $submission = null; 
    if(in_array("Store", $actions)) {
      $type = "Form" . $this->m_guid;
      $submissions = $GLOBALS["WT"]->getNode($this->m_guid . "/Submissions");         

      if($encrypt == "Yes") { 
        foreach($data as $k => $v) {
          $data[$k] = $GLOBALS["WT"]->encrypt($v);
        }
      }

      $submission = $submissions->createChild($type, $data);
    }

    if(in_array("Store in...", $actions)) {
      $nodeType = $this->getAttribute("Node Type");
      $path = $this->getAttribute("Path");
      $data = Array();
      foreach($results as $field) {
        $fieldID = "Field" . $field["__guid"];
        switch($field["Field Type"]) {
          case "Date":
            $year = $GLOBALS["WT"]->getRequestValue($fieldID . "Year");
            $month = $GLOBALS["WT"]->getRequestValue($fieldID . "Month");
            $day = $GLOBALS["WT"]->getRequestValue($fieldID . "Day");
            $value = $year . "-" . sprintf("%02d", $month) . "-" . sprintf("%02d", $day);
            break;
          default:
            $value = $GLOBALS["WT"]->getRequestValue($fieldID);
            break;
        }

        $data[$field["Store In"]] = $value;
      }
      $parent = $GLOBALS["WT"]->getNode($path);
      $submission = $parent->createChild($nodeType, $data);
    }


    if(in_array("Add to Contacts", $actions)) {
      $data = Array();
      foreach($results as $field) {
        if($field["Store In"] != "") {
          $settings = Array();
          parse_str($field["Settings"], $settings);
          if(get_magic_quotes_gpc()) {
            $settings = array_map("stripslashes", $settings);
          }

          $fieldID = "Field" . $field["__guid"];

          if($field["Field Type"] == "Checkboxes") {

            if(array_key_exists("options", $settings)) {

              $optionQuery = Array();
              if(array_key_exists("optionCriteria", $settings)) {
                $optionQuery["Criteria"] = $settings["optionCriteria"];
              }
              if(array_key_exists("optionType", $settings)) {
                $optionQuery["Node Type"] = $settings["optionType"];
              }
              if(array_key_exists("optionOrderBy", $settings)) {
                $optionQuery["Order By"] = $settings["optionOrderBy"];
              }

              $options = $GLOBALS["WT"]->getOptions($settings["options"], $optionQuery);
            } else {
              if(strpos($field["Data"], "\n") !== false) {
                $options = array_map("trim", explode("\n", $field["Data"]));

              } else {
                $options = array_map("trim", explode(",", $field["Data"]));

              }
            }

//            $options = array_map("trim", explode(",", $field["Data"]));
            $data[$field["Store In"]] = "";
            for($i = 1; $i <= count($options); $i++) {
              $value = $GLOBALS["WT"]->getRequestValue($fieldID . "_$i");
              if($value != "") {
                if($field["Store In"] == "Contact Groups" && !is_numeric($value)) {
                  $group = $GLOBALS["WT"]->getNode("/Groups/$value");
                  if($group) {
                    $value = $group->m_guid;
                  }
                }
                if($data[$field["Store In"]] != "") {
                  $data[$field["Store In"]] .= ",";
                }
                $data[$field["Store In"]] .= $value;
              }
            }


          } else {

            $data[$field["Store In"]] = $GLOBALS["WT"]->getRequestValue($fieldID);
          }            
        }          
      }

      $contactNode = NULL;
      if($data["Email Address"]) {
        $q = Array("Node Type" => "Contact", "Select" => "Contact.__guid", "Criteria" => "`Email Address` = '" . trim(mysql_real_escape_string($data["Email Address"])) . "'", "Limit" => 1);
        $contactGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
        if($contactGuid) {
          $contactNode = $GLOBALS["WT"]->getNode($contactGuid);
        }

      }
      $parent = $GLOBALS["WT"]->getNode("/Contacts");

      if(!$contactNode) {
        $submission = $parent->createChild("Contact", $data);
        $contactNode = $submission;
      }

      $groupName = $this->getAttribute("Add to Group");
      if($groupName != "") {
        $group = $GLOBALS["WT"]->getNode("/Groups/$groupName");
        $GLOBALS["WT"]->linkNodes($group, $contactNode);
      }
    }

    return $submission;
  }

  /**
   *  Convert form submission data to data which uses the forms labels as keys
   *
   *  @method convertDataWithLabels
   *  @param {Array} data The Form submission data
   *  @return {Array} The data using labels as keys
   */
  function convertDataWithLabels($data) {
    $formdata = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);
    foreach($results as $field) {
      $fieldID = "Field" . $field["__guid"];
      $label = $field["Label"];
      $formdata[$fieldID] = $data[$label];
    }
    return $formdata;
  }

  function getDataWithLabels($data) {
    $formdata = Array();
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);
    foreach($results as $field) {
      $fieldID = "Field" . $field["__guid"];
      $label = $field["Label"];
      $formdata[$label] = $data[$fieldID];
    }    
    return $formdata;
  }

  /**
   *  Render a form's data as HTML
   *
   *  @method renderStatic
   *  @param {Array} data The data from the form
   *  @param {Array} args Possible keys in args: "usetable" - use a table to render the data, "style" - the style to apply to the table, "rowstyle" - the style to apply to a row, "cellstyle" - the style to apply to a cell, "hide" - a comma separated list of fields to hide
   *  @return {String} the html for the form data
   */
  function renderStatic($data, $args = Array()) 
  {
    $html = "";
    $hide = Array();
    $usetable = true;
    if(array_key_exists("usetable", $args) && $args["usetable"] == "no") {
      $usetable = false;
    }
    if(array_key_exists("hide", $args)) {
      $hide = array_map("trim", explode(",", $args["hide"]));
    }
    
    if($usetable) {
      $html = '<table ';
      if(array_key_exists("style", $args)) {
        $html .= $args["style"];
      }
      $html .= '>';
    }

    $omit = Array();
    if(array_key_exists("omit", $args)) {
      $omit = explode(",", $args["omit"]);
    }

    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);

    foreach($results as $field) {
      
      $fieldID = "Field" . $field["__guid"];
      $label = $field["Label"];

      if($field["Field Type"] == "Date") {
        if(!array_key_exists($fieldID, $data)) {
          $year = $data[$fieldID . "Year"];
          $month = $data[$fieldID . "Month"];
          $day = $data[$fieldID . "Day"];
          $data[$fieldID] = $year . "-" . sprintf("%02d", $month) . "-" . sprintf("%02d", $day);

          if(array_key_exists("dateformat", $args)) {
            $data[$fieldID] = date($args["dateformat"], strtotime($data[$fieldID]));
          }
        }
      }


      if(!in_array($label, $hide) && $field["Field Type"] != 'Fieldset close') {
        if($field["Field Type"] == 'Fieldset') {
          $html .= '<tr>';
          $html .= '<td colspan="2"><h2>';
          $html .= $label;
          $html .= '</h2></td>';
          $html .= '</tr>';
        } else {
	  if($label != "" || $data[$fieldID] != "") {
            if($usetable) {
              $html .= '<tr ';
              if(array_key_exists("rowstyle", $args)) {
                $html .= $args["rowstyle"];
              }
              $rowIDPrefix = "row";
              if(array_key_exists("rowidprefix", $args)) {
                $rowIDPrefix = $args["rowidprefix"];
              }
              $rowID = $rowIDPrefix . $field["__guid"];
              
              $html .= ' id="' . $rowID . '"';
              $html .= '>';
              $html .= '<th ';
              if(array_key_exists("headingstyle", $args)) {
                $html .= $args["headingstyle"];
              } else {
                $html .= 'style="text-align:right;padding-right: 8px"';
              }
              $html .= '>' . htmlEntities($label) . ':</th>';
              $html .= '<td ';
              if(array_key_exists("cellstyle", $args)) {
                $html .= $args["cellstyle"];
              }
              if($field["Field Type"] == "File") {
                $html .= '>' . $data[$fieldID] . '</td>';
              } else if($field["Field Type"] == "Multi Line Text") { 
                $html .= '>' . nl2br(htmlspecialchars($data[$fieldID])) . '</td>';
              } else {
                $html .= '>' . htmlspecialchars($data[$fieldID]) . '</td>';
              }
              $html .= '</tr>';

            } else {
              $html .= '<div class="formrow">';
              $html .= '<label class="fieldlabel">' . htmlEntities($label) . ':</label>';
              $html .= '<span class="readonlyfield">' . htmlspecialchars($data[$fieldID]) . '&nbsp;</span>';
              $html .= '</div>';
	    }
          }
          
        }
      }
    }

    if($usetable) {
      $html .= '</table>';
    }
    return $html;
  }
 
  function renderJS($args = Array())
  {
    $q = Array();
    $q["Path"] = $this->m_guid . "/Fields/*";
    $q["Node Type"] = "wtFormField";
    $q["form"] = $this;
    $q["values"] = $values;
    $q["Criteria"] = "`Field Type` <> 'Hidden'";
    if(array_key_exists("omit", $args)) {
      $q["Criteria"] .= " AND Label <> '" . mysql_escape_string($args["omit"]) . "'";
    }

    $js = $GLOBALS["WT"]->query($q, "wtFormJSCallback");
    $js = substr($js, 0, strlen($js) - 1);
    return $js;

  }

  /**
   *  Render a form
   *
   *  @method render
   *  @param {Array} [args] 
   *  @param {Array} [values] values to use in the form
   *  @return {String} The HTML for the form
   */

  function render($args = Array(), $values = Array()) {


    $action = $this->getAttribute("Action");
    $actions = array_map("trim", explode(",", $action));

    $templateFunction = "";
    if(array_key_exists("Template Function", $args)) {
      $templateFunction = $args["Template Function"];
    }

    $fid = $GLOBALS["WT"]->getRequestValue("fid", 0);
    if($fid != 0 && !array_key_exists("static", $args)) {
      // need to check the fid came from a valid person
      return $this->getAttribute("Thankyou Message");
      
    } else {
      $this->m_hasRequiredFields = false;
      $formDefinition = Array();

      $q = Array();
      $q["Path"] = $this->m_guid . "/Fields/*";
      $q["Node Type"] = "wtFormField";
      $q["form"] = $this;
      if(!$values) {
        $values = Array();
      }

      $q["values"] = $values;


      $q["definition"] = &$formDefinition;
      if(array_key_exists("static", $args)) {
        $q["static"] = $args["static"];
      }
      if(array_key_exists("nolabels", $args)) {
        $q["nolabels"] = $args["nolabels"];
      }
      $formID = md5(uniqid());
      $_SESSION["WTFORMIDS"]["FORM" . $this->m_guid] = $formID;
      $GLOBALS["WTOPENFIELDSETS"] = 0;
      $GLOBALS["WTFORMCONDITIONJS"] = '';
      $GLOBALS["WTCHECKEDFIELDS"] = Array();
   
     
      if(!array_key_exists("static", $args)) {
        $html .= '<input type="hidden" name="formGuid" value="' . $this->m_guid . '">';
        $html .= '<input type="hidden" name="id" value="' . $formID .  '">';
        $html .= '<label for="email" style="display:none;">Please leave this field blank</label><input style="display: none" type="text" id="email" name="email" autocomplete="off"/>';

      // render all hidden fields first
        $q["Criteria"] = "`Field Type` = 'Hidden'";
        $html .= $GLOBALS["WT"]->query($q, "wtFormFieldCallback");
      }

      if(array_key_exists("remember", $args) && $args["remember"] == "yes" && $args["remember"] = "true") {
        $q["remember"] = "yes";
      }

      // render all non hidden fields
      $q["Criteria"] = "`Field Type` <> 'Hidden'";
      if(array_key_exists("omit", $args)) {
        $q["Criteria"] .= " AND Label <> '" . mysql_escape_string($args["omit"]) . "'";
      }

      if(array_key_exists("hide", $args)) {
        $q["hide"] = explode(",", $args["hide"]);
      }


      $html .= $GLOBALS["WT"]->query($q, "wtFormFieldCallback");

      while($GLOBALS["WTOPENFIELDSETS"] > 0) {
        $html .= '</fieldset>';
        $GLOBALS["WTOPENFIELDSETS"]--;
      }

      $html .= '<div class="formrow formbuttonrow">';
      if($this->m_hasRequiredFields && !array_key_exists("required field message", $args) && $args["form"] != "no") {
        $required = "Required&nbsp;Fields";

        if(WTConfig::get("Multilingual") == "Yes") {
          $required = wtTranslation(Array("text" => "Required Fields", "returntext" => "yes"));
        }
        $html .= '<span class="requiredtextrow">';
        $html .= '<span class="required">*&nbsp;' . $required . '</span>';
        $html .= '</span>';
      }
//      $html .= '&nbsp;</td>';


      if(!array_key_exists("static", $args)) {
        if((!array_key_exists("submit", $args)) || ($args["submit"] != "" && $args["submit"] != "no") ) {

          $submittext = "Submit";
          if(array_key_exists("submittext", $args)) {
            $submittext = $args["submittext"];
          }
          if(WTConfig::get("Multilingual") == "Yes") {
            $submittext = wtTranslation(Array("text" => $submittext, "ignoredirection" => "yes", "returntext" => "yes"));
          }



          $buttonclass = "formbutton";
          if(array_key_exists("buttonclass", $args)) {
            $buttonclass = $args["buttonclass"];
          }

          $backclass = $buttonclass;
          if(array_key_exists("backclass", $args)) {
            $backclass = $args["backclass"];
          }

          $submitclass = $buttonclass;
          if(array_key_exists("submitclass", $args)) {
            $submitclass = $args["submitclass"];
          }
        
          $html .= '<span class="formbuttons">';
          if(array_key_exists("back", $args)) {
            $onback = 'history.go(-1)';
            if(array_key_exists("onback", $args)) {
              $onback = $args["onback"];
            }
            $html .= '<input type="button" class="' . $backclass . '" value="' . $args["back"] . '" onclick="' . $onback . '"/>';
            $html .= "&nbsp;&nbsp;";
          }

          $html .= '<input type="submit" value="' . $submittext . '" class="' . $submitclass . '"/>';
//          $html .= '&nbsp;&nbsp;';
          if((!array_key_exists("reset", $args)) || $args["reset"] != "no") {
            $html .= '&nbsp;&nbsp;';
            $resettext = "Reset";
            if(array_key_exists("resettext", $args)) {
              $resettext = $args["resettext"];
            }
            if(WTConfig::get("Multilingual") == "Yes") {
              $resettext = wtTranslation(Array("text" => $resettext, "ignoredirection" => "yes", "returntext" => "yes"));
            }


            $html .= '<input type="reset" class="' . $buttonclass . '" value="' . $resettext . '"/>';
          }

          if(array_key_exists("cancel", $args))  {
            $html .= '&nbsp&nbsp;';
            $oncancel = 'history.go(-1)';
            if(array_key_exists("oncancel", $args)) {
              $oncancel = $args["oncancel"];
            }
            $html .= '<input type="button" class="' . $buttonclass . '" value="' . htmlentities($args["cancel"]) . '" onclick="' . $oncancel . '"/>';
          }
          $html .= '</span>';
        } else {
        }
      }
      $html .= '</div>';

      if($templateFunction != "") {
        $data = Array("Form" => $html);
        ob_start();
        $templateFunction($data, Array());
        $html = ob_get_contents();
        ob_end_clean();
      }



      if(!array_key_exists("static", $args)) {
        if((!array_key_exists("form", $args)) || ($args["form"] !== false && $args["form"] !== "no")) {
          $jsdefinition = "";
          foreach($formDefinition as $field => $fieldCheck) {
            if($jsdefinition != "") {
              $jsdefinition .= ',';
            }
            $jsdefinition .= $field . ":'$fieldCheck'";
          }
          $jsdefinition = '{' . $jsdefinition . '}';
          $header = '<script language="javascript" src="?wtInclude=wtFormCheck.js"></script><form ';
          if(array_key_exists("id", $args)) {
            $header .= ' id="' . $args["id"] . '" ';
          }
          $header .= ' method="post" ';
          if(array_key_exists("onsubmit", $args)) {
            if($args["onsubmit"] != "") {
              $header .= ' onsubmit="' . $args["onsubmit"] . '" ';
            }
          } else {
            $header .= ' onsubmit="return wtFormCheck(this, ' . $jsdefinition . ')" ';
          }
          $header .= ' action="' . $GLOBALS["WT"]->getRequestURI() . '" enctype="multipart/form-data"><input type="hidden" name="wtCmd" value="submitform"/>';

          $header .= '<input type="hidden" name="wtSubmitted" value=""/>';
          if(array_key_exists("action", $args)) {
            $header .= '<input type="hidden" name="wtFormAction" value="' . htmlEntities($args["action"]) . '"/>';
          }
          if(array_key_exists("extension", $args)) {
            $header .= '<input type="hidden" name="wtFormExtension" value="' . htmlEntities($args["extension"]) . '"/>';
          }

            if(in_array("Email", $actions) || in_array("Store", $actions) ) {
              if($GLOBALS["WT"]->getMode() == "edit") {
//                $header .= '<input type="button" value="Edit Form Email Details"/>';
                $args = Array();
                $args["guid"] = $this->m_guid;
                $args["noteditable"] = "Name,Edit Email Address";
                $args["hidden"] = "Action";
                if(in_array("Email", $actions)) {
                  $args["forceeditable"] = "Email To";
                } else {
                  $args["noteditable"] .= ",Reply To";
                }
                $page = $GLOBALS["WT"]->getCurrentPage();
                if($page) {
                  $args["page"] = $page->m_guid;
                }
                $args["label"] = "Edit Form Details";
                $header .= $GLOBALS["WT"]->getButtonHTML("edit", $args);
              }
            }

          $html = $header . $html;
          $html .= '</form>';
          if($GLOBALS["WTFORMCONDITIONJS"] != "") {
            $html .= '<script language="javascript">' . "\n";
            $html .= 'var g_fieldDependencies = Array()' . "\n";
            $html .= 'var g_fieldConditions = Array()' . "\n";
            $html .= $GLOBALS["WTFORMCONDITIONJS"];
            $html .= 'wtSetFieldVisibility();' . "\n";
            $html .= '</script>';
          }
        }
      }
      return $html;
    }
  }

  /**
   * Validate an email address 
   * 
   *  @method checkEmail
   *  @static
   *  @param {String} email The email address
   *  @return {boolean} Returns true if the email address is valide
   */
  static function checkEmail($email) {
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
      // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
      return false;
    }

    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
      if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
        return false;
      }
    }

    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
      $domain_array = explode(".", $email_array[1]);
      if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
      }
 
      for ($i = 0; $i < sizeof($domain_array); $i++) {
        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
          return false;
        }
      }
    }
    return true;
  }


  /**
   *  Output the a file in a form submission given the URI for the file
   *
   *  @method processFormURI
   *  @param {String} path The URI identifying the file
   */
  static function processFormURI($path) {
    $pathParts = explode("/", $path);
    if(count($pathParts) == 4 && $pathParts[1] == "filesubmissions") {
      $filename = $pathParts[3];
      $extension = "";
      $pos = strrpos($filename, ".");
      if($pos !== false) {
        $extension = substr($filename, $pos + 1);
      }
      $filePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/submissions/" . $pathParts[2];
      $mimetype = WTFile::getMimeType($extension);
      if(file_exists($filePath)) {
        if($filename == "") {
          $filename = basename($filePath);
        }
        header("Content-Type: $mimetype");
        header('Content-Length: ' . filesize($filePath));
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: private');
        header('Pragma: private');

        readfile($filePath);
        exit("");
      }
    }
    exit("");
  }

}

$GLOBALS["WT"]->registerURIHandler("__form", Array("WTForm", "processFormURI"));

?>