Question

Trying to use recaptcha with formmail script from http://www.tectite.com

Asked by: sobeservices2

I am having a hell of a time trying to get recaptcha to work with my formmail script from tectite.com I've even tried others could someone help .

http://www.bcpba.org/contact.php

                                  
1:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-07 at 07:54:27ID24634901
Tags

recaptcha

,

formmail script

,

captcha

,

tectite

Topics

Scripting Languages

,

Open Source Programming

,

PHP Scripting Language

Participating Experts
2
Points
500
Comments
30

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. working with FormMail
    I have modified Matt Wright's FormMail 1.6 and need to pass to it the following input field of a form (Netscape & JavaScript1.1): <INPUT TYPE=HIDDEN NAME="print_fields" VALUE="somevalue"> VALUE will depend on whether some earlier fields in the ...
  2. Formmail CGI script
    im having difficulty setting up a form using the formmail cgi script. if you arent familiar with it check it out here [url]http://www.scriptarchive.com . currently i have web services running. we are a subdomain of a school network. all mail is handled by them at the district...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mplungjanPosted on 2009-08-07 at 10:12:31ID: 25044933

And?

varify.php shows nothing

Hard to help without seeing the actual code

 

by: sobeservices2Posted on 2009-08-07 at 10:24:04ID: 25045023

This is the contact form bcpba.org/contact.php

<form action="varify.php" method="post" class="style8" id="BCPBA Contact Us Form">
                  <p>
                    <input type="hidden" name="env_report" value="REMOTE_HOST,REMOTE_ADDR,HTTP_USER_AGENT,AUTH_TYPE,REMOTE_USER" />
                    <!-- STEP 2: Put your email address in the 'recipients' value.
                 Note that you also have to allow this email address in the
                 $TARGET_EMAIL setting within formmail.php!
    -->
                    <input type="hidden" name="recipients" value="lindaW5XLZS3Bbcpba.org,infoW5XLZS3Bbcpba.org" />
                    <!-- STEP 3: Specify required fields in the 'required' value -->
                    <input type="hidden" name="required" value="email:Your email address,realname:Your name" />
                    <!-- STEP 4: Put your subject line in the 'subject' value. -->
                    <input type="hidden" name="subject" value="BCPBA Website Contact Us Form" />
                  </p>
                  <table width="368" border="0">
                    <tr>
                      <td><span class="style6 style7"><strong>Name</strong></span></td>
                      <td><input name="realname" type="text" size="30" />
                          </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>Email </strong></span></td>
                      <td><span class="style14">
                        <input name="email" type="text" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>Company / Station</strong></span></td>
                      <td><span class="style14">
                        <input name="Company or Station" type="text" id="testfield" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>Address</strong></span></td>
                      <td><span class="style14">
                        <input name="Address" type="text" id="text" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>City</strong></span></td>
                      <td><span class="style14">
                        <input name="City" type="text" id="text" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>State</strong></span></td>
                      <td><span class="style14">
                        <input name="State" type="text" id="text" size="5" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><p class="style18 style17 style16 style6 style7"><strong>Zip </strong></p></td>
                      <td><span class="style16">
                        <input name="Zip" type="text" id="text" size="30" />
                      </span></td>
                    </tr>
                  </table>
                  <p class="style14 style6 style7">I<strong> would like (<em>check all that apply</em>) </strong></p>
                  <p class="style5">
                    <input type="checkbox" name="Checkbox1" value="Membership Information" />
                    Membership information sent to me <br />
                    <input type="checkbox" name="Checkbox2" value="Participate or Support in some way other than membership" />
                    Participate or support in some way other than membership
                    <label><br />
                      <input type="checkbox" name="Checkbox3" value="I have a question answered?" />
                    </label>
                    Have a   question answered (see below)<br />
                    <label>
                      <input type="checkbox" name="Checkbox4" value="Address change (type previous address   below)" />
                    </label>
                    Address change (type previous address   below)</p>
                  <p class="style5"><br />
                      <label>
                      <input type="checkbox" name="Checkbox5" value="Other (see below)" />
                      </label>
                    Other (see below)</p>
                  <p class="style14 style6 style7"><strong>Comments</strong></p>
                  <p class="style14 style11">
                    <textarea name="mesg" rows="10" cols="50"></textarea>
                  </p>
                  <p class="style14 style11">&nbsp;</p>
  <!-- Start of Varification Code. -->

   <?php
     require_once('recaptchalib.php');
     $publickey = "KEY LEFT OUT FOR SECURITY"; // you got this from the signup page
     echo recaptcha_get_html($publickey);
   ?>
   <input type="submit" />
 </form>
  <!-- End of Varification Code. -->


This is the varify.php code


 <?php
 require_once('recaptchalib.php');
 $privatekey = "XXXXXXXILEFT MY KEY OUT FOR SECURITY";
 $resp = recaptcha_check_answer ($privatekey,
                               $_SERVER["REMOTE_ADDR"],
                               $_POST["recaptcha_challenge_field"],
                               $_POST["recaptcha_response_field"]);

 if (!$resp->is_valid) {
   // What happens when the CAPTCHA was entered incorrectly
   die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
        "(reCAPTCHA said: " . $resp->error . ")");
 } else {
   // Your code here to handle a successful verification
 }
 ?>

 

by: mplungjanPosted on 2009-08-07 at 12:04:43ID: 25045945

I do NOT see any of that,
I see

<!--

-->

in the view-source source of varify

 

by: sobeservices2Posted on 2009-08-08 at 12:23:01ID: 25051333

Looking for a formmail script that uses recaptcha and is easy to install. I can't seem to find a good secure formmail script.


** Contact info  removed by b0lsc0tt - EE Zone Advisor **

 

by: mplungjanPosted on 2009-08-08 at 22:47:38ID: 25052977

I personally use recaptcha. It was not difficult to install

When I look a the view-source of your varify, I do not beleive it is the same code as the one you posted...

 

by: sobeservices2Posted on 2009-08-10 at 09:38:53ID: 25061522

I am posing my source code here as I have it.

Right now the form will work if you fill out the recapture and if you don't fill out the recapture the form still works.

I am using.

Here is the code from where the users fills out the form.

I am using a script by http://www.tectite.com/ to process the form mail.


ANY HELP WOULD GREATLY BE APPRECIATED. AS RIGHT NOW I AM STUCK AND DON"T KNOW WHAT TO DO.




                  <!-- STEP 1: Put the full URL to formmail.php on your website in the 'action' value. -->
                </p>
                        <span class="style8">
                <!-- STEP 1: Put the full URL to formmail.php on your website in the 'action' value. -->
                </span>
                <form action="" method="post" class="style8" name="contact">
                  <p>
                    <input type="hidden" name="env_report" value="REMOTE_HOST,REMOTE_ADDR,HTTP_USER_AGENT,AUTH_TYPE,REMOTE_USER" />
                    <!-- STEP 2: Put your email address in the 'recipients' value.
                 Note that you also have to allow this email address in the
                 $TARGET_EMAIL setting within formmail.php!
    -->
                    <input type="hidden" name="recipients" value="XXXX" />
                    <!-- STEP 3: Specify required fields in the 'required' value -->
                    <input type="hidden" name="required" value="email:Your email address,realname:Your name" />
                    <!-- STEP 4: Put your subject line in the 'subject' value. -->
                    <input type="hidden" name="subject" value="BCPBA Website Contact Us Form" />
                  </p>
                  <table width="368" border="0">
                    <tr>
                      <td><span class="style6 style7"><strong>Name</strong></span></td>
                      <td><input name="realname" type="text" size="30" />
                          </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>Email </strong></span></td>
                      <td><span class="style14">
                        <input name="email" type="text" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>Company / Station</strong></span></td>
                      <td><span class="style14">
                        <input name="Company or Station" type="text" id="testfield" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>Address</strong></span></td>
                      <td><span class="style14">
                        <input name="Address" type="text" id="text" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>City</strong></span></td>
                      <td><span class="style14">
                        <input name="City" type="text" id="text" size="30" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><span class="style18 style17 style6 style7"><strong>State</strong></span></td>
                      <td><span class="style14">
                        <input name="State" type="text" id="text" size="5" />
                      </span></td>
                    </tr>
                    <tr>
                      <td><p class="style18 style17 style16 style6 style7"><strong>Zip </strong></p></td>
                      <td><span class="style16">
                        <input name="Zip" type="text" id="text" size="30" />
                      </span></td>
                    </tr>
                  </table>
                  <p class="style14 style6 style7">I<strong> would like (<em>check all that apply</em>) </strong></p>
                  <p class="style5">
                    <input type="checkbox" name="Checkbox1" value="Membership Information" />
                    Membership information sent to me <br />
                    <input type="checkbox" name="Checkbox2" value="Participate or Support in some way other than membership" />
                    Participate or support in some way other than membership
                    <label><br />
                      <input type="checkbox" name="Checkbox3" value="I have a question answered?" />
                    </label>
                    Have a   question answered (see below)<br />
                    <label>
                      <input type="checkbox" name="Checkbox4" value="Address change (type previous address   below)" />
                    </label>
                    Address change (type previous address   below)</p>
                  <p class="style5"><br />
                      <label>
                      <input type="checkbox" name="Checkbox5" value="Other (see below)" />
                      </label>
                    Other (see below)</p>
                  <p class="style14 style6 style7"><strong>Comments</strong></p>
                  <p class="style14 style11">
                    <textarea name="mesg" rows="10" cols="50"></textarea>
                  </p>
                  <p class="style14 style11">&nbsp;</p>
  <!-- Start of Varification Code. -->
 
<?php
 
require_once('recaptchalib.php');
 
// Get a key from http://recaptcha.net/api/getkey
$publickey = "PUBK";
$privatekey = "PRIVK";
 
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
 
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
 
        if ($resp->is_valid) {
                //echo "You got it!";
                        echo "<script>document.contact.action='formmail.php';document.contact.submit(); </script>";
        } else {
                # set the error code so that we can display it
                $error = $resp->error;
        }
}
echo recaptcha_get_html($publickey, $error);
?>
    <br/>
    <input type="submit" value="submit" />
    </form>
  <!-- End of Varification Code. --> 

                                              
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:

Select allOpen in new window

 

by: sobeservices2Posted on 2009-08-10 at 09:39:58ID: 25061538

Oh the action of the submit is not calling varify.php like rechapture shows in the example. I can't figure out how to make there thing work on my site

 

by: mplungjanPosted on 2009-08-10 at 23:56:53ID: 25066668

Mine looks like this where PUBLIC_KEY is my public key (I removed yours from the example above and put the exampl in a snippet for you)

        <form action="actualformmail.php" method="post" >
        <input type="hidden" name="subject" value="Mail from my website" />
        <input type="hidden" name="redirect" value="thankyou.html" />
 
        <table width="100%" border="1">
          <tr><td align="right">First name:</td><td>&nbsp;</td><td><input name="FirstName" value="" size="55" /></td></tr>
          <tr><td align="right">Last name:</td><td>&nbsp;</td><td><input type="text" name="LastName" value="" size="55" /></td></tr>
          <tr><td align="right">City/Country:</td><td>&nbsp;</td><td><input type="text" name="Country" value="" size="55" /></td></tr>
          <tr><td align="right">* Email:</td><td>&nbsp;</td><td id="emailCell"><input type="text" name="email" value="" size="55" /></td></tr>
          <tr valign="top"><td align="right">Message:</td><td>&nbsp;</td><td id="questionCell"><textarea name="question" cols="40" rows="10"></textarea></td></tr>
          <tr><td colspan="2">&nbsp;</td><td><script type="text/javascript" src="http://api.recaptcha.net/challenge?k=PUBLIC_KEY"></script>
 
	<noscript>
  		<iframe src="http://api.recaptcha.net/noscript?k=PUBLIC_KEY" height="300" width="500" frameborder="0"></iframe><br/>
  		<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
  		<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
	</noscript></td></tr>
 
          <tr><td colspan="2">&nbsp;</td><td><input type="submit" value="Send" /></td></tr>
        </table>
 
       </form>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: sobeservices2Posted on 2009-08-11 at 07:27:38ID: 25069450

I replaced PUBLIC_KEY with my public key.
Replaced "actualformmail.php" with my formmail.php (I use a formmail script from http://www.tectite.com/)

Did work. Just looped back to the contact page again.

I put up a test at bcpba.org/test.html


Also $TARGET_EMAIL = array("^$info@bcpba\.org",

THIS IS THE TARGET LOCATION OF THE FORM my email address.

** offer to chat removed - b0lsc0tt **

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="en-us">
	<head>
		<title>Contact The Broward County Police Benevolent Association</title>
		<link href="styles.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-2389628-7");
pageTracker._initData();
pageTracker._trackPageview();
</script>
<!-- This following bit of code catches IE up to the rest of the browsers in terms of handling transparent graphics. -->
<!--[If IE]>
	<style>        #nav { 
        	  margin: 0 0 0 7px; 
              }
		h1 {
			margin: 0 110px 50px 0;
		}
	</style>
<![EndIf]-->
<style type="text/css">
<!--
.style11 {font-size: 10px}
.style5 {font-size: 12px; font-family: Arial, Helvetica, sans-serif;}
.style6 {font-family: Arial, Helvetica, sans-serif}
.style7 {font-size: 12px}
.style8 {font-weight: bold}
-->
</style>
</head>
	<body>
    
 
<!-- Starting here is where I'm building the template. -->
 
<!-- This div tag has the whole page in it, and with CSS we center this div. -->
 
		<div id="page">
 
<!-- NOTE: You might need to change the path of the images (and/or rename the images) when you put this on your servers -->
 
			<img src="images/bcpba-image-top.png" alt="The Broward County Police Benevolent Association" width="780" height="289" />
 
<!-- This is the start of the nav bar -->
 
			<div id="nav">
 
				<img src="images/bcpba-nav-curve.png" alt="navbar swoosh" width="160" height="35" />
 
<!-- This is the start of the nav bar links section -->
 
			  <div id="navlinks">                	<p>
              
                        <a href="index.html"><img src="images/home-button.png" alt="Home" width="160" height="25" /></a>
                	    <a href="about.html"><img src="images/bcpba-nav-01.png" alt="About the PBA" width="160" height="25" /></a>
                	    <a href="membership.html"><img src="images/bcpba-nav-02.png" alt="Membership" width="160" height="26" /></a>
                	    <a href="executive_board_staff.html"><img src="images/bcpba-nav-03.png" alt="Executive Board and Staff" width="160" height="26" /></a>
                	    <a href="board_of_directors.html"><img src="images/bcpba-nav-04.png" alt="Board of Directors" width="160" height="24" /></a>
                	    <a href="legal_representation.html"><img src="images/bcpba-nav-05.png" alt="Legal Representation" width="160" height="26" /></a>
                	    <a href="hope_fund.html"><img src="images/bcpba-nav-06.png" alt="The Hope Fund" width="160" height="25" /></a>
                        <a href="hope_fund.html"><img src="images/scholarship_program_button.png" alt="Scholarship Program" width="160" height="25" /></a>				  
                	    <a href="legislative.html"><img src="images/bcpba-nav-07.png" alt="Legislative" width="160" height="23" /></a>
                	    <a href="pba_hall.html"><img src="images/bcpba-nav-08.png" alt="PBA Hall" width="160" height="25" /></a>
                	    <a href="contracts.html"><img src="images/contracts_button.png" alt="Contracts" width="160" height="25" /></a>
                	    <a href="news.html"><img src="images/bcpba-nav-10.png" alt="News Alerts" width="160" height="25" /></a>
                	    <a href="pba_plate.html"><img src="images/bcpba-nav-11.png" alt="PBA License Plate" width="160" height="25" /></a>				 
                	    <a href="merchandise.html"><img src="images/bcpba-nav-12.png" alt="Merchandise" width="160" height="25" /></a>
                	    <a href="members_only_home.php"><img src="images/bcpba-nav-13.png" alt="Members Only Page" width="160" height="25" /></a>
                	    <a href="newsletter.html"><img src="images/bcpba-nav-14.png" alt="Newsletter" width="160" height="25" /></a>
                	    <a href="/blog2/blog2/"><img src="images/bcpba-nav-15.png" alt="President's Blog" width="160" height="25" /></a>
                	    <a href="contact.html"><img src="images/bcpba-nav-16.png" alt="Contact Us Page" width="160" height="26" /></a>                    
                	    <a href="police_memorial.html"><img src="images/bcpba-nav-17.png" alt="Police Memorial" width="160" height="24" /></a>				
                	    <a href="affiliation.html"><img src="images/affiliations_button.png" alt="Affiliation" width="160" height="25" /></a>                	    
                        <a href="links.html"><img src="images/links_button.png" alt="Links" width="160" height="25" /></a>
                        <a href="events.html"><img src="images/events_button.png" alt"Events" width="160" hight="25"/></a><a href="">
                        <br />
                        <br />
                        <img src="images/syndicated-feed-icon.gif" alt="" width="16" height="16" /></a><a href="pba_feed.xml">PBA RSS FEED</a>
                        <br />
               	</p>
                    <p><!-- Start of Site Search Pro code --><style type="text/css">.sp2_field {border:1px solid #999999; background-color:#ffffff; font-family:Arial; font-style:normal; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_btn {font-family:Arial; font-style:normal; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_i_select {background-color:#ffffff; font-family:Arial; font-style:normal; color:#000000; font-size:12px; font-weight:normal; 
}a.sp2_advanced:link,a.sp2_advanced:active,a.sp2_advanced:visited {font-family:Arial; font-style:normal; text-decoration:none; color:#7777cc; font-size:11px; font-weight:normal; 
}a.sp2_advanced:hover {font-family:Arial; font-style:normal; text-decoration:underline; color:#7777cc; font-size:11px; font-weight:normal; 
}.sp2_info {font-family:Arial; font-style:normal; text-decoration:none; color:#000000; font-size:13px; font-weight:bold; 
}a.sp2_title:link,a.sp2_title:active,a.sp2_title:visited {font-family:Arial; font-style:normal; text-decoration:none; color:#7777cc; font-size:13px; font-weight:bold; 
}a.sp2_title:hover {font-family:Arial; font-style:normal; text-decoration:underline; color:#7777cc; font-size:13px; font-weight:bold; 
}.sp2_result {font-family:Arial; font-style:normal; text-decoration:none; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_select {font-family:Arial; font-style:normal; text-decoration:none; color:#990000; font-size:12px; font-weight:bold; 
}.sp2_address {font-family:Arial; font-style:normal; text-decoration:none; color:#008000; font-size:12px; font-weight:normal; 
}.sp2_page {font-family:Arial; font-style:normal; text-decoration:none; color:#000000; font-size:12px; font-weight:normal; 
}a.sp2_page:link,a.sp2_page:active,a.sp2_page:visited {font-family:Arial; font-style:normal; text-decoration:underline; color:#000000; font-size:12px; font-weight:normal; 
}a.sp2_page:hover {font-family:Arial; font-style:normal; text-decoration:underline; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_nowpage {font-family:Arial; font-style:normal; text-decoration:none; color:#a90a08; font-size:12px; font-weight:bold; 
}</style>
<form action="http://bcpba.org/searchpro/index.php" method="get" enctype="application/x-www-form-urlencoded" name="qs" id="qs">
<br />
&nbsp;&nbsp;&nbsp;Search Site<br />
&nbsp;&nbsp;&nbsp;<input class="sp2_field" name="q" type="text" id="q" value="" maxlength="255" size="15"> 
    <br />
&nbsp;&nbsp;&nbsp;<input class="sp2_btn" name="search" type="submit" id="search" value="Search">
        <br />
&nbsp;&nbsp;&nbsp;<a class="sp2_advanced" href="http://bcpba.org/searchpro/advanced_search.php?g=0">Advanced search</a>
</form>
<!-- End of Site Search Pro code -->  </p>
			  </div>
 
		  </div>
 
            <p>
  <!-- This is the end of the navigation bar area -->
            </p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
          <p>
              
              
<!-- This is the start of the body side of things -->
<?php
$FM_VERS = "8.05";      // script version
 
/* ex:set ts=4 sw=4 et:
 * FormMail PHP script from Tectite.com.  This script requires PHP 4 or later.
 * Copyright (c) 2001-2008 Root Software and Open Concepts Pty Ltd
 * (ABN 93 003 733 499), Melbourne, Australia.
 * This script is free for all use as described in the "Copying and Use" and
 * "Warranty and Disclaimer" sections below.
 *
 * Visit us at http://www.tectite.com/ for updates and more information.
 *
 *** If you use Tectite FormMail, please support its development and other
 *** freeware products by putting the following link on your website:
 ***  Visit www.tectite.com for free <a href="http://www.tectite.com/">html form processor</a>.
 *
 * Author: Russell Robinson, 2nd October 2001
 * Last Modified: RR 14:07 Wed 15 August 2007
 * QVCS Version: $Revision: 1.4 $
 *
 * Read This First
 * ~~~~~~~~~~~~~~~
 *  This script is very well documented and quite large!  It looks daunting,
 *  but really isn't.
 *  If you have experience with PHP or other scripting languages,
 *  here's what you *need* to read:
 *      - Configuration (TARGET_EMAIL & DEF_ALERT)
 *      - Creating Forms
 *  That's it!  (Alternatively, just read the Quick Start and/or
 *  Quicker Start section below).
 *  Full configuration documentation is here:
 *      http://www.tectite.com/fmdoc/index.php
 *
 * Purpose:
 * ~~~~~~~~
 *  To accept information from an HTML form via HTTP and mail it to recipients.
 *
 * What does this PHP script do?
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  On your web site, you may have one or more HTML forms that accept
 *  information from people visiting your website.  Your aim is for your
 *  website to email that information to you and/or add it to a database.
 *  FormMail performs those functions.
 *
 * Quick Start
 * ~~~~~~~~~~~
 *  1. Edit this file and set TARGET_EMAIL for your requirements (near
 *      line 235 in this file - replace "yourhost\.com" with your mail server's
 *      name).  We also strongly recommend you set DEF_ALERT (the next
 *      configuration below TARGET_EMAIL).
 *  2. Install this file as formmail.php (or other name ending in .php)
 *     on your web server.
 *  3. Create an HTML form and:
 *      - specify a hidden field called "recipients" with the email address
 *        of the person to receive the form's results.
 *      - in the your form tag set the action attribute to
 *        the formmail.php you uploaded to your web server
 *
 *  Once you have FormMail working, you may be interested in some advanced
 *  usage and features.  We have HOW-TO guides at www.tectite.com which
 *  describe many of the advanced processing you can do with FormMail.
 *      http://www.tectite.com/fmhowto/guides.php
 *
 * Quicker Start
 * ~~~~~~~~~~~~~
 *  Use the FormMail Configuration Wizard here:
 *      http://www.tectite.com/wizards/fmconf.php
 *  By answering a few questions you'll get a configured FormMail and
 *  a sample HTML form ready to upload and use on your server.
 *
 * Features
 * ~~~~~~~~
 *  For a list of features go to: http://www.tectite.com/formmailpage.php
 *
 * Security
 * ~~~~~~~~
 *  Security is the primary concern in accepting data from your website
 *  visitors.
 *  Tectite FormMail has several security features designed into it.  Note,
 *  however, it requires configuration for your particular web site.
 *
 * Configuration
 * ~~~~~~~~~~~~~
 *  To configure this script, go to the section titled "CONFIGURATION"
 *  (after reading the legal stuff below).
 *
 *  There is only one mandatory setting: TARGET_EMAIL
 *  and one strongly recommended setting: DEF_ALERT
 *
 *  Full configuration information is available here:
 *      http://www.tectite.com/fmdoc/index.php
 *
 * Creating Forms
 * ~~~~~~~~~~~~~~
 *  Go to this URL to learn how to write HTML forms for use with
 *  Tectite FormMail: http://www.tectite.com/fmdoc/creating_forms.php
 *
 * Copying and Use
 * ~~~~~~~~~~~~~~~
 *  Tectite FormMail is provided free of charge and may be freely distributed
 *  and used provided that you:
 *      1. keep this header, including copyright and comments,
 *         in place and unmodified; and,
 *      2. do not charge a fee for distributing it, without an agreement
 *         in writing with Root Software allowing you to do so; and,
 *      3. if you modify FormMail before distributing it, you clearly
 *         identify:
 *              a) who you are
 *              b) how to contact you
 *              c) what changes you have made
 *              d) why you have made those changes.
 *
 * Warranty and Disclaimer
 * ~~~~~~~~~~~~~~~~~~~~~~~
 *  Tectite FormMail is provided free-of-charge and with ABSOLUTELY NO WARRANTY.
 *  It has not been verified for use in critical applications, including,
 *  but not limited to, medicine, defense, aircraft, space exploration,
 *  or any other potentially dangerous activity.
 *
 *  By using Tectite FormMail you agree to indemnify Root Software and
 *  Open Concepts Pty Ltd, their agents, employees, directors and
 *  associated companies and businesses from any liability whatsoever.
 *
 * We still care
 * ~~~~~~~~~~~~~
 *  If you find a bug or fault in FormMail, please report it to us.
 *  We will respond to your report and make endeavours to rectify any
 *  faults you've detected as soon as possible.
 *
 *  To contact us please register on our forums at:
 *      http://www.tectite.com/vbforums/
 *  or view our contact information:
 *      http://www.tectite.com/contacts.php
 *
 * Version History
 * ~~~~~~~~~~~~~~~
 *  Near the top of this file, you'll find its version. The version
 *  line looks like this:
 *       $FM_VERS = "N.MM";     /* script version ...
 *
 *  The version history used to be located within this file.  However,
 *  starting with Version 8.00 we've moved it...
 *
 *  You can read the complete version history of FormMail on our
 *  main website here:
 *   http://www.tectite.com/fmdoc/version_history.php
 */
 
    //
    // Capture the current date and time, for various purposes.
    //
$lNow = time();
 
set_magic_quotes_runtime(0);        // disable this silly setting (usually not enabled)
ini_set('track_errors',1);          // enable $php_errormsg
 
$aAlertInfo = array();
$aPHPVERSION = array();
 
$sLangID = "";                      // the language ID
$aMessages = array();               // all FormMail messages in the appropriate
                                    // language
 
$bUseOldVars = IsOldVersion($aPHPVERSION);
 
    //
    // seed the random number generate if not version 4.2.0 or later
    //
if (!IsPHPAtLeast("4.2.0"))
    mt_srand(time());
 
    //
    // we set references to the appropriate arrays to handle PHP version differences
    // Session vars are selected after we start the session.
    //
if ($bUseOldVars)
{
    $aServerVars = &$HTTP_SERVER_VARS;
    $aGetVars = &$HTTP_GET_VARS;
    $aFormVars = &$HTTP_POST_VARS;
    $aFileVars = &$HTTP_POST_FILES;
    $aEnvVars = &$HTTP_ENV_VARS;
}
else
{
    $aServerVars = &$_SERVER;
    $aGetVars = &$_GET;
    $aFormVars = &$_POST;
    $aFileVars = &$_FILES;
    $aEnvVars = &$_ENV;
}
$bIsGetMethod = false;
 
    //
    // If the form submission was using the GET method, switch to the
    // GET vars instead of the POST vars
    //
if (isset($aServerVars["REQUEST_METHOD"]) && $aServerVars["REQUEST_METHOD"] === "GET")
{
    $bIsGetMethod = true;
    if ($bUseOldVars)
        $aFormVars = &$HTTP_GET_VARS;
    else
        $aFormVars = &$_GET;
}
 
if (!isset($REAL_DOCUMENT_ROOT))
    SetRealDocumentRoot();
 
if (isset($aServerVars['SERVER_PORT']))
    $SCHEME = ($aServerVars['SERVER_PORT'] == 80) ? "http://" : "https://";
else
    $SCHEME = "";
if (isset($aServerVars['SERVER_NAME']))
    $SERVER = $aServerVars['SERVER_NAME'];
else
    $SERVER = "";
 
/*****************************************************************************/
/* CONFIGURATION (do not alter this line in any way!!!)                      */
/*****************************************************************************
 * This is the *only* place where you need to modify things to use formmail.php
 * on your particular system.  This section finishes at "END OF CONFIGURATION".
 * Help for all settings can be found on our website:
 *  http://www.tectite.com/fmdoc/index.php
 *
 * Also, above each setting is a direct URL to the help information for the
 * setting.
 *****************************************************************************/
 
            /* Help: http://www.tectite.com/fmdoc/email_name.php */
define("EMAIL_NAME","^[-a-z0-9.]+");    // the '^' is an important security feature!
 
            /* Help: http://www.tectite.com/fmdoc/target_email.php */
$TARGET_EMAIL = array("^$info@bcpba\.org",
                );
 
            /* Help: http://www.tectite.com/fmdoc/def_alert.php */
define("DEF_ALERT","");
 
            /* Help: http://www.tectite.com/fmdoc/set_real_document_root.php */
$SET_REAL_DOCUMENT_ROOT = "";       // overrides the value set by SetRealDocumentRoot function
 
    //
    // override $REAL_DOCUMENT_ROOT from the $SET_REAL_DOCUMENT_ROOT value (if any)
    // Do not alter the following code (next 3 lines)!
    //
if (isset($SET_REAL_DOCUMENT_ROOT) && $SET_REAL_DOCUMENT_ROOT !== "")
    $REAL_DOCUMENT_ROOT = $SET_REAL_DOCUMENT_ROOT;
 
            /* Help: http://www.tectite.com/fmdoc/config_check.php */
$CONFIG_CHECK = array("TARGET_EMAIL");
 
            /* Help: http://www.tectite.com/fmdoc/at_mangle.php */
define("AT_MANGLE","W5XLZS3B");
 
            /* Help: http://www.tectite.com/fmdoc/target_urls.php */
$TARGET_URLS = array();         // default; no URLs allowed
 
            /* Help: http://www.tectite.com/fmdoc/head_crlf.php */
define("HEAD_CRLF","\r\n");
 
            /* Help: http://www.tectite.com/fmdoc/body_lf.php */
define("BODY_LF","\r\n");       // the new default: use this for CR+LF
//define("BODY_LF","\n");       // the old default: just LF
 
            /* Help: http://www.tectite.com/fmdoc/from_user.php */
$FROM_USER = "";                            // the default - setting not used
 
            /* Help: http://www.tectite.com/fmdoc/sendmail_f_option.php */
define("SENDMAIL_F_OPTION",false);
define("SENDMAIL_F_OPTION_LINE",__LINE__-1);    // don't modify this line!
 
            /* Help: http://www.tectite.com/fmdoc/fixed_sender.php */
$FIXED_SENDER = "";
 
            /* Help: http://www.tectite.com/fmdoc/set_sender_from_email.php */
define("SET_SENDER_FROM_EMAIL",false);
 
            /* Help: http://www.tectite.com/fmdoc/ini_set_from.php */
define("INI_SET_FROM",false);
 
            /* Help: http://www.tectite.com/fmdoc/logdir.php */
$LOGDIR = "";                           // directory for log files; empty string to
                                        // disallow log files
            /* Help: http://www.tectite.com/fmdoc/autorespondlog.php */
$AUTORESPONDLOG = "";           // file name in $LOGDIR for the auto responder
                                // log; empty string for no auto responder log
 
            /* Help: http://www.tectite.com/fmdoc/csv_file_settings.php */
$CSVDIR = "";                       // directory for csv files; empty string to
                                    // disallow csv files
$CSVSEP = ",";      // comma separator between fields (columns)
$CSVINTSEP = ";";   // semicolon is the separator for fields (columns)
                    // with multiple values (checkboxes, etc.)
$CSVQUOTE = '"';    // all fields in the CSV are quoted with this character;
                    // default is double quote.  You can change it to
                    // single quote or leave it empty for no quotes.
//$CSVQUOTE = "'";  // use this if you want single quotes
$CSVOPEN = "";      // set to "b" to force line terminations to be
                    // kept as $CSVLINE setting below, regardless of
                    // operating system.  Keep as empty string and
                    // leave $CSVLINE unchanged, to get text file
                    // terminations for your server's operating system.
                    // (Line feed on UNIX, carriage-return line feed on Windows).
$CSVLINE = "\n";    // line termination for CSV files.  The default is
                    // a single line feed, which may be modified for your
                    // server's operating system.  If you want to change
                    // this value, you *must* set $CSVOPEN = "b".
 
            /* Help: http://www.tectite.com/fmdoc/templatedir.php */
$TEMPLATEDIR = "";                  // directory for template files; empty string
                                    // if you don't have any templates
 
            /* Help: http://www.tectite.com/fmdoc/templateurl.php */
$TEMPLATEURL = "";                  // default; no template URL
 
            /* Help: http://www.tectite.com/fmdoc/multiformdir.php */
$MULTIFORMDIR = "";         // directory for multi-form template files; empty string
                            // if you're not using multi-forms
 
            /* Help: http://www.tectite.com/fmdoc/multiformurl.php */
$MULTIFORMURL = "";                 // default; no multi-forms templates URL
 
            /* Help: http://www.tectite.com/fmdoc/authentication_settings.php */
$AUTHENTICATE = "";
//$AUTHENTICATE = "Basic cnVzc2VsbHI6dGVzdA==";        // example
$AUTH_USER = "";
$AUTH_PW = "";
 
            /* Help: http://www.tectite.com/fmdoc/form_ini_file.php */
$FORM_INI_FILE = "";
 
            /* Help: http://www.tectite.com/fmdoc/moduledir.php */
$MODULEDIR = ".";
 
            /* Help: http://www.tectite.com/fmdoc/fmcompute.php */
$FMCOMPUTE = "fmcompute.php";
 
            /* Help: http://www.tectite.com/fmdoc/fmgeoip.php */
$FMGEOIP = "fmgeoip.php";
 
            /* Help: http://www.tectite.com/fmdoc/advanced_templates.php */
define("ADVANCED_TEMPLATES",false);     // set to true for advanced templates
 
            /* Help: http://www.tectite.com/fmdoc/limited_import.php */
define("LIMITED_IMPORT",true);      // set to true if your database cannot
                                    // handle escaped quotes or newlines within
                                    // imported data.  Microsoft Access is one
                                    // example.
 
            /* Help: http://www.tectite.com/fmdoc/valid_env.php */
$VALID_ENV = array('HTTP_REFERER','REMOTE_HOST','REMOTE_ADDR','REMOTE_USER',
				'HTTP_USER_AGENT');
 
            /* Help: http://www.tectite.com/fmdoc/fileuploads.php */
define("FILEUPLOADS",false);        // set to true to allow file attachments
 
            /* Help: http://www.tectite.com/fmdoc/max_file_upload_size.php */
define("MAX_FILE_UPLOAD_SIZE",0);       // default of 0 means that other software
                                        // controls the maximum file upload size
                                        // (FormMail doesn't test the file size)
 
            /* Help: http://www.tectite.com/fmdoc/file_repository.php */
$FILE_REPOSITORY = "";
 
            /* Help: http://www.tectite.com/fmdoc/file_mode.php */
define("FILE_MODE",0664);     // always precede with 0 to specify octal!
 
            /* Help: http://www.tectite.com/fmdoc/file_overwrite.php */
define("FILE_OVERWRITE",true);
 
            /* Help: http://www.tectite.com/fmdoc/next_num_file.php */
$NEXT_NUM_FILE = "";
 
            /* Help: http://www.tectite.com/fmdoc/put_data_in_url.php */
define("PUT_DATA_IN_URL",true); // set to true to place data in the URL
                                    // for bad_url redirects
 
            /* Help: http://www.tectite.com/fmdoc/db_see_input.php */
define("DB_SEE_INPUT",false);       // set to true to just see the input values
 
            /* Help: http://www.tectite.com/fmdoc/db_see_ini.php */
define("DB_SEE_INI",false);     // set to true to just see the ini file
 
            /* Help: http://www.tectite.com/fmdoc/maxstring.php */
define("MAXSTRING",1024);           // maximum string length for a value
 
            /* Help: http://www.tectite.com/fmdoc/bshowmesgnumbers.php */
$bShowMesgNumbers = false;
 
            /* Help: http://www.tectite.com/fmdoc/filters.php */
            /* Note for Tectite personnel: the upgrade Wizard will merge new values
             * but be careful of $var usage and quoting in new entries.
             */
$FILTERS = array("encode"=>"$REAL_DOCUMENT_ROOT/cgi-bin/fmencoder -kpubkey.txt",
                "null"=>"null",
 'csv'=>'csv');
 
            /* Help: http://www.tectite.com/fmdoc/socket_filters.php */
$SOCKET_FILTERS = array(
				 "httpencode"=>array("site"=>"YourSiteHere",
				 	"port"=>80,
					"path"=>"/cgi-bin/fmencoder",
					"params"=>array(array("name"=>"key",
							"file"=>"$REAL_DOCUMENT_ROOT/cgi-bin/pubkey.txt"))),
				 "sslencode"=>array("site"=>"ssl://YourSecureSiteHere",
				 	"port"=>443,
					"path"=>"/cgi-bin/fmencoder",
					"params"=>array(array("name"=>"key",
							"file"=>"$REAL_DOCUMENT_ROOT/cgi-bin/pubkey.txt"))),
				);
 
            /* Help: http://www.tectite.com/fmdoc/filter_attribs.php */
$FILTER_ATTRIBS = array("encode"=>"Strips,MIME=application/vnd.fmencoded,Encrypts",
                        "httpencode"=>"Strips,MIME=application/vnd.fmencoded,Encrypts",
                        "sslencode"=>"Strips,MIME=application/vnd.fmencoded,Encrypts",
                        "csv"=>"Strips,MIME=text/csv",);
 
            /* Help: http://www.tectite.com/fmdoc/check_for_new_version.php */
define("CHECK_FOR_NEW_VERSION",true);
define("CHECK_DAYS",30);
 
            /* Help: http://www.tectite.com/fmdoc/scratch_pad.php */
$SCRATCH_PAD = "";
 
            /* Help: http://www.tectite.com/fmdoc/cleanup_time.php */
$CLEANUP_TIME = 60;     // cleanup time in minutes
 
            /* Help: http://www.tectite.com/fmdoc/cleanup_chance.php */
$CLEANUP_CHANCE = 20;     // percentage probability that cleanup will be performed
 
            /* Help: http://www.tectite.com/fmdoc/pear_settings.php */
$PEAR_SMTP_HOST = "";
$PEAR_SMTP_PORT = 25;
$PEAR_SMTP_USER = "";
$PEAR_SMTP_PWD = "";
 
            /* Help: http://www.tectite.com/fmdoc/alert_on_user_error.php */
define("ALERT_ON_USER_ERROR",false);
 
            /* Help: http://www.tectite.com/fmdoc/enable_attack_detection.php */
define("ENABLE_ATTACK_DETECTION",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_url.php */
define("ATTACK_DETECTION_URL","");
 
            /* Help: http://www.tectite.com/fmdoc/alert_on_attack_detection.php */
define("ALERT_ON_ATTACK_DETECTION",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_mime.php */
define("ATTACK_DETECTION_MIME",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_dups.php */
$ATTACK_DETECTION_DUPS = array("realname","address1","address2","country","zip",
                                "phone","postcode","state","email");
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_specials.php */
define("ATTACK_DETECTION_SPECIALS",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_specials.php */
$ATTACK_DETECTION_SPECIALS_ONLY_EMAIL = array("derive_fields","required",
                    "mail_options","good_url","bad_url","good_template",
                    "bad_template");
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_specials.php */
$ATTACK_DETECTION_SPECIALS_ANY_EMAIL = array("subject");
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_many_urls.php */
define("ATTACK_DETECTION_MANY_URLS",0);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_many_url_fields.php */
define("ATTACK_DETECTION_MANY_URL_FIELDS",0);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_url_patterns.php */
$ATTACK_DETECTION_URL_PATTERNS = array(
            '(^|[^-a-z_.0-9]+)(?<!@)([-a-z0-9]+\.)+(com|org|net|biz|info|name|pro|tel|asia|cat)\b',
            '(^|[^-a-z_.0-9]+)(?<!@)([-a-z0-9]+\.)+(com{0,1}|org|net)\.[a-z][a-z]\b');
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_ignore_errors.php */
define("ATTACK_DETECTION_IGNORE_ERRORS",false);
 
            /* Help: http://www.tectite.com/fmdoc/geoip_lic.php */
$GEOIP_LIC = "";        // default - no GeoIP
 
            /* Help: http://www.tectite.com/fmdoc/zero_is_empty.php */
define("ZERO_IS_EMPTY",false);
 
            /* Help: http://www.tectite.com/fmdoc/session_name.php */
$SESSION_NAME = "";
 
            /* Help: http://www.tectite.com/fmdoc/hook_dir.php */
$HOOK_DIR = "";
 
/* UPGRADE CONTROL
**
** FILTERS:lt:8.04:merge:The FILTERS configuration has
** been modified to include some new standard filters.:
**
** FILTER_ATTRIBS:lt:8.04:no_keep:The FILTER_ATTRIBS configuration has
** been modified to include new information about the standard filters.:
**
** ATTACK_DETECTION_URL_PATTERNS:eq:8.02:no_keep:The ATTACK_DETECTION_URL_PATTERNS
** configuration has been modified to fix a bug.:
**
** FILTER_ATTRIBS:lt:4.00:no_keep:The FILTER_ATTRIBS configuration has
** been modified to include new information about the standard filters.:
**
** SET_REAL_DOCUMENT_ROOT:gt:4.07:copy_from=REAL_DOCUMENT_ROOT:The
** REAL_DOCUMENT_ROOT configuration has been renamed to SET_REAL_DOCUMENT_ROOT.:
**
** EMAIL_NAME:lt:6.01:no_keep:The EMAIL_NAME configuration has
** been modified to match hyphens ('-') in email addresses.:
**
** ZERO_IS_EMPTY:le:6.01:set_to=true:ZERO_IS_EMPTY has been
** set to a value that duplicates previous behaviour.:
**
** END OF CONTROL
*/
 
/*****************************************************************************/
/* END OF CONFIGURATION (do not alter this line in any way!!!)               */
/*****************************************************************************/
    //
    // the following constants define all FormMail messages
    //
define('MSG_SCRIPT_VERSION',0);     // This script requires at least PHP version...
define('MSG_END_VERS_CHK',1);       // If you're happy...
define('MSG_VERS_CHK',2);           // A later version of FormMail is available...
define('MSG_CHK_FILE_ERROR',3);     // Unable to create check file...
define('MSG_UNK_VALUE_SPEC',4);     // derive_fields: unknown value specification...
define('MSG_INV_VALUE_SPEC',5);     // derive_fields: invalid value specification...
define('MSG_DERIVED_INVALID',6);    // Some derive_fields specifications...
define('MSG_INT_FORM_ERROR',7);     // Internal form error...
define('MSG_OPTIONS_INVALID',8);    // Some mail_options settings...
define('MSG_PLSWAIT_REDIR',9);      // Please wait while you are redirected...
define('MSG_IFNOT_REDIR',10);       // If you are not redirected...
define('MSG_PEAR_OBJ',11);          // Failed to create PEAR Mail object...
define('MSG_PEAR_ERROR',12);        // PEAR Mail error...
define('MSG_NO_FOPT_ADDR',13);      // You have specified "SendMailFOption"...
define('MSG_MORE_INFO',14);         // More information...
define('MSG_INFO_STOPPED',15);      // Extra alert information suppressed...
define('MSG_FM_ALERT',16);          // FormMail alert
define('MSG_FM_ERROR',17);          // FormMail script error
define('MSG_FM_ERROR_LINE',18);     // The following error occurred...
define('MSG_USERDATA_STOPPED',19);  // User data suppressed...
define('MSG_FILTERED',20);          // This alert has been filtered...
define('MSG_TEMPLATES',21);         // You must set either TEMPLATEDIR or TEMPLATEURL...
define('MSG_OPEN_TEMPLATE',22);     // Failed to open template...
define('MSG_ERROR_PROC',23);        // An error occurred while processing...
define('MSG_ALERT_DONE',24);        // Our staff have been alerted...
define('MSG_PLS_CONTACT',25);       // Please contact us directly...
define('MSG_APOLOGY',26);           // We apologize for any inconvenience...
define('MSG_ABOUT_FORMMAIL',27);    // Your form submission was processed by...
define('MSG_PREG_FAILED',28);       // preg_match_all failed in FindCRMFields...
define('MSG_URL_INVALID',29);       // CRM URL "$URL" is not valid...
define('MSG_URL_OPEN',30);          // Failed to open Customer Relationship...
define('MSG_CRM_FAILED',31);        // Failure report from CRM...
define('MSG_CRM_FORM_ERROR',32);    // Your form submission was not...
define('MSG_OR',33);                // "$ITEM1" or "$ITEM2"
define('MSG_NOT_BOTH',34);          // not both "$ITEM1" and "$ITEM2"
define('MSG_XOR',35);               // "$ITEM1" or "$ITEM2" (but not both)
define('MSG_IS_SAME_AS',36);        // "$ITEM1" is the same as "$ITEM2"
define('MSG_IS_NOT_SAME_AS',37);    // "$ITEM1" is not the same as "$ITEM2"
define('MSG_REQD_OPER',38);         // Operator "$OPER" is not valid for "required"
define('MSG_PAT_FAILED',39);        // Pattern operator "$OPER" failed: pattern...
define('MSG_COND_OPER',40);         // Operator "$OPER" is not valid...
define('MSG_INV_COND',41);          // Invalid "conditions" field...
define('MSG_COND_CHARS',42);        // The conditions field "$FLD" is not valid...
define('MSG_COND_INVALID',43);      // The conditions field "$FLD" is not valid...
define('MSG_COND_TEST_LONG',44);    // Field "$FLD" has too many components...
define('MSG_COND_IF_SHORT',45);     // Field "$FLD" has too few components for...
define('MSG_COND_IF_LONG',46);      // Field "$FLD" has too many components for...
define('MSG_COND_UNK',47);          // Field "$FLD" has an unknown command word...
define('MSG_MISSING',48);           // Missing "$ITEM"...
define('MSG_NEED_ARRAY',49);        // "$ITEM" must be an array...
define('MSG_SUBM_FAILED',50);       // Your form submission has failed...
define('MSG_FILTER_WRONG',51);      // Filter "$FILTER" is not properly...
define('MSG_FILTER_CONNECT',52);    // Could not connect to site "$SITE"...
define('MSG_FILTER_PARAM',53);      // Filter "$FILTER" has invalid parameter...
define('MSG_FILTER_OPEN_FILE',54);  // Filter "$FILTER" cannot open file...
define('MSG_FILTER_FILE_ERROR',55); // Filter "$FILTER": read error on file...
define('MSG_FILTER_READ_ERROR',56); // Filter '$filter' failed: read error...
define('MSG_FILTER_NOT_OK',57);     // Filter 'FILTER' failed...
define('MSG_FILTER_UNK',58);        // Unknown filter...
define('MSG_FILTER_CHDIR',59);      // Cannot chdir...
define('MSG_FILTER_NOTFOUND',60);   // Cannot execute...
define('MSG_FILTER_ERROR',61);      // Filter "$FILTER" failed...
define('MSG_FLD_NOTFOUND',62);      // "$FIELD" is not a field submitted...
define('MSG_TEMPLATE_ERRORS',63);   // Template "$NAME" caused the...
define('MSG_TEMPLATE_FAILED',64);   // Failed to process template "$NAME"...
define('MSG_MIME_PREAMBLE',65);     // (Your mail reader should not show this...
define('MSG_MIME_HTML',66);         // This message has been generated by FormMail...
define('MSG_FILE_OPEN_ERROR',67);   // Failed to open file "$NAME"...
define('MSG_ATTACH_DATA',68);       // Internal error: AttachFile requires...
define('MSG_PHP_HTML_TEMPLATES',69);    // HTMLTemplate option is only ...
define('MSG_PHP_FILE_UPLOADS',70);  // For security reasons, file upload...
define('MSG_FILE_UPLOAD',71);       // File upload attempt ignored...
define('MSG_FILE_UPLOAD_ATTACK',72);// Possible file upload attack...
define('MSG_PHP_PLAIN_TEMPLATES',73);// PlainTemplate option is only...
define('MSG_ATTACH_NAME',74);       // filter_options: Attach must contain a name...
define('MSG_PHP_BCC',75);           // Warning: BCC is probably not supported...
define('MSG_CSVCOLUMNS',76);        // The "csvcolumns" setting is not...
define('MSG_CSVFILE',77);           // The "csvfile" setting is not...
define('MSG_TARG_EMAIL_PAT_START',78);  // Warning: Your TARGET_EMAIL pattern...
define('MSG_TARG_EMAIL_PAT_END',79);    // Warning: Your TARGET_EMAIL pattern...
define('MSG_CONFIG_WARN',80);       // The following potential problems...
define('MSG_PHP_AUTORESP',81);      // Autorespond is only supported...
define('MSG_ALERT',82);             // This is a test alert message...
define('MSG_NO_DEF_ALERT',83);      // No DEF_ALERT value has been set....
define('MSG_TEST_SENT',84);         // Test message sent.  Check your email.....
define('MSG_TEST_FAILED',85);       // FAILED to send alert message...
define('MSG_NO_DATA_PAGE',86);      // This URL is a Form submission program...
define('MSG_REQD_ERROR',87);        // The form required some values that you...
define('MSG_COND_ERROR',88);        // Some of the values you provided...
define('MSG_CRM_FAILURE',89);       // The form submission did not succeed...
define('MSG_FOPTION_WARN',90);      // Warning: You've used SendMailFOption in...
define('MSG_NO_ACTIONS',91);        // The form has an internal error...
define('MSG_NO_RECIP',92);          // The form has an internal error...
define('MSG_INV_EMAIL',93);         // Invalid email addresses...
define('MSG_FAILED_SEND',94);       // Failed to send email...
define('MSG_ARESP_EMAIL',96);       // No "email" field was found. Autorespond...
define('MSG_ARESP_SUBJ',97);        // Your form submission...
define('MSG_LOG_NO_VERIMG',98);     // No VerifyImgString in session...
define('MSG_ARESP_NO_AUTH',99);     // Failed to obtain authorization...
define('MSG_LOG_NO_MATCH',100);     // User did not match image...
define('MSG_ARESP_NO_MATCH',101);   // Your entry did not match...
define('MSG_LOG_FAILED',102);       // Failed
define('MSG_ARESP_FAILED',103);     // Autoresponder failed
define('MSG_LOG_OK',104);           // OK
define('MSG_THANKS_PAGE',105);      // Thanks!  We've received your....
define('MSG_LOAD_MODULE',106);      // Cannot load module....
define('MSG_LOAD_FMCOMPUTE',107);   // Cannot load FMCompute....
define('MSG_REGISTER_MODULE',108);  // Cannot register module....
define('MSG_COMP_PARSE',109);       // These parse errors occurred....
define('MSG_COMP_REG_DATA',110);    // Failed to register data field....
define('MSG_COMP_ALERT',111);       // The following alert messages....
define('MSG_COMP_DEBUG',112);       // The following debug messages...
define('MSG_COMP_EXEC',113);        // The following errors occurred....
define('MSG_REG_FMCOMPUTE',114);    // Cannot register function...
define('MSG_USER_ERRORS',115);      // A number of errors occurred...
define('MSG_CALL_PARAM_COUNT',116); // Invalid parameter count...
define('MSG_CALL_UNK_FUNC',117);    // Unknown function...
define('MSG_SAVE_FILE',118);        // Failed to save file....
define('MSG_CHMOD',119);            // Failed to chmod file....
define('MSG_VERIFY_MISSING',120);   // Image verification string missing...
define('MSG_VERIFY_MATCH',121);     // Your entry did not match...
define('MSG_FILE_NAMES_INVALID',122);// Some file_names specifications...
define('MSG_FILE_NAMES_NOT_FILE',123);// Your file_names specification...
define('MSG_TEMPL_ALERT',124);       // The following alert messages....
define('MSG_TEMPL_DEBUG',125);       // The following debug messages...
define('MSG_TEMPL_PROC',126);        // The following errors occurred....
define('MSG_SAVE_FILE_EXISTS',127);  // Cannot save file....
define('MSG_EMPTY_ADDRESSES',128);   // $COUNT empty addresses
 
define('MSG_AND',133);              // "$ITEM1" and "$ITEM2"
define('MSG_NEXT_PLUS_GOOD',134);   // The form specifies both next_form and....
define('MSG_MULTIFORM',135);        // You must set either MULTIFORMDIR or MULTIFORMURL...
define('MSG_MULTIFORM_FAILED',136); // Failed to process multi-page form template "$NAME"...
define('MSG_NEED_THIS_FORM',137);   // Multi-page forms require "this_form" field...
define('MSG_NO_PHP_SELF',138);      // PHP on the server is not providing "PHP_SELF"
define('MSG_RETURN_URL_INVALID',139); // Return "$URL" is not valid...
define('MSG_GO_BACK',140);          // Cannot 'go back' if not a multi-page form...
define('MSG_OPEN_URL',141);         // Cannot open URL...
define('MSG_CANNOT_RETURN',142);    // Cannot return to page....
define('MSG_ATTACK_DETECTED',143);  // Server attack detected....
define('MSG_ATTACK_PAGE',144);      // Your form submission....
define('MSG_ATTACK_MIME_INFO',145); // The field "$FLD" contained...
define('MSG_ATTACK_DUP_INFO',146);  // The fields "$FLD1" and...
define('MSG_ATTACK_SPEC_INFO',147); // Special field "$FLD"...
define('MSG_NEED_SCRATCH_PAD',148); // You need to set SCRATCH_PAD...
define('MSG_MULTI_UPLOAD',149);     // File upload processing failed during multi-page form processing.
define('MSG_OPEN_SCRATCH_PAD',150); // Cannot open directory...
define('MSG_NO_NEXT_NUM_FILE',151); // You cannot use the %nextnum% feature...
define('MSG_NEXT_NUM_FILE',152);    // Cannot process next number...
define('MSG_ATTACK_MANYURL_INFO',153); // Field "$FLD"...
define('MSG_ATTACK_MANYFIELDS_INFO',154); // $NUM fields have URLs....
 
define('MSG_URL_PARSE',160);        // URL parse failed
define('MSG_URL_SCHEME',161);       // Unsupported URL scheme...
define('MSG_SOCKET',162);           // Socket error ...
define('MSG_GETURL_OPEN',163);      // Open URL failed: ...
 
    //
    // The following are PHP's file upload error messages
    //
define('MSG_FILE_UPLOAD_ERR_UNK',180);  // Unknown error code.
define('MSG_FILE_UPLOAD_ERR1',181);     // The uploaded file exceeds the upload_max_filesize directive in php.ini.
define('MSG_FILE_UPLOAD_ERR2',182);     // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.
define('MSG_FILE_UPLOAD_ERR3',183);     // The uploaded file was only partially uploaded.
define('MSG_FILE_UPLOAD_ERR4',184);     // No file was uploaded.
define('MSG_FILE_UPLOAD_ERR6',186);     // Missing a temporary folder.
define('MSG_FILE_UPLOAD_ERR7',187);     // Failed to write file to disk.
define('MSG_FILE_UPLOAD_ERR8',188);     // File upload stopped by extension.
define('MSG_FILE_UPLOAD_SIZE',189);     // Uploaded file "$NAME" is too big...
                                        // (not a PHP error code - internal maximum file size error)
 
    //
    // following are for derive_fields functions
    //
define('MSG_DER_FUNC_ERROR',200);       // derive_fields: invalid function....
define('MSG_DER_FUNC_SIZE_FMT',201);    // function 'size' requires....
define('MSG_DER_FUNC_IF_FMT',202);      // function 'if' requires....
define('MSG_DER_FUNC_NEXTNUM_FMT',203); // function 'nextnum' requires....
define('MSG_DER_FUNC_EXT_FMT',204);     // function 'ext' requires....
define('MSG_DER_FUNC1_FMT',205);        // function 'FUNC' requires....
 
// <A NAME="MessageNumbers"> Jump to: <A HREF="#BuiltinMessages">
 
    //
    // Return true if using the built-in language
    //
function IsBuiltInLanguage()
{
    global  $sLangID;
 
    return (strpos($sLangID,"builtin") !== false);
}
 
$sSavePath = "";
$bPathSaved = false;
    //
    // Set include path to include the given directory.
    //
function AddIncludePath($s_dir = ".")
{
    global  $sSavePath,$bPathSaved;
 
    $s_path = ini_get('include_path');
    $i_path_len = strlen($s_path);
    $s_sep = IsServerWindows() ? ";" : ":";     // get path separator
        //
        // look for it in the include_path
        //
    $b_found = false;
    $i_pos = 0;
    $i_len = strlen($s_dir);
    while (!$b_found && ($i_pos = strpos($s_path,$s_dir,$i_pos)) !== false)
    {
        if ($i_pos == 0)
        {
            if ($i_len == $i_path_len)
                $b_found = true;        // the path only has $s_dir
            elseif ($s_path{$i_len} == $s_sep)
                $b_found = true;
        }
        elseif ($s_path{$i_pos-1} == $s_sep &&
                    ($i_pos + $i_len == $i_path_len ||
                    $s_path{$i_pos + $i_len} == $s_sep))
                $b_found = true;
        if (!$b_found)
            $i_pos++;
    }
    if (!$b_found)
    {
            //
            // allow multiple calls, but only store the original path once
            //
        if (!$bPathSaved)
            $sSavePath = $s_path;
        if (empty($s_path))
            $s_path = $s_dir;
        else
                //
                // prepend the directory
                //
            $s_path = $s_dir.$s_sep.$s_path;
        ini_set('include_path',$s_path);
        $bPathSaved = true;
    }
}
 
    //
    // Reset the include path after a call to AddIncludePath.
    //
function ResetIncludePath()
{
    global  $sSavePath,$bPathSaved;
 
    if ($bPathSaved)
    {
        ini_set('include_path',$sSavePath);
        $bPathSaved = false;
    }
}
 
    //
    // Load a language file
    //
function LoadLanguageFile()
{
    global  $aMessages,$sLangID,$sHTMLCharSet;
 
    AddIncludePath();
    @include("language.inc");
    ResetIncludePath();
}
 
    //
    // Load the messages array from the default language, and then
    // override with an optional language file.
    // Note: all messages get the MNUM parameter sent which they can use.
    // If they don't use it, the message number is appended.
    //
function LoadBuiltinLanguage()
{
    global  $aMessages,$sLangID;
 
    $sLangID = "English (builtin)";
        // MSG_SCRIPT_VERSION is shown if the PHP version is too old to run
        // FormMail
        // Parameters:
        //  $PHPREQ     is the minimum required PHP version
        //  $PHPVERS    is  the version the server currently has installed.
    $aMessages[MSG_SCRIPT_VERSION] = 'This script requires at least PHP version '.
                                     '$PHPREQ.  You have PHP version $PHPVERS.';
 
        // MSG_END_VERS_CHK is sent at the end of an Alert message when
        // FormMail detects that there's a newer version available
        // Parameters: none
    $aMessages[MSG_END_VERS_CHK] =  '***************************************************\n'.
                                    'If you are happy with your current version and want\n'.
                                    'to stop these reminders, edit formmail.php and\n'.
                                    'set CHECK_FOR_NEW_VERSION to false.\n'.
                                    '***************************************************\n';
 
        // MSG_VERS_CHK is sent in an Alert message when
        // FormMail detects that there's a newer version available
        // Parameters:
        //  $TECTITE    the website to go to
        //  $FM_VERS    the current FormMail version
        //  $NEWVERS    the new FormMail version that's available
    $aMessages[MSG_VERS_CHK] =  'A later version of FormMail is available from $TECTITE.\n'.
                                'You are currently using version $FM_VERS.\n'.
                                'The new version available is $NEWVERS.\n';
 
        // MSG_CHK_FILE_ERROR is sent in an Alert message when
        // FormMail cannot create a file to record the time of version check.
        // Parameters:
        //  $FILE   the file name that could not be created
        //  $ERROR  the actual error message
    $aMessages[MSG_CHK_FILE_ERROR] = 'Unable to create check file "$FILE": $ERROR';
 
        // MSG_UNK_VALUE_SPEC is sent in an Alert message when
        // a form uses an unknown value specification in derive_fields.
        // Parameters:
        //  $SPEC   the unknown value specification
        //  $MSG    additional message
    $aMessages[MSG_UNK_VALUE_SPEC] = 'derive_fields: unknown value specification '.
                                     '"$SPEC"$MSG';
 
        // MSG_INV_VALUE_SPEC is sent in an Alert message when
        // a form uses a value specification in derive_fields that's
        // formatted incorrectly (missing terminating '%')
        // Parameters:
        //  $SPEC   the invalid value specification
    $aMessages[MSG_INV_VALUE_SPEC] = 'derive_fields: invalid value specification '.
                                     '"$SPEC" (possibly missing a "%")';
 
        // MSG_DERIVED_INVALID is sent in an Alert message when
        // a form's derive_fields setting has errors
        // Parameters: none
        // A list of errors is appended on separate lines
    $aMessages[MSG_DERIVED_INVALID] = 'Some derive_fields specifications are invalid $MNUM:\n';
 
        // MSG_INT_FORM_ERROR is sent in an Alert message and displayed
        // to the form user
        // Parameters: none
    $aMessages[MSG_INT_FORM_ERROR] = 'Internal form error';
 
        // MSG_OPTIONS_INVALID is sent in an Alert message when
        // a form's options settings are invalid.  This applies to
        // mail_options, filter_options, crm_options, and autorespond
        // Parameters:
        //  $OPT    the name of the options field
        // A list of errors is appended on separate lines
    $aMessages[MSG_OPTIONS_INVALID] = 'Some $OPT settings are undefined $MNUM:\n';
 
        // MSG_PLSWAIT_REDIR is shown to the user for a redirect
        // with JavaScript
        // Parameters: none
    $aMessages[MSG_PLSWAIT_REDIR] = 'Please wait while you are redirected...';
 
        // MSG_IFNOT_REDIR is shown to the user for a redirect
        // with JavaScript
        // Parameters:
        //  $URL    the URL to redirect to
    $aMessages[MSG_IFNOT_REDIR] = 'If you are not automatically redirected, '.
                                  'please <a href="$URL">click here</a>.';
 
        // MSG_PEAR_OBJ is shown to the user if the PEAR Mail object
        // cannot be created
        // Parameters: none
    $aMessages[MSG_PEAR_OBJ] = 'Failed to create PEAR Mail object';
 
        // MSG_PEAR_ERROR is sent in an Alert message if the PEAR Mail processing
        // reports an error
        // Parameters:
        //  $MSG    the error message from PEAR
    $aMessages[MSG_PEAR_ERROR] = 'PEAR Mail error: $MSG';
 
        // MSG_NO_FOPT_ADDR is sent in an Alert message SendMailFOption is
        // specified in the form and no email address has been provided
        // Parameters: none
    $aMessages[MSG_NO_FOPT_ADDR] = 'You have specified "SendMailFOption" in your '.
                                   'form, but there is no email address to use';
 
        // MSG_MORE_INFO is sent in an Alert message on a line by itself, just
        // before extra information about the FormMail processing that may have
        // led to the alert message
        // Parameters: none
    $aMessages[MSG_MORE_INFO] = 'More information:';
 
        // MSG_INFO_STOPPED is sent in an Alert message to say that extra
        // alert information has been suppressed because of potential security
        // problems with showing it.
        // Parameters: none
    $aMessages[MSG_INFO_STOPPED] = '(Extra alert information suppressed for '.
                                   'security purposes. $MNUM)';
 
        // MSG_FM_ALERT is sent as the subject line of an Alert message
        // Parameters: none
    $aMessages[MSG_FM_ALERT] = 'FormMail alert';
 
        // MSG_FM_ERROR is sent as the subject line of an Alert message
        // Parameters: none
    $aMessages[MSG_FM_ERROR] = 'FormMail script error';
 
        // MSG_FM_ERROR_LINE is sent in an Alert message on a
        // separate line to introduce the actual error message
        // Parameters: none
    $aMessages[MSG_FM_ERROR_LINE] = 'The following error occurred in FormMail $MNUM:';
 
        // MSG_USERDATA_STOPPED is sent in an Alert message to say that the
        // user's data has been suppressed because of potential security
        // problems with showing it.
        // Parameters: none
    $aMessages[MSG_USERDATA_STOPPED] = '(User data suppressed for security '.
                                       'purposes. $MNUM)';
 
        // MSG_FILTERED is sent in an Alert message to show what filter
        // has been used on the message
        // Parameters:
        //  $FILTER     the name of the filter
    $aMessages[MSG_FILTERED] = 'This alert has been filtered through "$FILTER" '.
                               'for security purposes.';
 
        // MSG_TEMPLATES is sent in an Alert message when a form tries
        // to use a template, but templates have not been configured in
        // formmail.php
        // Parameters: none
    $aMessages[MSG_TEMPLATES] = 'You must set either TEMPLATEDIR or TEMPLATEURL '.
                                'in formmail.php before you can specify '.
                                'templates in your forms.';
 
        // MSG_OPEN_TEMPLATE is sent in an Alert message when FormMail cannot
        // open a template file
        // Parameters:
        //  $NAME   the name of the template file
        //  $ERROR  information about the error
    $aMessages[MSG_OPEN_TEMPLATE] = 'Failed to open template "$NAME" $MNUM: $ERROR';
 
        // MSG_ERROR_PROC is shown to the user as part of an error
        // page.  This message introduces the error.
        // Parameters: none
    $aMessages[MSG_ERROR_PROC] = 'An error occurred while processing the '.
                                 'form $MNUM.\n\n';
 
        // MSG_ALERT_DONE is shown to the user as part of an error
        // page if an Alert message has been sent to the website owner.
        // Parameters: none
    $aMessages[MSG_ALERT_DONE] = 'Our staff have been alerted to the error $MNUM.\n';
 
        // MSG_PLS_CONTACT is shown to the user as part of an error
        // page if an Alert message could *not* be sent to the website owner.
        // Parameters: none
    $aMessages[MSG_PLS_CONTACT] = 'Please contact us directly since this form '.
                                  'is not working $MNUM.\n';
 
        // MSG_APOLOGY is shown to the user as part of an error
        // page as an apology for a problem with the form.
        // Parameters: none
    $aMessages[MSG_APOLOGY] = 'We apologize for any inconvenience this error '.
                              'may have caused.';
 
        // MSG_ABOUT_FORMMAIL is shown to the user at the foot of pages
        // generated by FormMail (e.g. the default "Thanks" page and default
        // error page).
        // Parameters:
        //  $FM_VERS    the FormMail version number
        //  $TECTITE    www.tectite.com
    $aMessages[MSG_ABOUT_FORMMAIL] = 'Your form submission was processed by bcpba.org'.
                                     ''.
                                     '';
 
        // MSG_PREG_FAILED is sent in an Alert message if the TectiteCRM
        // system failed to return the expected result.
        // Parameters: none
    $aMessages[MSG_PREG_FAILED] = 'preg_match_all failed in FindCRMFields';
 
        // MSG_URL_INVALID is sent in an Alert message if the specified
        // URL for TectiteCRM is not valid according to the TARGET_URLS
        // configuration setting
        // Parameters:
        //  $URL        the invalid URL
    $aMessages[MSG_URL_INVALID] = 'The URL "$URL" to access the Customer '.
                                  'Relationship Management System is not valid '.
                                  '(see TARGET_URLS in formmail.php)';
 
        // MSG_URL_OPEN is sent in an Alert message if the specified
        // URL for TectiteCRM cannot be opened
        // Parameters:
        //  $URL    the invalid URL
        //  $ERROR  information about the error
    $aMessages[MSG_URL_OPEN] = 'Failed to open Customer Relationship '.
                               'Management System URL "$URL" $MNUM: $ERROR';
 
        // MSG_CRM_FAILED is sent in an Alert message if the TectiteCRM
        // system doesn't return an OK message
        // Parameters:
        //  $URL    the invalid URL
        //  $MSG    more information
    $aMessages[MSG_CRM_FAILED] = 'Failure report from Customer Relationship '.
                                 'Management System (url="$URL") $MNUM: $MSG';
 
        // MSG_CRM_FORM_ERROR is shown to the user if the information
        // passed to TectiteCRM was not accepted
        // Parameters: none
    $aMessages[MSG_CRM_FORM_ERROR] = 'Your form submission was not accepted';
 
        // MSG_AND is shown to the user; it shows two items separated
        // by "and"
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_AND] = '"$ITEM1" and "$ITEM2"';
 
        // MSG_OR is shown to the user; it shows two items separated
        // by "or"
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_OR] = '"$ITEM1" or "$ITEM2"';
 
        // MSG_NOT_BOTH is shown to the user; it shows two items that must
        // be specified together
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_NOT_BOTH] = 'not both "$ITEM1" and "$ITEM2"';
 
        // MSG_XOR is shown to the user; it shows two items that must
        // not be specified together
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_XOR] = '"$ITEM1" or "$ITEM2" (but not both)';
 
        // MSG_IS_SAME_AS is shown to the user; it shows two items that must
        // not be the same value
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_IS_SAME_AS] = '"$ITEM1" is the same as "$ITEM2"';
 
        // MSG_IS_NOT_SAME_AS is shown to the user; it shows two items that must
        // be the same value
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_IS_NOT_SAME_AS] = '"$ITEM1" is not the same as "$ITEM2"';
 
        // MSG_REQD_OPER is sent in an Alert message when an unknown
        // operator has been used in a "required" specification
        // Parameters:
        //  $OPER       the unknown operator
    $aMessages[MSG_REQD_OPER] = 'Operator "$OPER" is not valid for "required"';
 
        // MSG_PAT_FAILED is sent in an Alert message when a "conditions" pattern
        // match has not matched anything (this isn't necessarily an error)
        // Parameters:
        //  $OPER       the "conditions" operator
        //  $PAT        the "conditions" pattern
        //  $VALUE      the value that was searched
    $aMessages[MSG_PAT_FAILED] = 'Pattern operator "$OPER" failed: pattern '.
                                 '"$PAT", value searched was "$VALUE".';
 
        // MSG_COND_OPER is sent in an Alert message when a "conditions"
        // operator is not value
        // Parameters:
        //  $OPER       the "conditions" operator
    $aMessages[MSG_COND_OPER] = 'Operator "$OPER" is not valid for "conditions"';
 
        // MSG_INV_COND is sent in an Alert message when a "conditions"
        // field is not valid
        // Parameters:
        //  FLD     the field name
    $aMessages[MSG_INV_COND] = 'Invalid "conditions" field "$FLD" - not a string or array.';
 
        // MSG_COND_CHARS is sent in an Alert message when a "conditions"
        // field is missing the mandatory first 2 characters (the separators)
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
    $aMessages[MSG_COND_CHARS] = 'The conditions field "$FLD" is not valid. '.
                                 'You must provide the two separator '.
                                 'characters at the beginning. You had "$COND".';
 
        // MSG_COND_INVALID is sent in an Alert message when a "conditions"
        // field has the wrong format
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the internal separator character for the field.
    $aMessages[MSG_COND_INVALID] = 'The conditions field "$FLD" is not valid. '.
                                   'There must be at least 5 components '.
                                   'separated by "$SEP". Your value was "$COND".';
 
        // MSG_COND_TEST_LONG is sent in an Alert message when a "conditions"
        // TEST value has too many components
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the list separator character for the field.
    $aMessages[MSG_COND_TEST_LONG] = 'Field "$FLD" has too many components for '.
                                     'a "TEST" command: "$COND".\nAre you missing '.
                                     'a "$SEP"?';
 
        // MSG_COND_IF_SHORT is sent in an Alert message when a "conditions"
        // IF value has too few components
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the internal separator character for the field.
    $aMessages[MSG_COND_IF_SHORT] = 'Field "$FLD" has too few components for '.
                                    'an "IF" command: "$COND".\nThere must be '.
                                    'at least 6 components separated by "$SEP"';
 
        // MSG_COND_IF_LONG is sent in an Alert message when a "conditions"
        // IF value has too many components
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the list separator character for the field.
    $aMessages[MSG_COND_IF_LONG] = 'Field "$FLD" has too many components for '.
                                   'an "IF" command: "$COND".\nAre you missing '.
                                   'a "$SEP"?';
 
        // MSG_COND_UNK is sent in an Alert message when a "conditions"
        // value has an unknown command
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  CMD     the unknown command
    $aMessages[MSG_COND_UNK] = 'Field "$FLD" has an unknown command word '.
                               '"$CMD": "$COND".';
 
        // MSG_MISSING is sent in an Alert message when
        // a socket filter is incorrectly defined
        // Parameters:
        //  ITEM    the missing item
    $aMessages[MSG_MISSING] = 'Missing "$ITEM"';
 
        // MSG_NEED_ARRAY is sent in an Alert message when
        // a socket filter is incorrectly defined
        // Parameters:
        //  ITEM    the item that should be an array
    $aMessages[MSG_NEED_ARRAY] = '"$ITEM" must be an array';
 
        // MSG_SUBM_FAILED is shown to the user when an internal error
        // as occurred and that error is not to be shown
        // Parameters: none
    $aMessages[MSG_SUBM_FAILED] = 'Your form submission has failed due to '.
                                  'an error on our server.';
 
        // MSG_FILTER_WRONG is sent in an Alert message when
        // a socket filter is incorrectly defined
        // Parameters:
        //  FILTER  the filter name
        //  ERRORS  a string containing a list of errors
    $aMessages[MSG_FILTER_WRONG] = 'Filter "$FILTER" is not properly defined: '.
                                   '$ERRORS';
 
        // MSG_FILTER_CONNECT is sent in an Alert message when FormMail
        // cannot connect to a socket filter
        // Parameters:
        //  FILTER  the filter name
        //  SITE    the site
        //  ERRNUM  socket error number
        //  ERRSTR  socket error message
    $aMessages[MSG_FILTER_CONNECT] = 'Could not connect to site "$SITE" '.
                                     'for filter "$FILTER" ($ERRNUM): $ERRSTR';
 
        // MSG_FILTER_PARAM is sent in an Alert message when a socket
        // filter has an invalid parameter specification
        // Parameters:
        //  FILTER  the filter name
        //  NUM     parameter number
        //  NAME    parameter name
    $aMessages[MSG_FILTER_PARAM] = 'Filter "$FILTER" has invalid parameter '.
                                   '#$NUM: no "$NAME"';
 
        // MSG_FILTER_OPEN_FILE is sent in an Alert message when a socket
        // filter cannot open the required file
        // Parameters:
        //  FILTER  the filter name
        //  FILE    the file that could not be opened
        //  ERROR   the error message
    $aMessages[MSG_FILTER_OPEN_FILE] = 'Filter "$FILTER" cannot open file '.
                                       '"$FILE": $ERROR';
 
        // MSG_FILTER_FILE_ERROR is sent in an Alert message when a socket
        // filter gets an error message during reading a file
        // Parameters:
        //  FILTER  the filter name
        //  FILE    the file that could not be opened
        //  ERROR   the error message
        //  NLINES  the number of lines that were read successfully
    $aMessages[MSG_FILTER_FILE_ERROR] = 'Filter "$FILTER": read error on file '.
                                        '"$FILE" after $NLINES lines: $ERROR';
 
        // MSG_FILTER_READ_ERROR is sent in an Alert message when a socket
        // filter gets an error during reading from the socket
        // Parameters:
        //  FILTER  the filter name
        //  ERROR   the error message
    $aMessages[MSG_FILTER_READ_ERROR] = 'Filter "$FILTER" failed: read error: '.
                                        '$ERROR';
 
        // MSG_FILTER_NOT_OK is sent in an Alert message when a socket
        // filter fails to return the agreed __OK__ indicator
        // Parameters:
        //  FILTER  the filter name
        //  DATA    the data returned from the filter
    $aMessages[MSG_FILTER_NOT_OK] = 'Filter "$FILTER" failed (missing '.
                                    '__OK__ line): $DATA';
 
        // MSG_FILTER_UNK is sent in an Alert message
        // when an unknown filter is specified by a form
        // Parameters:
        //  FILTER  the filter name
    $aMessages[MSG_FILTER_UNK] = 'Unknown filter "$FILTER"';
 
        // MSG_FILTER_CHDIR is sent in an Alert message
        // when FormMail cannot change to the filter's directory
        // Parameters:
        //  FILTER  the filter name
        //  DIR     the directory name
        //  ERROR   an error message from the system
    $aMessages[MSG_FILTER_CHDIR] = 'Cannot chdir to "$DIR" to run filter '.
                                   '"$FILTER": $ERROR';
 
        // MSG_FILTER_NOTFOUND is sent in an Alert message
        // when FormMail cannot execute the filter
        // Parameters:
        //  FILTER  the filter name
        //  CMD     the command line being executed
        //  ERROR   an error message from the system
    $aMessages[MSG_FILTER_NOTFOUND] = 'Cannot execute filter "$FILTER" with '.
                                      'command "$CMD": $ERROR';
 
        // MSG_FILTER_ERROR is sent in an Alert message
        // when a filter returns a non-zero status
        // Parameters:
        //  FILTER  the filter name
        //  ERROR   an error message from the system
        //  STATUS  the status return from the command
    $aMessages[MSG_FILTER_ERROR] = 'Filter "$FILTER" failed (status $STATUS): '.
                                   '$ERROR';
 
        // MSG_FLD_NOTFOUND is sent as part of an Alert message
        // when a template refers to a non-existent form field
        // Parameters:
        //  FIELD   the field name
    $aMessages[MSG_FLD_NOTFOUND] = '"$FIELD" is not a field submitted from the form';
 
        // MSG_TEMPLATE_ERRORS is sent as part of an Alert message
        // when a template has generated some errors.  The message
        // should end with a new line and the actual errors are
        // output after it.
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_TEMPLATE_ERRORS] = 'Template "$NAME" caused the '.
                                      'following errors $MNUM:\n';
 
        // MSG_TEMPLATE_FAILED is sent in an Alert message
        // when processing a template has failed.
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_TEMPLATE_FAILED] = 'Failed to process template "$NAME"';
 
        // MSG_MIME_PREAMBLE is sent in the preamble of MIME emails
        // Parameters: none
    $aMessages[MSG_MIME_PREAMBLE] = '(Your mail reader should not show this '.
                                    'text.\nIf it does you may need to '.
                                    'upgrade to more modern software.)';
 
        // MSG_MIME_HTML is sent in the preamble of HTML emails
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_MIME_HTML] = 'This message has been generated by FormMail '.
                                'using an HTML template\ncalled "$NAME". The '.
                                'raw text of the form results\nhas been '.
                                'included below, but your mail reader should '.
                                'display the HTML\nversion only (unless it\'s '.
                                'not capable of doing so).';
 
        // MSG_FILE_OPEN_ERROR is sent in an Alert message when FormMail
        // cannot open a file
        // Parameters:
        //  NAME    the file name
        //  TYPE    the type of file
        //  ERROR   the system error message
    $aMessages[MSG_FILE_OPEN_ERROR] = 'Failed to open $TYPE file "$NAME": $ERROR';
 
        // MSG_ATTACH_DATA is sent in an Alert message when the file
        // attachment through 'data' has gone wrong.
        // Parameters: none
    $aMessages[MSG_ATTACH_DATA] = 'Internal error: AttachFile requires '.
                                  '"tmp_name" or "data"';
 
        // MSG_PHP_HTML_TEMPLATES is sent in an Alert message when an
        // HTML template is used but the PHP version is too old.
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_HTML_TEMPLATES] = 'HTMLTemplate option is only supported '.
                                     'with PHP version 4.0.5 or above.  Your '.
                                     'server is running version $PHPVERS.';
 
        // MSG_PHP_FILE_UPLOADS is sent in an Alert message when
        // file upload is used but the PHP version is too old.
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_FILE_UPLOADS] = 'For security reasons, file upload is only '.
                                   'allowed with PHP version 4.0.3 or above. '.
                                   'Your server is running version $PHPVERS.';
 
        // MSG_FILE_UPLOAD is sent in an Alert message when
        // file upload is attempted but FormMail is not configured to allow
        // it
        // Parameters: none
    $aMessages[MSG_FILE_UPLOAD] = 'File upload attempt ignored';
 
        // MSG_FILE_UPLOAD_ATTACK is sent in an Alert message when
        // possible file upload attack is detected
        // Parameters:
        //  NAME    file name
        //  TEMP    temporary file name
        //  FLD     name of the file upload field
    $aMessages[MSG_FILE_UPLOAD_ATTACK] = 'Possible file upload attack '.
                                         'detected: field="$FLD", name="$NAME" '.
                                         'temp name="$TEMP"';
 
        // MSG_PHP_PLAIN_TEMPLATES is sent in an Alert message when a
        // Plain template is used but the PHP version is too old.
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_PLAIN_TEMPLATES] = 'PlainTemplate option is only supported '.
                                     'with PHP version 4.0.5 or above.  Your '.
                                     'server is running version $PHPVERS.';
 
        // MSG_ATTACH_NAME is sent in an Alert message when a
        // the form uses the Attach feature without specifying a file name
        // Parameters: none
    $aMessages[MSG_ATTACH_NAME] = 'filter_options: Attach must contain a name '.
                                  '(e.g. Attach=data.txt)';
 
        // MSG_PHP_BCC is sent in an Alert message when a
        // the form uses the BCC feature and the PHP version may not support it
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_BCC] = 'Warning: BCC is probably not supported on your '.
                              'PHP version ($PHPVERS)';
 
        // MSG_CSVCOLUMNS is sent in an Alert message when a csvcolumns field
        // is not correct
        // Parameters:
        //  $VALUE  the csvcolumns field value
    $aMessages[MSG_CSVCOLUMNS] = 'The "csvcolumns" setting is not '.
                                 'valid: "$VALUE"';
 
        // MSG_CSVFILE is sent in an Alert message when a csvfile field
        // is not correct
        // Parameters:
        //  $VALUE  the csvfile field value
    $aMessages[MSG_CSVFILE] = 'The "csvfile" setting is not valid: "$VALUE"';
 
        // MSG_TARG_EMAIL_PAT_START is sent in an Alert message when a
        // $TARGET_EMAIL pattern is insecure because of a missing '^'
        // at the beginning
        // Parameters:
        //  $PAT    the pattern
    $aMessages[MSG_TARG_EMAIL_PAT_START] = 'Warning: Your TARGET_EMAIL pattern '.
                                           '"$PAT" is missing a ^ at the '.
                                           'beginning.';
 
        // MSG_TARG_EMAIL_PAT_END is sent in an Alert message when a
        // $TARGET_EMAIL pattern is insecure because of a missing '$'
        // at the end
        // Parameters:
        //  $PAT    the pattern
    $aMessages[MSG_TARG_EMAIL_PAT_END] = 'Warning: Your TARGET_EMAIL pattern '.
                                         '"$PAT" is missing a $ at the end.';
 
        // MSG_CONFIG_WARN is sent in an Alert message when the FormMail
        // configuration may have some problems.  The messages are
        // passed on separate lines, so the line terminations below
        // are important.
        // Parameters:
        //  $MESGS  lines of messages
    $aMessages[MSG_CONFIG_WARN] = 'The following potential problems were found '.
                                  'in your configuration:\n$MESGS\n\n'.
                                  'These are not necessarily errors, but you '.
                                  'should review the documentation\n'.
                                  'inside formmail.php.  If you are sure your '.
                                  'configuration is correct\n'.
                                  'you can disable the above messages by '.
                                  'changing the CONFIG_CHECK settings.';
 
        // MSG_PHP_AUTORESP is sent in an Alert message when the PHP version
        // does not support autoresponding
        // Parameters:
        //  $PHPVERS    current PHP version
    $aMessages[MSG_PHP_AUTORESP] = 'Autorespond is only supported with PHP '.
                                   'version 4.0.5 or above.  Your server is '.
                                   'running version $PHPVERS.';
 
        // MSG_ALERT is the test alert message (formmail.php?testalert=1)
        // Parameters:
        //  $LANG               the language ID
        //  $PHPVERS            PHP version
        //  $FM_VERS            FormMail version
        //  $SERVER             server type
        //  $DOCUMENT_ROOT      PHP's DOCUMENT_ROOT value
        //  $SCRIPT_FILENAME    PHP's SCRIPT_FILENAME value
        //  $PATH_TRANSLATED    PHP's PATH_TRANSLATED value
        //  $REAL_DOCUMENT_ROOT the REAL_DOCUMENT_ROOT value
    $aMessages[MSG_ALERT] = 'This is a test alert message $MNUM\n'.
                            'Loaded language is $LANG\n'.
                            'PHP version is $PHPVERS\n'.
                            'FormMail version is $FM_VERS\n'.
                            'Server type: $SERVER\n'.
                            '\n'.
                            'DOCUMENT_ROOT: $DOCUMENT_ROOT\n'.
                            'SCRIPT_FILENAME: $SCRIPT_FILENAME\n'.
                            'PATH_TRANSLATED: $PATH_TRANSLATED\n'.
                            'REAL_DOCUMENT_ROOT: $REAL_DOCUMENT_ROOT';
 
        // MSG_NO_DEF_ALERT is displayed if you use the testalert feature
        // and no DEF_ALERT setting has been provided.
        // Parameters: none
    $aMessages[MSG_NO_DEF_ALERT] = 'No DEF_ALERT value has been set.';
 
        // MSG_TEST_SENT is displayed if when use the testalert feature
        // Parameters: none
    $aMessages[MSG_TEST_SENT] = 'Test message sent.  Check your email.';
 
        // MSG_TEST_FAILED is displayed if when use the testalert feature
        // and the mail sending fails.
        // Parameters: none
    $aMessages[MSG_TEST_FAILED] = 'FAILED to send alert message.  Check your '.
                                  'server error logs.';
 
        // MSG_NO_DATA_PAGE is the page that's displayed if the user
        // just opens the URL to FormMail directly.
        // Parameters: none
    $aMessages[MSG_NO_DATA_PAGE] =  'This URL is a Form submission program.\n'.
                                    'It appears the form is not working '.
                                    'correctly as there was no data found.\n'.
                                    'You\'re not supposed to browse to this '.
                                    'URL; it should be accessed from a form.';
 
        // MSG_REQD_ERROR is displayed to the user as a default error
        // message when they haven't supplied some required fields
        // Parameters: none
    $aMessages[MSG_REQD_ERROR] = 'The form required some values that you '.
                                 'did not seem to provide.';
 
        // MSG_COND_ERROR is displayed to the user as a default error
        // message when some form conditions have failed
        // Parameters: none
    $aMessages[MSG_COND_ERROR] = 'Some of the values you provided are not valid.';
 
        // MSG_CRM_FAILURE is displayed to the user when submission
        // to the CRM has failed.
        // Parameters:
        //      $URL    the URL that was used
        //      $DATA   data returned from the CRM
    $aMessages[MSG_CRM_FAILURE] = 'The form submission did not succeed due to '.
                                  'a CRM failure. URL was \'$URL\'. '.
                                  'Returned CRM data:\n$DATA';
 
        // MSG_FOPTION_WARN is sent in an Alert message when the form
        // uses the superseded SendMailFOption feature
        // Parameters:
        //  $LINE   line number for SENDMAIL_F_OPTION
    $aMessages[MSG_FOPTION_WARN] = 'Warning: You\'ve used SendMailFOption in '.
                                   '"mail_options" in your form. This has been '.
                                   'superseded with a configuration setting '.
                                   'inside formmail.php.  Please update your '.
                                   'formmail.php configuration (look for '.
                                   'SENDMAIL_F_OPTION on line $LINE) and set '.
                                   'it to "true", then remove SendMailFOption '.
                                   'from your form(s).';
 
        // MSG_NO_ACTIONS is sent in an Alert message when there is no
        // action to perform or email address to send to
        // Parameters: none
    $aMessages[MSG_NO_ACTIONS] = 'The form has an internal error - no actions '.
                                 'or recipients were specified.';
 
        // MSG_NO_RECIP is sent in an Alert message when there are no
        // valid recipients to send to
        // Parameters: none
    $aMessages[MSG_NO_RECIP] = 'The form has an internal error - no valid '.
                               'recipients were specified.';
 
        // MSG_INV_EMAIL is sent in an Alert message when there are errors
        // in the email addresses specified in the form
        // Parameters:
        //  $ERRORS     list of errors
    $aMessages[MSG_INV_EMAIL] = 'Invalid email addresses were specified '.
                                'in the form $MNUM:\n$ERRORS';
 
        // MSG_FAILED_SEND is sent in an Alert message when the mail sending fails.
        // Parameters: none
    $aMessages[MSG_FAILED_SEND] = 'Failed to send email';
 
        // MSG_ARESP_EMAIL is sent in an Alert message when
        // no email address has been specified for an autoreponse
        // Parameters: none
    $aMessages[MSG_ARESP_EMAIL] = 'No "email" field was found. Autorespond '.
                                  'requires the submitter\'s email address.';
 
        // MSG_ARESP_SUBJ is the default subject for the auto response email
        // Parameters: none
    $aMessages[MSG_ARESP_SUBJ] = 'Your form submission';
 
        // MSG_LOG_NO_VERIMG is written to the auto respond log file
        // if no VerifyImgString session variable was found
        // Parameters: none
    $aMessages[MSG_LOG_NO_VERIMG] = 'No VerifyImgString in session';
 
        // MSG_ARESP_NO_AUTH is shown to the user
        // if no VerifyImgString session variable was found
        // Parameters: none
    $aMessages[MSG_ARESP_NO_AUTH] = 'Failed to obtain authorization to send '.
                                    'you email. This is probably a fault on '.
                                    'the server.';
 
        // MSG_LOG_NO_MATCH is written to the auto respond log file
        // if the user's entry did not match the image verification
        // Parameters: none
    $aMessages[MSG_LOG_NO_MATCH] = 'User did not match image';
 
        // MSG_ARESP_NO_MATCH is shown to the user
        // if the user's entry did not match the image verification
        // Parameters: none
    $aMessages[MSG_ARESP_NO_MATCH] = 'Your entry did not match the image';
 
        // MSG_LOG_FAILED is written to the auto respond log file
        // if the autoresponding failed
        // Parameters: none
    $aMessages[MSG_LOG_FAILED] = 'Failed';
 
        // MSG_ARESP_FAILED is sent in an Alert message
        // if the autoresponding failed
        // Parameters: none
    $aMessages[MSG_ARESP_FAILED] = 'Autoresponder failed';
 
        // MSG_LOG_OK is written to the auto respond log file
        // if the autoresponding succeeded
        // Parameters: none
    $aMessages[MSG_LOG_OK] = 'OK';
 
        // MSG_THANKS_PAGE is the default page that's displayed if the
        // submission is successful
        // Parameters: none
    $aMessages[MSG_THANKS_PAGE] = 'Thanks!  We\'ve received your information '.
                                  'and, if it\'s appropriate, we\'ll be in '.
                                  'contact with you soon.';
 
        // MSG_LOAD_MODULE is sent in an alert message if a module
        // could not be loaded.
        // Parameters:
        //  $FILE    the file name
        //  $ERROR   the error message
    $aMessages[MSG_LOAD_MODULE] = 'Cannot load module from file \'$FILE\': $ERROR';
 
        // MSG_LOAD_FMCOMPUTE is sent in an alert message if the form
        // specifies at least one "fmcompute" field and the FMCompute
        // module cannot be loaded.
        // Parameters:
        //  $FILE    the file name
        //  $ERROR   the error message
    $aMessages[MSG_LOAD_FMCOMPUTE] = 'Cannot load FMCompute module from file '.
                                        '\'$FILE\': $ERROR';
 
        // MSG_REGISTER_MODULE is sent in an alert message if a module
        // could not register with FMCompute
        // Parameters:
        //  $NAME    the name of the module
        //  $ERROR   the error message
    $aMessages[MSG_REGISTER_MODULE] = 'Cannot register module $NAME with '.
                                        'FMCompute: $ERROR';
 
 
        // MSG_COMP_PARSE is sent in an alert message if a parse error
        // occurs in an fmcompute field
        // Parameters:
        //  $CODE    the code with an error
        //  $ERRORS  the error messages
    $aMessages[MSG_COMP_PARSE] = 'These parse errors occurred in the following '.
                                    'code:\n$ERRORS\n$CODE';
 
        // MSG_COMP_REG_DATA is sent in an alert message if FormMail cannot
        // register a data field with the FMCompute module
        // Parameters:
        //  $NAME    the field name
        //  $ERROR  the error message
    $aMessages[MSG_COMP_REG_DATA] = 'Failed to register data field \'$NAME\': '.
                                    '$ERROR';
 
        // MSG_COMP_ALERT is sent in an alert message if the FMCompute
        // module has generated some alert messages.
        // Parameters:
        //  $ALERTS  the alerts
    $aMessages[MSG_COMP_ALERT] = 'The following alert messages were reported '.
                                'from the FMCompute module: $ALERTS';
 
        // MSG_COMP_DEBUG is sent in an alert message if the FMCompute
        // module has generated some debug messages.
        // Parameters:
        //  $DEBUG  the alerts
    $aMessages[MSG_COMP_DEBUG] = 'The following debug messages were reported '.
                                'from the FMCompute module: $DEBUG';
 
        // MSG_COMP_EXEC is sent in an alert message if the FMCompute
        // module has generated some error messages during execution
        // Parameters:
        //  $ERRORS  the errors
    $aMessages[MSG_COMP_EXEC] = 'The following error messages were reported '.
                                'from the FMCompute module: $ERRORS';
 
        // MSG_TEMPL_ALERT is sent in an alert message if Advanced Template
        // Processing has generated some alert messages.
        // Parameters:
        //  $ALERTS  the alerts
    $aMessages[MSG_TEMPL_ALERT] = 'The following alert messages were reported '.
                                'from the Advanced Template Processor: $ALERTS';
 
        // MSG_TEMPL_DEBUG is sent in an alert message if Advanced Template
        // Processing has generated some debug messages.
        // Parameters:
        //  $DEBUG  the alerts
    $aMessages[MSG_TEMPL_DEBUG] = 'The following debug messages were reported '.
                                'from the Advanced Template Processor: $DEBUG';
 
        // MSG_TEMPL_PROC is sent in an alert message if Advanced Template Processing
        // has generated some error messages during processing
        // Parameters:
        //  $ERRORS  the errors
    $aMessages[MSG_TEMPL_PROC] = 'The following error messages were reported '.
                                'from the Advanced Template Processor: $ERRORS';
 
        // MSG_REG_FMCOMPUTE is sent in an Alert message when FormMail
        // cannot register an external function with FMCompute.
        // Parameters:
        //  FUNC    the function that could not be registered
        //  ERROR   the error message
    $aMessages[MSG_REG_FMCOMPUTE] = 'Cannot register function "$FUNC" with '.
                                    'FMCompute: $ERROR';
 
 
        // MSG_USER_ERRORS is shown as part of a user error when an FMCompute
        // has called the "UserError" function one or more times.
        // Parameters:
        //  NONE
    $aMessages[MSG_USER_ERRORS] = 'One or more errors occurred in your form submission';
 
 
        // MSG_CALL_PARAM_COUNT is sent in an alert when a call to a FormMail
        // function from FMCompute has the wrong number of parameters
        // Parameters:
        //  FUNC    the function name
        //  COUNT   the actual number of parameters passed
    $aMessages[MSG_CALL_PARAM_COUNT] = 'FMCompute called FormMail function '.
                                       '\'$FUNC\' with wrong number of '.
                                       'parameters: $COUNT';
 
        // MSG_CALL_UNK_FUNC is sent in an alert when FMCompute calls an
        // unknown FormMail function
        // Parameters:
        //  FUNC    the function name
    $aMessages[MSG_CALL_UNK_FUNC] = 'FMCompute called unknown FormMail function '.
                                       '\'$FUNC\'';
 
        // MSG_SAVE_FILE is sent in an alert when saving a file to
        // the server has failed
        // Parameters:
        //  FILE    the source file name (usually a temporary file name)
        //  DEST    the destination file name
        //  ERR     the error message
    $aMessages[MSG_SAVE_FILE] = 'Failed to save file \'$FILE\' to \'$DEST\': $ERR';
 
        // MSG_SAVE_FILE_EXISTS is sent as part of an alert when saving a file to
        // the repository ($FILE_REPOSITORY) has failed because the file
        // already exists and FILE_OVERWRITE is set to false.
        // Parameters:
        //  FILE    the destination file name
    $aMessages[MSG_SAVE_FILE_EXISTS] = 'Cannot save file to repository as this would '.
                                        'overwrite \'$FILE\' and you have '.
                                        'set FILE_OVERWRITE to false.';
 
        // MSG_EMPTY_ADDRESSES is sent as part of an alert when a number of empty
        // email addresses have been specified in recipients, cc, or bcc
        // *and* there are no valid addresses provided
        // in the list
        // Parameters:
        //  COUNT    the number of empty addresses
    $aMessages[MSG_EMPTY_ADDRESSES] = '$COUNT empty addresses';
 
        // MSG_CHMOD is sent in an alert when changing the protection
        // mode of a file to has failed
        // Parameters:
        //  FILE    the file name
        //  MODE    the mode
        //  ERR     the error message
    $aMessages[MSG_CHMOD] = 'Failed to change protection mode of file \'$FILE\' '.
                            'to $MODE: $ERR';
 
        // MSG_VERIFY_MISSING is shown to the user image verification string
        // was not found
        // Parameters: none
    $aMessages[MSG_VERIFY_MISSING] = 'Image verification string missing. This'.
                                     ' is probably a fault on the server.';
 
        // MSG_VERIFY_MATCH is shown to the user
        // if the user's entry did not match the image verification for the
        // imgverify option
        // Parameters: none
    $aMessages[MSG_VERIFY_MATCH] = 'Your entry did not match the image';
 
        // MSG_FILE_NAMES_INVALID is sent in an Alert message when
        // a form's file_names setting has errors
        // Parameters: none
        // A list of errors is appended on separate lines
    $aMessages[MSG_FILE_NAMES_INVALID] = 'Some file_names specifications are invalid $MNUM:\n';
 
        // MSG_FILE_NAMES_NOT_FILE is sent in an Alert message when
        // a form's file_names setting refers to a file field that doesn't
        // exist
        // Parameters:
        //      NAME    the name of the file field that doesn't exist
    $aMessages[MSG_FILE_NAMES_NOT_FILE] = 'Your file_names specification has '.
                                          'an error. \'$NAME\' is not the name '.
                                          'of a file upload field\n';
 
        // MSG_NEXT_PLUS_GOOD is sent in an alert message if the form is
        // ambiguous and specifies both "next_form" and "good_url" or
        // "good_template"
        // Parameters:
        //  $WHICH  the "good_" field that was specified
    $aMessages[MSG_NEXT_PLUS_GOOD] = 'The form has specified both "next_form" '.
                                    'and "$WHICH" fields - the action to '.
                                    'to perform is ambiguous';
 
        // MSG_MULTIFORM is sent in an Alert message when a form tries
        // to use a multi-form template, but templates have not been configured in
        // formmail.php
        // Parameters: none
    $aMessages[MSG_MULTIFORM] = 'You must set either MULTIFORMDIR or MULTIFORMURL '.
                                'in formmail.php before you can use '.
                                'multi-page forms.';
 
        // MSG_MULTIFORM_FAILED is sent in an Alert message
        // when processing a multi-page form template has failed.
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_MULTIFORM_FAILED] = 'Failed to process multi-page form template "$NAME"';
 
        // MSG_NEED_THIS_FORM is sent in an Alert message
        // when a multi-page form does not specify the "this_form" field.
        // Parameters:
        //  none
    $aMessages[MSG_NEED_THIS_FORM] = 'Multi-page forms require "this_form" field';
 
        // MSG_NO_PHP_SELF is sent in an Alert message
        // when FormMail requires the "PHP_SELF" server variable and PHP is not
        // providing it.
        // Parameters:
        //  none
    $aMessages[MSG_NO_PHP_SELF] = 'PHP on the server is not providing "PHP_SELF"';
 
        // MSG_RETURN_URL_INVALID is sent in an Alert message
        // when "this_form" is not a valid return URL.  This occurs for
        // multi-page forms.
        // Parameters:
        //  URL     the invalid URL
    $aMessages[MSG_RETURN_URL_INVALID] = 'Return URL "$URL" is not valid';
 
        // MSG_GO_BACK is sent in an Alert message
        // when "multi_go_back" has been submitted but this isn't part of a
        // multi-page form.
        // Parameters:
        //  none
    $aMessages[MSG_GO_BACK] = 'Cannot "go back" if not in a multi-page form '.
                              'sequence or at the first page of the form '.
                              'sequence';
 
        // MSG_OPEN_URL is sent in an Alert message when a URL cannot
        // be opened.
        // Parameters:
        //  URL     the invalid URL
        //  ERROR   error message
    $aMessages[MSG_OPEN_URL] = 'Cannot open URL "$URL": $ERROR';
 
        // MSG_CANNOT_RETURN is sent in an Alert message when an invalid return
        // request is made in a multi-page form sequence.
        // Parameters:
        //  TO          the requested page index
        //  TOPINDEX    the top page index
    $aMessages[MSG_CANNOT_RETURN] = 'Cannot return to page $TO.  The top page '.
                                    'index is $TOPINDEX';
 
        // MSG_ATTACK_DETECTED is sent in an Alert message when an attack on
        // the server has been detected
        // Parameters:
        //  ATTACK      name or description of the attack
        //  INFO        more information about the attack
    $aMessages[MSG_ATTACK_DETECTED] = 'Server attack "$ATTACK" detected. '.
                                      'Your server is safe as FormMail is '.
                                      'invulnerable to this attack.  You can '.
                                      'disable these messages by setting '.
                                      'ALERT_ON_ATTACK_DETECTION to false '.
                                      'in FormMail\'s configuration section.'.
                                      '\nMore information:\n$INFO';
 
        // MSG_ATTACK_PAGE is the contents of the browser page displayed to the
        // user when an attack is detected
        // Parameters:
        //  none
    $aMessages[MSG_ATTACK_PAGE] = 'Your form submission has been rejected '.
                                  'as it appears to be an abuse of our server. '.
                                  'For more information about this error, visit '.
                                  '<a href="http://www.tectite.com/serverabuse.php" '.
                                  ' target="_blank">'.
                                  'www.tectite.com/serverabuse.php</a>.';
 
        // MSG_ATTACK_MIME_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the MIME attack
        // Parameters:
        //  FLD     name of the field
        //  CONTENT the invalid content found in the field
    $aMessages[MSG_ATTACK_MIME_INFO] = 'The field "$FLD" contained invalid '.
                                       'content "$CONTENT"';
 
        // MSG_ATTACK_DUP_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Duplicate Data attack
        // Parameters:
        //  FLD1     name of the first field
        //  FLD2     name of the second field
    $aMessages[MSG_ATTACK_DUP_INFO] = 'The fields "$FLD1" and "$FLD2" contained '.
                                      'duplicate data';
 
        // MSG_ATTACK_SPEC_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Special Field attack
        // Parameters:
        //  FLD     name of the special field
    $aMessages[MSG_ATTACK_SPEC_INFO] = 'Special field "$FLD" contained an email address';
 
        // MSG_ATTACK_MANYURL_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Many URLs attack
        // Parameters:
        //  FLD     name of the field
        //  NUM     number of URLs detected
    $aMessages[MSG_ATTACK_MANYURL_INFO] = 'Field "$FLD" contained $NUM URLs';
 
        // MSG_ATTACK_MANYFIELDS_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Many Fields with URLs
        // attack
        // Parameters:
        //  NUM     number of fields detected with URLs
        //  FLDS    list of fields with URLs in them
    $aMessages[MSG_ATTACK_MANYFIELDS_INFO] = '$NUM fields contained URLs: $FLDS';
 
 
        // MSG_NEED_SCRATCH_PAD is an alert message when processing requires
        // SCRATCH_PAD configuration for file upload processing.  This occurs
        // when you upload files in pages of a multi page form sequence.
        // Parameters:
        //  none
    $aMessages[MSG_NEED_SCRATCH_PAD] = 'You need to set SCRATCH_PAD in the '.
                                        'configuration section to process '.
                                        'uploaded files.';
 
        // MSG_OPEN_SCRATCH_PAD is an alert message when the SCRATCH_PAD
        // directory cannot be opened for cleanup.
        // Parameters:
        //  DIR     name of the directory
        //  ERR     more error information
    $aMessages[MSG_OPEN_SCRATCH_PAD] = 'Cannot open SCRATCH_PAD directory '.
                                        '"$DIR".  Open failed: $ERR';
 
        // MSG_NO_NEXT_NUM_FILE is an alert message when a form tries to
        // use the %nextnum% derivation feature but you haven't
        // setup FormMail's configuration correctly.
        // Parameters:
        //  none
    $aMessages[MSG_NO_NEXT_NUM_FILE] = 'You cannot use the %nextnum% feature: '.
                                        'you have not configured NEXT_NUM_FILE';
 
        // MSG_NEXT_NUM_FILE is an alert message when a form tries to
        // use the %nextnum% derivation feature but the next number file cannot
        // be processed.
        // Parameters:
        //  FILE    name of the file
        //  ACT     action
        //  ERR     more error information
    $aMessages[MSG_NEXT_NUM_FILE] = 'Cannot $ACT next number file '.
                                            '\'$FILE\': $ERR';
 
        // MSG_MULTI_UPLOAD is an alert message when processing of uploaded
        // fails during a multi-page form sequence
        // Parameters:
        //  none
    $aMessages[MSG_MULTI_UPLOAD] = 'File upload processing failed during '.
                                    'multi-page form processing.';
 
        // MSG_URL_PARSE is an error message when a URL to be opened
        // cannot be parsed
        // Parameters:
        //  none
    $aMessages[MSG_URL_PARSE] = 'Failed to parse URL';
 
        // MSG_URL_SCHEME is an error message when a URL to be opened
        // has an unsupported "scheme" value
        // Parameters:
        //  SCHEME     the scheme that was seen
    $aMessages[MSG_URL_SCHEME] = 'Unsupported URL scheme "$SCHEME"';
 
        // MSG_SOCKET is an error message when opening a socket for a URL
        // fails
        // Parameters:
        //  ERRNO     the error code
        //  ERRSTR    the error string
        //  PHPERR    the value of $php_errormsg
    $aMessages[MSG_SOCKET] = 'Socket error $ERRNO: $ERRSTR: $PHPERR';
 
        // MSG_GETURL_OPEN is an error message when the web server reports
        // a failure on opening a URL
        // Parameters:
        //  STATUS     the HTTP status value (number + string)
    $aMessages[MSG_GETURL_OPEN] = 'Open URL failed: $STATUS';
 
        // MSG_FILE_UPLOAD_ERRn are the error messages corresponding to the
        // PHP file upload error code n.
        // Parameters:
        //  none
    $aMessages[MSG_FILE_UPLOAD_ERR1] = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
    $aMessages[MSG_FILE_UPLOAD_ERR2] = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.';
    $aMessages[MSG_FILE_UPLOAD_ERR3] = 'The uploaded file was only partially uploaded.';
    $aMessages[MSG_FILE_UPLOAD_ERR4] = 'No file was uploaded.';
    $aMessages[MSG_FILE_UPLOAD_ERR6] = 'Missing a temporary folder.';
    $aMessages[MSG_FILE_UPLOAD_ERR7] = 'Failed to write file to disk.';
 
    $aMessages[MSG_FILE_UPLOAD_ERR8] = 'File upload stopped by extension.';
 
        // MSG_FILE_UPLOAD_ERR_UNK is displayed when an unknown error code
        // is provided by PHP for a file upload
        // Parameters:
        //  ERRNO   the error code
    $aMessages[MSG_FILE_UPLOAD_ERR_UNK] = 'Unknown file upload error code $ERRNO';
 
        // MSG_FILE_UPLOAD_SIZE is displayed when an uploaded file exceeds
        // the configured maximum size
        // Parameters:
        //  NAME   the uploaded file's name
        //  SIZE   the size of the uploaded file
        //  MAX    the maximum size that was exceeded
    $aMessages[MSG_FILE_UPLOAD_SIZE] = 'Uploaded file "$NAME" is too big ('.
                                        '$SIZE bytes). The maximum permitted '.
                                        'size is $MAX kilobytes.';
 
        // MSG_DER_FUNC_ERROR is sent in an Alert message when
        // a form uses a derive_fields function that's
        // formatted incorrectly
        // Parameters:
        //  $SPEC   the invalid value specification
        //  $MSG    a message describing the error or providing an example
    $aMessages[MSG_DER_FUNC_ERROR] = 'derive_fields: invalid function specification '.
                                     '"$SPEC": $MSG';
 
        // MSG_DER_FUNC_SIZE_FMT describes the right syntax for the "size" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_SIZE_FMT] = '"size" function requires this format: '.
                                    'size(file_field)';
 
        // MSG_DER_FUNC_IF_FMT describes the right syntax for the "if" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_IF_FMT] = '"if" function requires this format: '.
                                    'if(field;spec;spec)';
 
        // MSG_DER_FUNC_NEXTNUM_FMT describes the right syntax for the "nextnum" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_NEXTNUM_FMT] = '"nextnum" function requires this format: '.
                                    'nextnum(pad) or nextnum(pad;base).  pad and base '.
                                    'must be numbers. base must be 2 to 36 inclusive';
 
        // MSG_DER_FUNC_EXT_FMT describes the right syntax for the "ext" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_EXT_FMT] = '"ext" function requires this format: '.
                                    'ext(file_field)';
 
        // MSG_DER_FUNC1_FMT describes the right syntax for a function
        // requiring one parameter
        // Parameters:
        //  FUNC    name of the function
    $aMessages[MSG_DER_FUNC1_FMT] = '"$FUNC" function requires this format: '.
                                    '$FUNC(fieldname)';
 
}  // <A NAME="BuiltinMessages"> Jump to: <A HREF="#MessageNumbers">
 
    //
    // Load the default language, and then override with an optional language file.
    //
function LoadLanguage()
{
    LoadBuiltinLanguage();
    LoadLanguageFile();
}
 
    //
    // To return the value of a string or empty string if not set.
    //
function CheckString($ss)
{
    return (isset($ss) ? $ss : "");
}
 
$aGetMessageSubstituteErrors = array();
$aGetMessageSubstituteFound = array();
$bGetMessageSubstituteNoErrors = false;
 
    //
    // Worker function for GetMessage's preg_replace_callback calls.
    // Returns the value of the matched variable name.
    // Variables are searched for in the global $aGetMessageValues.
    // If no such variable exists, an empty string is returned and the
    // global variable $aGetMessageSubstituteErrors lists the missing names.
    //
function GetMessageSubstituteParam($a_matches)
{
    global  $aGetMessageValues,$aGetMessageSubstituteErrors;
    global  $aGetMessageSubstituteFound,$bGetMessageSubstituteNoErrors;
 
    $s_name = $a_matches[1];
    $aGetMessageSubstituteFound[] = $s_name;
    $s_value = "";
    if (isset($aGetMessageValues[$s_name]))
        $s_value = $aGetMessageValues[$s_name];
    elseif ($bGetMessageSubstituteNoErrors)
        $s_value = '$'.$s_name;
    else
        $aGetMessageSubstituteErrors[] = $s_name;
    return ($s_value);
}
 
    //
    // Returns message text from a message number, with optional parameters.
    //
function GetMessage($i_msg_num,$a_params = array(),
                        $b_show_mnum = true,$b_no_errors = false)
{
    global  $aMessages,$sLangID,$bShowMesgNumbers;
 
    if (!isset($aMessages[$i_msg_num]))
    {
        SendAlert("Unknown Message Number $i_msg_num was used",false,true);
        $s_text = "<UNKNOWN MESSAGE NUMBER>";
    }
    else
        $s_text = $aMessages[$i_msg_num];
    $s_mno = $bShowMesgNumbers ? "[M$i_msg_num]" : "";
 
    $s_orig_text = $s_text;
        //
        // substitute parameters; only works with PHP version 4.0.5 or later
        //
    if (strpos($s_text,'$') !== false)
    {
        global  $aGetMessageValues,$aGetMessageSubstituteErrors;
        global  $aGetMessageSubstituteFound,$bGetMessageSubstituteNoErrors;
 
        $aGetMessageSubstituteErrors = array();
        $aGetMessageSubstituteFound = array();
        $aGetMessageValues = $a_params;
        $bGetMessageSubstituteNoErrors = $b_no_errors;
        $aGetMessageValues["MNUM"] = $s_mno;    // add the message number
            //
            // search for words in this form:
            //      $word
            // where word begins with an alphabetic character and
            // consists of alphanumeric and underscore
            //
        $s_text = preg_replace_callback('/\$([a-z][a-z0-9_]*)/i',
                                            'GetMessageSubstituteParam',$s_text);
        if (count($aGetMessageSubstituteErrors) > 0)
            SendAlert("Message Number $i_msg_num ('$s_orig_text') in language $sLangID ".
                        "specified the following unsupported parameters: ".
                        implode(',',$aGetMessageSubstituteErrors));
        if (!in_array("MNUM",$aGetMessageSubstituteFound))
                //
                // append the message number
                //
            $s_text .= $b_show_mnum ? " $s_mno" : "";
    }
    else
            //
            // append the message number
            //
        $s_text .= $b_show_mnum ? " $s_mno" : "";
        //
        // replace '\n' sequences with new lines
        //
    return (str_replace('\n',"\n",$s_text));
}
 
    //
    // Check for old version of PHP - die if too old.
    //
function IsOldVersion(&$a_this_version)
{
    $a_modern = array(4,1,0);   // versions prior to this are "old" - "4.1.0"
    $s_req_string = "4.0.5";    // version 4.0.5 of PHP is required from
                                // FormMail 5.00 onward (because we use
                                // preg_replace_callback for all messages to
                                // support languages other than English)
    $a_too_old = explode(".",$s_req_string);
 
    $i_cannot_use = ($a_too_old[0] * 10000) +
                    ($a_too_old[1] * 100) +
                    $a_too_old[2];
 
    $s_vers_string = phpversion();
    $a_this_version = explode(".",$s_vers_string);
    $i_this_num = ($a_this_version[0] * 10000) +
                    ($a_this_version[1] * 100) +
                    $a_this_version[2];
 
    if ($i_this_num <= $i_cannot_use)
        die(GetMessage(MSG_SCRIPT_VERSION,array("PHPREQ"=>$s_req_string,
                                                "PHPVERS"=>$s_vers_string)));
    $i_modern_num = ($a_modern[0] * 10000) +
                    ($a_modern[1] * 100) +
                    $a_modern[2];
    return ($i_this_num < $i_modern_num);
}
 
    //
    // Check if the server is Windows
    //
function IsServerWindows()
{
    static  $bGotAnswer = false;
    static  $bAnswer;
 
    if (!$bGotAnswer)
    {
        if ((isset($_ENV["OS"]) && stristr($_ENV["OS"],"windows") !== false) ||
            (isset($_SERVER["PATH"]) && stristr($_SERVER["PATH"],"winnt") !== false) ||
            (isset($_SERVER["PATH"]) && stristr($_SERVER["PATH"],"windows") !== false) ||
            (isset($_SERVER["SystemRoot"]) && stristr($_SERVER["SystemRoot"],"winnt") !== false) ||
            (isset($_ENV["SystemRoot"]) && stristr($_ENV["SystemRoot"],"winnt") !== false) ||
            (isset($_SERVER["SystemRoot"]) && stristr($_SERVER["SystemRoot"],"windows") !== false) ||
            (isset($_ENV["SystemRoot"]) && stristr($_ENV["SystemRoot"],"windows") !== false) ||
            (isset($_SERVER["Path"]) && stristr($_SERVER["Path"],"windows") !== false))
            $bAnswer = true;
        else
            $bAnswer = false;
        $bGotAnswer = true;
    }
    return ($bAnswer);
}
 
    //
    // To return a temporary file name from $SCRATCH_PAD
    //
function GetScratchPadFile($s_prefix)
{
    global  $SCRATCH_PAD;
 
    switch (substr($SCRATCH_PAD,-1))
    {
    case '/':
    case '\\':
        $s_dir = substr($SCRATCH_PAD,0,-1);
        break;
    default:
        $s_dir = $SCRATCH_PAD;
        break;
    }
        //
        // Ideally, we could use tempnam. But,
        // tempnam is system dependent and might not use the
        // SCRATCH_PAD directory even if we tell it to.
        // So, we'll force the file into SCRATCH_PAD.
        //
        // Note that we do *not* create the file, even though tempnam
        // does create it in PHP version 4.0.3 and above. (The reason is
        // we can't guarantee a non-race condition anyway.)
        //
    do
    {
        $i_rand = mt_rand(0,16777215);  // 16777215 is FFFFFF in hex
        $s_name = $SCRATCH_PAD."/".$s_prefix.sprintf("%06X",$i_rand);
    }
    while (file_exists($s_name));
    return ($s_name);
}
 
    //
    // To return a temporary file name.
    //
function GetTempName($s_prefix)
{
    global  $SCRATCH_PAD;
 
    if (isset($SCRATCH_PAD) && !empty($SCRATCH_PAD))
        $s_name = GetScratchPadFile($s_prefix);
    else
        $s_name = tempnam("/tmp",$s_prefix);
    return ($s_name);
}
 
    //
    // To find a directory on the server for temporary files.
    //
function GetTempDir()
{
    $s_name = GetTempName("fm");
    if (file_exists($s_name))
        unlink($s_name);
    $s_dir = dirname($s_name);
    return ($s_dir);
}
 
    //
    // Returns true if the PHP version is at or later than the string specified
    // (can't use "version_compare" before 4.1.0).
    //
function IsPHPAtLeast($s_vers)
{
    global  $aPHPVERSION;
 
    $a_test_version = explode(".",$s_vers);
    if (count($a_test_version) < 3)
        return (false);
    return ($aPHPVERSION[0] > $a_test_version[0] ||
            ($aPHPVERSION[0] == $a_test_version[0] &&
                ($aPHPVERSION[1] > $a_test_version[1] ||
                    $aPHPVERSION[1] == $a_test_version[1] &&
                        $aPHPVERSION[2] >= $a_test_version[2])));
}
 
define('DEBUG',false);      // for production
//define('DEBUG',true);         // for development and debugging
 
if (DEBUG)
{
    error_reporting(E_ALL);     // trap everything!
    LoadLanguage();
}
else
{
    $iOldLevel = error_reporting(E_ALL ^ E_WARNING);
    LoadLanguage();
        //
        // report everyting except warnings and notices
        //
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
}
 
function SetRealDocumentRoot()
{
    global  $aServerVars,$REAL_DOCUMENT_ROOT;
 
    if (isset($aServerVars['SCRIPT_FILENAME']))
        $REAL_DOCUMENT_ROOT = $aServerVars['SCRIPT_FILENAME'];
    elseif (isset($aServerVars['PATH_TRANSLATED']))
        $REAL_DOCUMENT_ROOT = $aServerVars['PATH_TRANSLATED'];
    else
        $REAL_DOCUMENT_ROOT = "";
        //
        // look for 'www' or 'public_html' and strip back to that if found,
        // otherwise just get the directory name
        //
    if (($i_pos = strpos($REAL_DOCUMENT_ROOT,"/www/")) !== false)
        $REAL_DOCUMENT_ROOT = substr($REAL_DOCUMENT_ROOT,0,$i_pos+4);
    elseif (($i_pos = strpos($REAL_DOCUMENT_ROOT,"/public_html/")) !== false)
        $REAL_DOCUMENT_ROOT = substr($REAL_DOCUMENT_ROOT,0,$i_pos+12);
    elseif (!empty($REAL_DOCUMENT_ROOT))
        $REAL_DOCUMENT_ROOT = dirname($REAL_DOCUMENT_ROOT);
    elseif (isset($aServerVars['DOCUMENT_ROOT']) &&
            !empty($aServerVars['DOCUMENT_ROOT']))
        $REAL_DOCUMENT_ROOT = $aServerVars['DOCUMENT_ROOT'];
}
 
    //
    // Hook system: before initialization (but after configuration)
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookpreinit.inc");
 
if (!empty($SESSION_NAME))
    session_name($SESSION_NAME);
 
session_start();
 
function ZapSession()
{
    session_destroy();
}
 
if ($bUseOldVars)
    $aSessionVars = &$HTTP_SESSION_VARS;
else
    $aSessionVars = &$_SESSION;
 
$aSessionVars["FormError"] = NULL;
unset($aSessionVars["FormError"]);                  // start with no error
$aSessionVars["FormErrorInfo"] = NULL;
unset($aSessionVars["FormErrorInfo"]);              // start with no error
$aSessionVars["FormErrorCode"] = NULL;
unset($aSessionVars["FormErrorCode"]);              // start with no error
$aSessionVars["FormErrorItems"] = NULL;
unset($aSessionVars["FormErrorItems"]);             // start with no error
$aSessionVars["FormData"] = NULL;
unset($aSessionVars["FormData"]);                   // start with no data
$aSessionVars["FormIsUserError"] = NULL;
unset($aSessionVars["FormIsUserError"]);            // start with no data
$aSessionVars["FormAlerted"] = NULL;
unset($aSessionVars["FormAlerted"]);                // start with no data
 
//
// Note that HTTP_REFERER is easily spoofed, so there's no point in
// using it for security.
//
 
    //
    // SPECIAL_FIELDS is the list of fields that formmail.php looks for to
    // control its operation
    //
$SPECIAL_FIELDS = array(
        "email",        // email address of the person who filled in the form
        "realname",     // the real name of the person who filled in the form
        "recipients",   // comma-separated list of email addresses to which we'll send the results
        "cc",           // comma-separated list of email addresses to which we'll CC the results
        "bcc",          // comma-separated list of email addresses to which we'll BCC the results
        "required",     // comma-separated list of fields that must be found in the input
        "conditions",   // complex condition tests
        "fmcompute",    // computations
        "fmmodules",    // list of modules required
        "mail_options", // comma-separated list of options
        "good_url",     // URL to go to on success
        "good_template",// template file to display on success
        "bad_url",      // URL to go to on error
        "bad_template", // template file to display on error
        "template_list_sep", // separator when expanding lists in templates
        "this_form",    // the URL of the form (can be used by bad_url)
        "subject",      // subject for the email
        "env_report",   // comma-separated list of environment variables to report
        "filter",       // a supported filter to use
        "filter_options",// options for using the filter
        "filter_fields",// list of fields to filter (default is to filter all fields)
        "logfile",      // log file to write to
        "csvfile",      // file to write CSV records to
        "csvcolumns",   // columns to save in the csvfile
        "crm_url",      // URL for sending data to the CRM; note that the
                        // value must have a valid prefix specified in TARGET_URLS
        "crm_spec",     // CRM specification (field mapping)
        "crm_options",  // comma-separated list of options to control CRM processing
        "derive_fields", // a list of fields to derive from other fields
        "file_names",   // specifies names for files being uploaded
        "autorespond",  // specification for auto-responding
        "arverify",     // verification field to allow auto-responding
        "imgverify",    // verification field to allow submission
        "multi_start",  // set this field on the first page of a multi-page form sequence
        "multi_keep",   // set this field on the pages of a multi-page form sequence
                        // to the list of fields that should be kept when moving
                        // forward after going backwards
        "next_form",    // next form name or empty for last form
        "multi_go_back",// this field should be set when the user clicks the
                        // back button or link in a multi-page form sequence
        "alert_to");    // email address to send alerts (errors) to
 
    //
    // $SPECIAL_MULTI is the list of fields from $SPECIAL_FIELDS that can
    // have multiple values, for example:
    //      name="conditions1"
    //      name="conditions2"
    //
$SPECIAL_MULTI = array(
        "conditions",
        "fmcompute",
        );
 
    //
    // $SPECIAL_NOSTRIP is the list of fields from $SPECIAL_FIELDS that
    // should not be stripped (other than for magic_quotes_gpc reasons).
    //
$SPECIAL_NOSTRIP = array(
        "conditions",
        "fmcompute",
        );
 
    //
    // VALID_MAIL_OPTIONS lists the valid mail_options words
    //
$VALID_MAIL_OPTIONS = array(
        "AlwaysList"=>true,
        "CharSet"=>true,
        "DupHeader"=>true,
        "Exclude"=>true,
        "FromAddr"=>true,
        "HTMLTemplate"=>true,
        "KeepLines"=>true,
        "NoEmpty"=>true,
        "NoPlain"=>true,
        "PlainTemplate"=>true,
        "SendMailFOption"=>true,
        "StartLine"=>true,
        "TemplateMissing"=>true,
        );
 
    //
    // VALID_CRM_OPTIONS lists the valid crm_options words
    //
$VALID_CRM_OPTIONS = array(
        "ErrorOnFail"=>true,
        );
 
    //
    // VALID_AR_OPTIONS lists the valid autorespond words
    //
$VALID_AR_OPTIONS = array(
        "Subject"=>true,
        "HTMLTemplate"=>true,
        "PlainTemplate"=>true,
        "TemplateMissing"=>true,
        "FromAddr"=>true,
        );
 
    //
    // VALID_FILTER_OPTIONS lists the valid filter_options words
    //
$VALID_FILTER_OPTIONS = array(
        "Attach"=>true,
        "KeepInLine"=>true,
        "CSVHeading"=>true,
        "CSVSep"=>true,
        "CSVIntSep"=>true,
        "CSVQuote"=>true,
        "CSVEscPolicy"=>true,
        "CSVRaw"=>true,
        );
 
    //
    // SPECIAL_VALUES is set to the value of the fields we've found
    //  usage: $SPECIAL_VALUES["email"] is the value of the email field
    //
$SPECIAL_VALUES = array();
    //
    // Array of mail options; set by the function 'ProcessMailOptions'
    //
$MAIL_OPTS = array();
    //
    // Array of crm options; set by the function 'ProcessCRMOptions'
    //
$CRM_OPTS = array();
    //
    // Array of autorespond options; set by the function 'ProcessAROptions'
    //
$AR_OPTS = array();
    //
    // Array of filter options; set by the function 'ProcessFilterOptions'
    //
$FILTER_OPTS = array();
 
    //
    // initialise $SPECIAL_VALUES so that we don't fail on using unset values
    //
foreach ($SPECIAL_FIELDS as $sFieldName)
    $SPECIAL_VALUES[$sFieldName] = "";
 
    //
    // Special defaults for some fields....
    //
$SPECIAL_VALUES['template_list_sep'] = ",";
 
    //
    // FORMATTED_INPUT contains the input variables formatted nicely
    // This is used for error reporting and debugging only.
    //
$FORMATTED_INPUT = array();
 
    //
    // $FILTER_ATTRIBS_LOOKUP is the parsed $FILTER_ATTRIBS array
    //
$FILTER_ATTRIBS_LOOKUP = array();
 
    //
    // $EMAIL_ADDRS is the array of email addresses from the $FORM_INI_FILE
    //
$EMAIL_ADDRS = array();
 
    //
    // Access the www.tectite.com website to get the current version.
    //
function CheckVersion()
{
    global  $FM_VERS;
 
@   $fp = fopen("http://www.tectite.com/fmversion.txt","r");
    if ($fp !== false)
    {
            //
            // version file looks like this:
            //      Version=versionumber
            //      Message=a message to send in the alert
            //
        $s_version = "";
        $s_message = "";
        $s_line = "";
        $b_in_mesg = false;
        while (!feof($fp))
        {
            $s_line = fgets($fp,1024);
            if ($b_in_mesg)
                $s_message .= $s_line;
            else
            {
                $s_prefix = substr($s_line,0,8);
                if ($s_prefix == "Message=")
                {
                    $s_message .= substr($s_line,8);
                    $b_in_mesg = true;
                }
                elseif ($s_prefix == "Version=")
                    $s_version = substr($s_line,8);
            }
        }
        fclose($fp);
        $s_version = str_replace("\r","",$s_version);
        $s_version = str_replace("\n","",$s_version);
        $s_stop_mesg = GetMessage(MSG_END_VERS_CHK);
        if ((float) $s_version > (float) $FM_VERS)
            SendAlert(GetMessage(MSG_VERS_CHK,array(
                        "TECTITE"=>"www.tectite.com",
                        "FM_VERS"=>"$FM_VERS",
                        "NEWVERS"=>$s_version,
                        ))."\n$s_message\n$s_stop_mesg",true,true);
    }
}
 
    //
    // Check for new FormMail version
    //
function Check4Update($s_chk_file,$s_id = "")
{
    global  $lNow,$php_errormsg;
 
@   $l_last_chk = filemtime($s_chk_file);
    if ($l_last_chk === false || $lNow - $l_last_chk >= (CHECK_DAYS*24*60*60))
    {
        CheckVersion();
            //
            // update the check file's time stamp
            //
    @   $fp = fopen($s_chk_file,"w");
        if ($fp !== false)
        {
            fwrite($fp,"FormMail version check ".
                (empty($s_id) ? "" : "for identifier '$s_id' ").
                "at ".date("H:i:s d-M-Y",$lNow)."\n");
            fclose($fp);
        }
        else
            SendAlert(GetMessage(MSG_CHK_FILE_ERROR,array("FILE"=>$s_chk_file,
                            "ERROR"=>CheckString($php_errormsg))));
    }
}
 
    //
    // Perform various processing at the end of the script's execution.
    //
function OnExit()
{
    global  $TARGET_EMAIL,$CHECK_FILE;
 
        //
        // Check the www.tectite.com website for a new version, but only
        // do this check once every CHECK_DAYS days (or on server reboot).
        //
    if (CHECK_FOR_NEW_VERSION)
    {
        global  $SERVER;
 
        if (isset($TARGET_EMAIL[0]))
        {
                //
                // use the first few characters of the MD5 of first email
                // address pattern from $TARGET_EMAIL to get a unique file
                // for the server
                //
            $s_id = "";
            if (isset($SERVER) && !empty($SERVER))
                $s_id = $SERVER;
            $s_dir = GetTempDir();
            $s_md5 = md5($TARGET_EMAIL[0]);
            $s_uniq = substr($s_md5,0,6);
            $s_chk_file = "fm"."$s_uniq".".txt";
            Check4Update($s_dir."/".$s_chk_file,$s_id);
        }
    }
}
 
register_shutdown_function('OnExit');
 
    //
    // Return the array with each string urlencode'd.
    //
function URLEncodeArray($a_array)
{
    foreach ($a_array as $m_key=>$s_str)
    {
            //
            // only encode the value after the '='
            //
        if (($i_pos = strpos($s_str,'=')) !== false)
            $a_array[$m_key] = substr($s_str,0,$i_pos+1).
                                urlencode(substr($s_str,$i_pos+1));
        else
            $a_array[$m_key] = urlencode($s_str);
    }
    return ($a_array);
}
 
    //
    // Add a parameter or list of parameters to a URL.
    //
function AddURLParams($s_url,$m_params,$b_encode = true)
{
    if (!empty($m_params))
    {
        if (!is_array($m_params))
            $m_params = array($m_params);
        if (strpos($s_url,'?') === false)
            $s_url .= '?';
        else
            $s_url .= '&';
        $s_url .= implode('&',($b_encode) ? URLEncodeArray($m_params) : $m_params);
    }
    return ($s_url);
}
 
    //
    // Recursively trim an array of strings (non string values are converted
    // to a string first).
    //
function TrimArray($a_list)
{
    foreach ($a_list as $m_key=>$m_item)
        if (is_array($m_item))
            $a_list[$m_key] = TrimArray($m_item);
        elseif (is_scalar($m_item))
            $a_list[$m_key] = trim("$m_item");
        else
            $a_list[$m_key] = "";
    return ($a_list);
}
 
    //
    // Parse a derivation specification and return an array of
    // field names and operators.
    //
function ParseDerivation($a_form_data,$s_fld_spec,$s_name,&$a_errors)
{
    $a_deriv = array();
    while (($i_len = strlen($s_fld_spec)) > 0)
    {
            //
            // we support the following operators:
            //      +   concatenate with a single space between, but skip the space
            //          if the next field is empty
            //      *   concatenate with a single space between
            //      .   concatenate with no space between
            //
        $i_span = strcspn($s_fld_spec,'+*.');
        if ($i_span == 0)
        {
            $a_errors[] = $s_name;
            return (false);
        }
        $a_deriv[] = trim(substr($s_fld_spec,0,$i_span));
        if ($i_span < $i_len)
        {
            $a_deriv[] = substr($s_fld_spec,$i_span,1);
            $s_fld_spec = substr($s_fld_spec,$i_span+1);
        }
        else
            $s_fld_spec = "";
    }
    return ($a_deriv);
}
 
    //
    // Test if a character is an alphabetic.
    //
function IsAlpha($ch)
{
    return (strpos("abcdefghijklmnopqrstuvwxyz",strtolower($ch)) !== false);
}
 
    //
    // Test if a character is a digit.
    //
function IsNumeric($ch)
{
    return (strpos("0123456789",$ch) !== false);
}
 
    //
    // Test if a character is an alphanumeric
    //
function IsAlnum($ch)
{
    return (IsAlpha($ch) || IsNumeric($ch));
}
 
    //
    // Return an array of tokens extracted from the given string.
    // A token is:
    //  - a word (begins with alpha or _, and is followed by any number
    //    of alphanumerics or _ chars)
    //  - a number (any number of consecutive digits with up to one period)
    //  - a string enclosed in specified quotes (this can be disabled)
    //  - any punctuation character
    //
    // Anything not matching the above is silently ignored!
    //
function GetTokens($s_str,$s_quotes = "'\"")
{
    $b_allow_strings = ($s_quotes !== "") ? true : false;
    $ii = 0;
    $i_len = strlen($s_str);
    $a_toks = array();
 
    while ($ii < $i_len)
    {
        switch ($ch = $s_str{$ii})
        {
        case " ":
        case "\t":
        case "\n":
        case "\r":
            $ii++;
            continue;
        }
            //
            // start of a token
            //
        $i_start = $ii;
        if ($ch == "_" || IsAlpha($ch))
        {
                //
                // a word
                //
            $i_count = 1;
            while (++$ii < $i_len &&
                   ($s_str{$ii} == "_" || IsAlnum($s_str{$ii})))
                ++$i_count;
            $a_toks[] = substr($s_str,$i_start,$i_count);
        }
        elseif (($ch == "." && $ii < ($i_len-1) && IsNumeric($s_str{$ii+1}))||
                IsNumeric($ch))
        {
                //
                // a number
                //
            $b_had_dot = ($ch == ".");
            $i_count = 1;
            while (++$ii < $i_len)
            {
                if (IsNumeric($s_str{$ii}))
                    ++$i_count;
                elseif ($s_str{$ii} == "." && !$b_had_dot)
                {
                    ++$i_count;
                    $b_had_dot = true;
                }
                else
                    break;
            }
            $a_toks[] = substr($s_str,$i_start,$i_count);
        }
        elseif ($b_allow_strings && strpos($s_quotes,$ch) !== false)
        {
            $c_quote = $ch;
                //
                // a quoted string
                //
            while (++$ii < $i_len)
            {
                if ($s_str{$ii} == $c_quote)
                {
                    ++$ii;  // include the terminating quote
                    break;
                }
            }
            $a_toks[] = substr($s_str,$i_start,$ii-$i_start);
        }
        else
        {
            $s_punct = "~!@#$%^&*()-+={}[]|:;<>,.?/`\\";
            if (!$b_allow_strings)
                $s_punct .= "'\"";
            if (strpos($s_punct,$ch) !== false)
                $a_toks[] = $ch;
            ++$ii;
        }
    }
    return ($a_toks);
}
 
    //
    // Return the value from a derive_fields specification.
    // Specifications are in this format:
    //      %info%
    // where info is a predefined word or a literal in quotes
    // (e.g. 'the time is ')
    //
function ValueSpec($s_spec,$a_form_data,&$a_errors)
{
    global  $lNow;
 
    $s_value = "";
    switch (trim($s_spec))
    {
    case 'date':        // "standard" date format: DD-MMM-YYYY
        $s_value = date('d-M-Y',$lNow);
        break;
    case 'time':        // "standard" time format: HH:MM:SS
        $s_value = date('H:i:s',$lNow);
        break;
    case 'ampm':        // am or pm
        $s_value = date('a',$lNow);
        break;
    case 'AMPM':        // AM or PM
        $s_value = date('A',$lNow);
        break;
    case 'dom0':        // day of month with possible leading zero
        $s_value = date('d',$lNow);
        break;
    case 'dom':         // day of month with no leading zero
        $s_value = date('j',$lNow);
        break;
    case 'day':         // day name (abbreviated)
        $s_value = date('D',$lNow);
        break;
    case 'dayname':     // day name (full)
        $s_value = date('l',$lNow);
        break;
    case 'daysuffix':   // day number suffix for English (st for 1st, nd for 2nd, etc.)
        $s_value = date('S',$lNow);
        break;
    case 'moy0':        // month of year with possible leading zero
        $s_value = date('m',$lNow);
        break;
    case 'moy':         // month of year with no leading zero
        $s_value = date('n',$lNow);
        break;
    case 'month':       // month name (abbreviated)
        $s_value = date('M',$lNow);
        break;
    case 'monthname':   // month name (full)
        $s_value = date('F',$lNow);
        break;
    case 'year':        // year (two digits)
        $s_value = date('y',$lNow);
        break;
    case 'fullyear':    // year (full)
        $s_value = date('Y',$lNow);
        break;
    case 'rfcdate':     // date formatted according to RFC 822
        $s_value = date('r',$lNow);
        break;
    case 'tzname':      // timezone name
        $s_value = date('T',$lNow);
        break;
    case 'tz':          // timezone difference from Greenwich +NNNN or -NNNN
        $s_value = date('O',$lNow);
        break;
    case 'hour120':     // hour of day (01-12) with possible leading zero
        $s_value = date('h',$lNow);
        break;
    case 'hour240':     // hour of day (00-23) with possible leading zero
        $s_value = date('H',$lNow);
        break;
    case 'hour12':      // hour of day (1-12) with no leading zero
        $s_value = date('g',$lNow);
        break;
    case 'hour24':      // hour of day (0-23) with no leading zero
        $s_value = date('G',$lNow);
        break;
    case 'min':         // minute of hour (00-59)
        $s_value = date('i',$lNow);
        break;
    case 'sec':         // seconds of minute (00-59)
        $s_value = date('s',$lNow);
        break;
    default:
        if ($s_spec{0} == "'")
        {
                //
                // to get a quote, use 3 quotes:
                //      '''
                //
            if ($s_spec == "'''")
                $s_value = "'";
            elseif (substr($s_spec,-1,1) == "'")
                $s_value = substr($s_spec,1,-1);
            else
                    //
                    // missing final quote is OK
                    //
                $s_value = substr($s_spec,1);
        }
        elseif (strspn($s_spec,"0123456789ABCDEF") == 2)
        {
                //
                // insert the ASCII character corresponding to
                // the hexadecimal value
                //
            $i_val = intval(substr($s_spec,0,2),16);
            $s_value = chr($i_val);
        }
        else
        {
                //
                // look for supported functions, start by getting all
                // the tokens
                //
            $a_toks = GetTokens($s_spec);
            if (count($a_toks) > 0)
            {
                switch ($a_toks[0])
                {
                case "if":
                        //
                        // "if" function: test first field
                        //       if not empty, then use second field
                        //       else, use third field
                        //
                        // Example: if(fld1 ; fld2 ; fld3)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to test (first)
                        //      3               ;
                        //      4               the "then" spec (can be missing)
                        //      5               ;
                        //      6               the "else" spec (can be missing)
                        //      7               )
                        //
                    if (($n_tok = count($a_toks)) < 6 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ";" ||
                            $a_toks[$n_tok-1] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_IF_FMT))));
                    else
                    {
                        $b_ok = true;
                        $s_fld_name = $a_toks[2];
                        $s_then_spec = $s_else_spec = "";
                        for ($ii = 4 ; $ii < $n_tok && $a_toks[$ii] != ';' ; $ii++)
                            $s_then_spec .= $a_toks[$ii];
                        if ($ii == $n_tok)
                            $b_ok = false;
                        else
                        {
                                //
                                // Concatenate tokens until the ')'.
                                // This provides the "else" spec.
                                //
                            for ( ; ++$ii < $n_tok && $a_toks[$ii] != ')' ; )
                                $s_else_spec .= $a_toks[$ii];
                            if ($ii == $n_tok)
                                $b_ok = false;
                        }
                        if ($b_ok)
                        {
                            if (!TestFieldEmpty($s_fld_name,$a_form_data,$s_mesg))
                                $s_fld_spec = $s_then_spec;
                            else
                                $s_fld_spec = $s_else_spec;
                            $s_value = GetDerivedValue($a_form_data,$s_fld_spec);
                        }
                        else
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                            array("SPEC"=>$s_spec,
                                                  "MSG"=>GetMessage(MSG_DER_FUNC_IF_FMT))));
                    }
                    break;
                case "size":
                        //
                        // "size" function: return size of uploaded file
                        //
                        // Example: size(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name for the file upload
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_SIZE_FMT))));
                    elseif (($i_size = GetFileSize($a_toks[2])) !== false)
                        $s_value = "$i_size";
                    break;
                case "ext":
                        //
                        // "ext" function: return filename extension of uploaded file
                        //
                        // Example: ext(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name for the file upload
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_EXT_FMT))));
                    elseif (($s_name = GetFileName($a_toks[2])) !== false)
                    {
                        if (($i_pos = strrpos($s_name,".")) !== false)
                            $s_value = substr($s_name,$i_pos+1);
                    }
                    break;
                case "ucase":
                case "lcase":
                        //
                        // "ucase" and "lcase" functions: return field
                        // converted to upper or lower case
                        //
                        // Example: lcase(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to convert
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC1_FMT,
                                                    array("FUNC"=>$a_toks[0])))));
                    elseif ($a_toks[0] == "ucase")
                        $s_value = strtoupper(GetFieldValue($a_toks[2],$a_form_data));
                    else
                        $s_value = strtolower(GetFieldValue($a_toks[2],$a_form_data));
                    break;
                case "ltrim":
                case "rtrim":
                case "trim":
                        //
                        // trim functions: return field with whitespace removed
                        // from left (ltrim), right (rtrim), or both (trim)
                        // ends.
                        //
                        // Example: ltrim(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to trim
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC1_FMT,
                                              array("FUNC"=>$a_toks[0])))));
                    else
                        $s_value = $a_toks[0](GetFieldValue($a_toks[2],$a_form_data));
                    break;
                case "ltrim0":
                        //
                        // ltrim0 function: return field with blanks and
                        // leading 0's removed from the left.
                        //
                        // Example: ltrim0(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to trim
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC1_FMT,
                                              array("FUNC"=>$a_toks[0])))));
                    else
                    {
                        $s_value = GetFieldValue($a_toks[2],$a_form_data);
                        $s_value = ltrim($s_value);     // trim blanks on left
                        $i_len = strspn($s_value,"0");
                            //
                            // if the whole string is zeroes, make sure we leave
                            // one of them!
                            //
                        if ($i_len == strlen($s_value))
                            if (--$i_len < 0)
                                $i_len = 0;
                        $s_value = substr($s_value,$i_len);
                    }
                    break;
                case "nextnum":
                        //
                        // "nextnum" function: return a unique number (next number)
                        //
                        // Usage: nextnum[(pad[,base])]
                        //
                        // Examples:
                        //      %nextnum%
                        //      %nextnum(8)%
                        //      %nextnum(5;16)%
                        //
                        // You can provide a padding amount. In this case, the
                        // number is padded on the left with zeroes to the number
                        // of digits specified.
                        //
                        // You can also provide a base for your numbers.  Valid
                        // values for base are 2 to 36, inclusive.
                        //
                        // tokens are:
                        //      1               (
                        //      2               the padding amount
                        //      3               ;
                        //      4               the base
                        //      5               )
                        //
                    $i_pad = 0;     // no padding
                    $i_base = 10;   // base 10
                    if (($n_tok = count($a_toks)) > 1)
                    {
                        if (($n_tok != 4 && $n_tok != 6) ||
                            $a_toks[1] != "(" ||
                            $a_toks[$n_tok-1] != ")")
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T1)")));
                        if ($n_tok == 6 && $a_toks[3] != ";")
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T2)")));
                        if (!is_numeric($a_toks[2]) ||
                            ($n_tok == 6 && !is_numeric($a_toks[4])))
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T3)")));
                        $i_pad = intval($a_toks[2]);
                        if ($n_tok == 6)
                        {
                            $i_base = intval($a_toks[4]);
                            if ($i_base < 2 || $i_base > 36)
                            {
                                SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                            array("SPEC"=>$s_spec,
                                                  "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T4)")));
                                $i_base = 10;
                            }
                        }
                        $s_value = GetNextNum($i_pad,$i_base);
                    }
                    else
                    {
                        $s_value = GetNextNum($i_pad,$i_base);
                    }
                    break;
                default:
                    SendAlert(GetMessage(MSG_UNK_VALUE_SPEC,
                                    array("SPEC"=>$s_spec,"MSG"=>"")));
                    break;
                }
            }
            else
                SendAlert(GetMessage(MSG_UNK_VALUE_SPEC,array("SPEC"=>$s_spec,
                                                            "MSG"=>"")));
        }
        break;
    }
    return ($s_value);
}
 
    //
    // Return the next number or fail on error
    //
function GetNextNum($i_pad,$i_base)
{
    global  $NEXT_NUM_FILE,$php_errormsg;
 
    if (!isset($NEXT_NUM_FILE) || $NEXT_NUM_FILE === "")
    {
        ErrorWithIgnore("next_num_config",GetMessage(MSG_NO_NEXT_NUM_FILE));
        exit;
    }
    if (($fp = @fopen($NEXT_NUM_FILE,"r+")) === false)
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"open",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
    if (!flock($fp,defined("LOCK_EX") ? LOCK_EX : 2))
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"flock",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
        //
        // read the first line only
        //
    if (!feof($fp))
    {
        if (($s_line = fread($fp,1024)) === false)
            $i_next = 1;
        elseif (($i_next = intval($s_line)) <= 0)
            $i_next = 1;
    }
    else
        $i_next = 1;
    if (rewind($fp) == 0)
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"rewind",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
    $s_ret = strval($i_next++);
    if (fputs($fp,"$i_next\r\n") <= 0)
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"fputs",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
    fclose($fp);
    if ($i_base != 10)
    {
        $s_ret = base_convert($s_ret,10,$i_base);
        $s_ret = strtoupper($s_ret);    // always upper case if alphas are used
    }
    if ($i_pad != 0)
        $s_ret = str_pad($s_ret,$i_pad,"0",STR_PAD_LEFT);
    return ($s_ret);
}
 
    //
    // Return the value of an object or array as a string.
    //
function GetObjectAsString($m_value)
{
    ob_start();
    print_r($m_value);
    $s_ret = ob_get_contents();
    ob_end_clean();
    return ($s_ret);
}
 
    //
    // Return a Server or Environment variable value.  Returns false if
    // not found, otherwise a string value.
    //
function GetEnvValue($s_name)
{
    global  $aServerVars,$aEnvVars;
 
    if (isset($aEnvVars[$s_name]))
        $m_value = $aEnvVars[$s_name];
    elseif (isset($aServerVars[$s_name]))
        $m_value = $aServerVars[$s_name];
        //
        // some values might not be strings - so convert
        //
    if (isset($m_value) && !is_scalar($m_value))
        $m_value = GetObjectAsString($m_value);
    return (isset($m_value) ? ((string) $m_value) : false);
}
 
    //
    // Same as "empty" but checks for true emptiness if ZERO_IS_EMPTY is
    // set to false.
    //
function IsFieldEmpty($s_value)
{
    if (ZERO_IS_EMPTY || is_array($s_value))
        return (empty($s_value));
    else
        return ($s_value === "");
}
 
    //
    // Test if a field is set in the given vars array or in the uploaded
    // files.
    //
function IsFieldSet($s_fld,$a_main_vars)
{
    global  $aFileVars;
 
    return (isset($a_main_vars[$s_fld]) ||
            (FILEUPLOADS && isset($aFileVars[$s_fld])));
}
 
    //
    // Return the info for the uploaded file, or false on error.
    //
function GetFileInfo($s_fld)
{
    global  $aFileVars;
 
    if (FILEUPLOADS && isset($aFileVars[$s_fld]))
    {
        $a_upload = $aFileVars[$s_fld];
        if (isset($a_upload['tmp_name']) && !empty($a_upload['tmp_name']) &&
            isset($a_upload['name']) && !empty($a_upload['name']) &&
            IsUploadedFile($a_upload))
                return ($a_upload);
    }
    return (false);
}
 
    //
    // Return the original name of the uploaded file or false on error.
    //
function GetFileName($s_fld)
{
    if (($a_upload = GetFileInfo($s_fld)) !== false)
        return ($a_upload['name']);
    return (false);
}
 
    //
    // Return the size of the uploaded file or false on error.
    //
function GetFileSize($s_fld)
{
    if (($a_upload = GetFileInfo($s_fld)) !== false)
        return ($a_upload['size']);
    return (false);
}
 
    //
    // Return a field value.  Empty string is returned if the field is
    // not found. File fields return the original name of the uploaded file.
    //
function GetFieldValue($s_fld,$a_main_vars)
{
    if (!isset($a_main_vars[$s_fld]))
    {
        if (($s_name = GetFileName($s_fld)) === false)
            $s_name = "";
        return ($s_name);
    }
    return ((string) $a_main_vars[$s_fld]);
}
 
    //
    // Tests a field against an array of vars for emptyness.
    // If the var isn't found there, then the POSTed files array is checked.
    // Returns true if the field is empty (a specific error may
    // be returned in the $s_mesg parameter).
    //
function TestFieldEmpty($s_fld,$a_main_vars,&$s_mesg)
{
    global  $aFileVars;
 
    $s_mesg = "";
    $b_empty = TRUE;
    if (!isset($a_main_vars[$s_fld]))
    {
            //
            // Each file var is an array with these elements:
            //      'name' => The original name of the file on the client machine.
            //      'type' => The mime type of the file, if the browser provided this information.
            //      'tmp_name' => The temporary filename of the file in which the uploaded file was stored on the server.
            //      'error' => The error code associated with this file upload.
            //                  NOTE: 'error' was added in PHP 4.2.0
            //      'size' => The size, in bytes, of the uploaded file.
            //
            // Error codes (the constants are only available from PHP 4.3.0 so
            // we have to use the raw numbers):
            //  UPLOAD_ERR_OK
            //      Value: 0; There is no error, the file uploaded with success.
            //  UPLOAD_ERR_INI_SIZE
            //      Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
            //  UPLOAD_ERR_FORM_SIZE
            //      Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.
            //  UPLOAD_ERR_PARTIAL
            //      Value: 3; The uploaded file was only partially uploaded.
            //  UPLOAD_ERR_NO_FILE
            //      Value: 4; No file was uploaded.
            //
        if (FILEUPLOADS && isset($aFileVars[$s_fld]))
        {
            $a_upload = $aFileVars[$s_fld];
            if (isset($a_upload['tmp_name']) && !empty($a_upload['tmp_name']) &&
                isset($a_upload['name']) && !empty($a_upload['name']))
            {
                if (IsUploadedFile($a_upload))
                    $b_empty = false;
            }
            if ($b_empty && isset($a_upload['error']))
                switch ($a_upload['error'])
                {
                case 1:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR1);
                    break;
                case 2:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR2);
                    break;
                case 3:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR3);
                    break;
                case 4:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR4);
                    break;
                case 6:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR6);
                    break;
                case 7:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR7);
                    break;
                case 8:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR8);
                    break;
                default:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR_UNK,
                                    array("ERRNO"=>$a_upload['error']));
                    break;
                }
        }
    }
    else
        $b_empty = IsFieldEmpty($a_main_vars[$s_fld]);
    return ($b_empty);
}
 
    //
    // Return a derived field value or value specification.
    //
function GetDerivedValue($a_form_data,$s_word,&$a_errors)
{
    global  $aFileVars;
 
    $s_value = "";
        //
        // a field name or a value specification
        // value specifications have the following format:
        //      %spec%
        //
    if (substr($s_word,0,1) == '%')
    {
        if (substr($s_word,-1,1) != '%')
        {
            SendAlert(GetMessage(MSG_INV_VALUE_SPEC,array("SPEC"=>$s_word)));
            $s_value = $s_word;
        }
        else
        {
            $s_spec = substr($s_word,1,-1);
            $s_value = ValueSpec($s_spec,$a_form_data,$a_errors);
        }
    }
    else
    {
        $s_fld_name = $s_word;
            //
            // try form data first, then the environment/server data
            //
        if (IsFieldSet($s_fld_name,$a_form_data))
            $s_value = GetFieldValue($s_fld_name,$a_form_data);
        elseif (($s_value = GetEnvValue($s_fld_name)) === false)
            $s_value = "";
        $s_value = trim($s_value);
    }
    return ($s_value);
}
 
    //
    // Derive a value from the form data using the specification returned
    // from ParseDerivation.
    //
function DeriveValue($a_form_data,$a_value_spec,$s_name,&$a_errors)
{
    $s_value = "";
    for ($ii = 0 ; $ii < count($a_value_spec) ; $ii++)
    {
        switch ($a_value_spec[$ii])
        {
        case '+':
                //
                // concatenate with a single space between, but skip the space
                // if the next field is empty
                //
            if ($ii < count($a_value_spec)-1)
            {
                $s_temp = GetDerivedValue($a_form_data,$a_value_spec[$ii+1],$a_errors);
                if (!IsFieldEmpty($s_temp))
                    $s_value .= ' ';
            }
            break;
        case '.':
                //
                // concatenate with no space between
                //
            break;
        case '*':
                //
                // concatenate with a single space between
                //
            $s_value .= ' ';
            break;
        default:
                //
                // a field name or a value specification
                // value specifications have the following format:
                //      %name%
                //
            $s_value .= GetDerivedValue($a_form_data,$a_value_spec[$ii],$a_errors);
            break;
        }
    }
    return ($s_value);
}
 
    //
    // Create derived fields specified by the "derive_fields" value.
    //
function CreateDerived($a_form_data)
{
    if (isset($a_form_data["derive_fields"]))
    {
        $a_errors = array();
            //
            // get the list of derived field specifications
            //
        $a_list = TrimArray(explode(",",$a_form_data["derive_fields"]));
        foreach ($a_list as $s_fld_spec)
        {
            if ($s_fld_spec === "")
                    //
                    // silently ignore empty derivations
                    //
                continue;
            if (($i_pos = strpos($s_fld_spec,"=")) === false)
            {
                $a_errors[] = $s_fld_spec;
                continue;
            }
            $s_name = trim(substr($s_fld_spec,0,$i_pos));
            $s_fld_spec = substr($s_fld_spec,$i_pos+1);
 
            if (($a_value_spec = ParseDerivation($a_form_data,$s_fld_spec,
                                                $s_name,$a_errors)) === false)
                break;
            $a_form_data[$s_name] = DeriveValue($a_form_data,$a_value_spec,$s_name,$a_errors);
        }
        if (count($a_errors) > 0)
        {
            SendAlert(GetMessage(MSG_DERIVED_INVALID).implode("\n",$a_errors));
            Error("derivation_failure",GetMessage(MSG_INT_FORM_ERROR));
        }
    }
    return ($a_form_data);
}
 
    //
    // To process the name specification for files and update the
    // array of file variables accordingly.
    //
function SetFileNames($s_name_spec,$a_order,$a_fields,$a_raw_fields,$a_all_raw_values,$a_file_vars)
{
    $a_errors = array();
        //
        // get the list of file name derivations
        //
    $a_list = TrimArray(explode(",",$s_name_spec));
    foreach ($a_list as $s_fld_spec)
    {
        if ($s_fld_spec === "")
                //
                // silently ignore empty file name derivations
                //
            continue;
        if (($i_pos = strpos($s_fld_spec,"=")) === false)
        {
            $a_errors[] = $s_fld_spec;
            continue;
        }
        $s_name = trim(substr($s_fld_spec,0,$i_pos));
        $s_fld_spec = substr($s_fld_spec,$i_pos+1);
 
        if (($a_value_spec = ParseDerivation($a_raw_fields,$s_fld_spec,
                                            $s_name,$a_errors)) === false)
            break;
        if (isset($a_file_vars[$s_name]) && is_array($a_file_vars[$s_name]))
        {
                //
                // we create our own special entry in the file variable's data
                //
            $a_file_vars[$s_name]['new_name'] = DeriveValue($a_raw_fields,
                                                        $a_value_spec,$s_name,
                                                        $a_errors);
                //
                // we also create (derive) a new field called 'name_of_X'
                // where X is the file fields's name
                //
            ProcessField("name_of_$s_name",$a_file_vars[$s_name]['new_name'],
                        $a_order,$a_fields,$a_raw_fields);
            $a_all_raw_values["name_of_$s_name"] = $a_file_vars[$s_name]['new_name'];
        }
        /* This is annoying if a file upload is optional.  Just ignore missing
            file upload fields.
        else
            SendAlert(GetMessage(MSG_FILE_NAMES_NOT_FILE,
                                            array("NAME"=>$s_name)));*/
    }
    if (count($a_errors) > 0)
    {
        SendAlert(GetMessage(MSG_FILE_NAMES_INVALID).implode("\n",$a_errors));
        Error("file_names_derivation_failure",GetMessage(MSG_INT_FORM_ERROR));
    }
    return (array($a_order,$a_fields,$a_raw_fields,$a_all_raw_values,$a_file_vars));
}
 
    //
    // Process a list of attributes or options.
    // Format for each attribute/option:
    //      name
    // or
    //      name=value
    //
    // Values can be simple values or semicolon (;) separated lists:
    //          avalue
    //          value1;value2;value3;...
    //
    // Returns attribute/options in the associative array $a_attribs.
    // Optionally, valid attributes can be provided in $a_valid_attribs
    // (if empty, all attributes found are considered valid).
    // Errors are returned in $a_errors.
    //
function ProcessAttributeList($a_list,&$a_attribs,&$a_errors,
                        $a_valid_attribs = array())
{
    $b_got_valid_list = (count($a_valid_attribs) > 0);
    foreach ($a_list as $s_attrib)
    {
            //
            // if the name begins with '.' then silently ignore it;
            // this allows you to temporarily disable an option without
            // getting an alert message
            //
        if (($i_pos = strpos($s_attrib,"=")) === false)
        {
            $s_name = trim($s_attrib);
            if (empty($s_name) || $s_name{0} == '.')
                continue;
                //
                // option is a simple "present" value
                //
            $a_attribs[$s_name] = true;
        }
        else
        {
            $s_name = trim(substr($s_attrib,0,$i_pos));
            if (empty($s_name) || $s_name{0} == '.')
                continue;
            $s_value_list = substr($s_attrib,$i_pos+1);
            if (($i_pos = strpos($s_value_list,";")) === false)
                    //
                    // single value
                    //
                $a_attribs[$s_name] = trim($s_value_list);
            else
                    //
                    // list of values
                    //
                $a_attribs[$s_name] = TrimArray(explode(";",$s_value_list));
        }
        if ($b_got_valid_list && !isset($a_valid_attribs[$s_name]))
            $a_errors[] = $s_name;
    }
}
 
    //
    // Process the options specified in the form.
    // Options can be specified in this format:
    //          option1,option2,option3,...
    // Each option can be a simple word or a word and value:
    //          name
    //          name=value
    // No name or value can contain a comma.
    // Values can be simple values or semicolon (;) separated lists:
    //          avalue
    //          value1;value2;value3;...
    // No value can contain a semicolon.
    // Be careful of values beginning and ending with whitespace characters;
    // they will be trimmed.
    //
function ProcessOptions($s_name,$a_form_data,&$a_options,$a_valid_options)
{
    $a_errors = array();
    $a_options = array();
    if (isset($a_form_data[$s_name]))
    {
            //
            // get the options list and trim each one
            //
        $a_list = TrimArray(explode(",",$a_form_data[$s_name]));
        ProcessAttributeList($a_list,$a_options,$a_errors,$a_valid_options);
    }
    if (count($a_errors) > 0)
        SendAlert(GetMessage(MSG_OPTIONS_INVALID,array("OPT"=>$s_name)).
                    implode("\n",$a_errors));
}
 
    //
    // Process the mail_options specified in the form.
    //
function ProcessMailOptions($a_form_data)
{
    global  $MAIL_OPTS,$VALID_MAIL_OPTIONS;
 
    ProcessOptions("mail_options",$a_form_data,$MAIL_OPTS,$VALID_MAIL_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsMailOptionSet($s_name)
{
    global  $MAIL_OPTS;
 
    return (isset($MAIL_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetMailOption($s_name)
{
    global  $MAIL_OPTS;
 
    return (isset($MAIL_OPTS[$s_name]) ? $MAIL_OPTS[$s_name] : NULL);
}
 
    //
    // Process the crm_options specified in the form.
    //
function ProcessCRMOptions($a_form_data)
{
    global  $CRM_OPTS,$VALID_CRM_OPTIONS;
 
    ProcessOptions("crm_options",$a_form_data,$CRM_OPTS,$VALID_CRM_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsCRMOptionSet($s_name)
{
    global  $CRM_OPTS;
 
    return (isset($CRM_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetCRMOption($s_name)
{
    global  $CRM_OPTS;
 
    return (isset($CRM_OPTS[$s_name]) ? $CRM_OPTS[$s_name] : NULL);
}
 
    //
    // Check if a field is in the mail exclusion list.
    //
function IsMailExcluded($s_name)
{
    $a_list = GetMailOption("Exclude");
    if (!isset($a_list))
        return (false);
    if (is_array($a_list))
        return (in_array($s_name,$a_list));
    else
        return ($s_name === $a_list);
}
 
    //
    // Process the autorespond specified in the form.
    //
function ProcessAROptions($a_form_data)
{
    global  $AR_OPTS,$VALID_AR_OPTIONS;
 
    ProcessOptions("autorespond",$a_form_data,$AR_OPTS,$VALID_AR_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsAROptionSet($s_name)
{
    global  $AR_OPTS;
 
    return (isset($AR_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetAROption($s_name)
{
    global  $AR_OPTS;
 
    return (isset($AR_OPTS[$s_name]) ? $AR_OPTS[$s_name] : NULL);
}
 
    //
    // Process the mail_options specified in the form.
    //
function ProcessFilterOptions($a_form_data)
{
    global  $FILTER_OPTS,$VALID_FILTER_OPTIONS;
 
    ProcessOptions("filter_options",$a_form_data,$FILTER_OPTS,$VALID_FILTER_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsFilterOptionSet($s_name)
{
    global  $FILTER_OPTS;
 
    return (isset($FILTER_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetFilterOption($s_name)
{
    global  $FILTER_OPTS;
 
    return (isset($FILTER_OPTS[$s_name]) ? $FILTER_OPTS[$s_name] : NULL);
}
 
    //
    // Lookup a filter attribute for the given filter.
    // Return it's value or false if not set.
    //
function GetFilterAttrib($s_filter,$s_attrib)
{
    global  $FILTER_ATTRIBS,$FILTER_ATTRIBS_LOOKUP;
 
    if (!isset($FILTER_ATTRIBS[$s_filter]))
            //
            // no attributes for the filter
            //
        return (false);
    if (!isset($FILTER_ATTRIBS_LOOKUP[$s_filter]))
    {
            //
            // the attributes have not yet been parsed - create the lookup table
            //
        $a_list = TrimArray(explode(",",$FILTER_ATTRIBS[$s_filter]));
        $FILTER_ATTRIBS_LOOKUP[$s_filter] = array();
        $a_errors = array();
 
        ProcessAttributeList($a_list,$FILTER_ATTRIBS_LOOKUP[$s_filter],$a_errors);
    }
        //
        // perform the lookup and return the value
        //
    if (!isset($FILTER_ATTRIBS_LOOKUP[$s_filter][$s_attrib]))
        return (false);
    return ($FILTER_ATTRIBS_LOOKUP[$s_filter][$s_attrib]);
}
 
    //
    // Check the filter attributes for the given filter.
    // Return true if the given attribute is set otherwise false.
    //
function IsFilterAttribSet($s_filter,$s_attrib)
{
    return (GetFilterAttrib($s_filter,$s_attrib));
}
 
    //
    // Process the given .ini file.
    //
function ProcessFormIniFile($s_file)
{
    global  $EMAIL_ADDRS;
 
    $a_sections = parse_ini_file($s_file,TRUE);
    if (DB_SEE_INI)
    {
            //
            // just display the ini file
            //
        $s_text = "<p><b>The following settings were found in the file '$s_file':</b></p>";
        foreach ($a_sections as $s_sect=>$a_settings)
        {
            $s_text .= "<p>[$s_sect]\n";
            foreach ($a_settings as $s_name=>$s_value)
                $s_text .= "$s_name = \"$s_value\"\n";
            $s_text .= "</p>";
        }
        CreatePage($s_text);
        exit;
    }
        //
        // Load the email_addresses section.
        //
    if (isset($a_sections["email_addresses"]))
        $EMAIL_ADDRS = $a_sections["email_addresses"];
        //
        // Process special fields
        //
    if (isset($a_sections["special_fields"]))
    {
        foreach ($a_sections["special_fields"] as $s_name=>$m_value)
        {
            if (IsSpecialField($s_name))
                SetSpecialField($s_name,$m_value);
                //
                // check for multiple valued special fields
                //
            if (($a_multi_fld = IsSpecialMultiField($s_name)) !== false)
                SetSpecialMultiField($a_multi_fld[0],$a_multi_fld[1],$m_value);
        }
    }
}
 
    //
    // UnMangle an email address
    //
function UnMangle($email)
{
    global  $EMAIL_ADDRS;
 
        //
        // map from a name to the real email address
        //
    if (isset($EMAIL_ADDRS[$email]))
        $email = $EMAIL_ADDRS[$email];
        //
        // unmangle
        //
    if (AT_MANGLE != "")
        $email = str_replace(AT_MANGLE,"@",$email);
    return ($email);
}
 
    //
    // Check a list of email addresses (comma separated); returns a list
    // of valid email addresses (comma separated).
    // The return value is true if there is at least one valid email address.
    //
function CheckEmailAddress($s_addr,&$s_valid,&$s_invalid)
{
    global  $TARGET_EMAIL;
 
    $s_invalid = $s_valid = "";
    $a_list = TrimArray(explode(",",$s_addr));
    $a_invalid = array();
    $n_empty = 0;
    for ($ii = 0 ; $ii < count($a_list) ; $ii++)
    {
        if ($a_list[$ii] === "")
        {
                //
                // ignore, but count empty addresses
                //
            $n_empty++;
            continue;
        }
        $s_email = UnMangle($a_list[$ii]);
            //
            // UnMangle works with INI files too, and a single
            // word can expand to a list of email addresses.
            //
        $a_this_list = TrimArray(explode(",",$s_email));
        foreach ($a_this_list as $s_email)
        {
            if ($s_email === "")
            {
                    //
                    // ignore, but count empty addresses
                    //
                $n_empty++;
                continue;
            }
            $b_is_valid = false;
            for ($jj = 0 ; $jj < count($TARGET_EMAIL) ; $jj++)
                if (eregi($TARGET_EMAIL[$jj],$s_email))
                {
                    if (empty($s_valid))
                        $s_valid = $s_email;
                    else
                        $s_valid .= ",".$s_email;
                    $b_is_valid = true;
                    break;
                }
            if (!$b_is_valid)
                $a_invalid[] = $s_email;
        }
    }
        //
        // just ignore empty recipients unless there are *no* valid recipients
        //
    if (empty($s_valid) && $n_empty > 0)
        $a_invalid[] = GetMessage(MSG_EMPTY_ADDRESSES,array("COUNT"=>$n_empty));
    if (count($a_invalid) > 0)
        $s_invalid = implode(",",$a_invalid);
    return (!empty($s_valid));
}
 
    //
    // Redirect to another URL
    //
function Redirect($url)
{
        //
        // for browsers without cookies enabled, append the Session ID
        //
    if (session_id() !== "")
        $url = AddURLParams($url,session_name()."=".urlencode(session_id()));
    if (defined("SID"))
        $url = AddURLParams($url,SID);
 
        //
        // this is probably a good idea to ensure the session data
        // is written away
        //
    if (function_exists('session_write_close'))
        session_write_close();
 
    header("Location: $url");
        //
        // if the header doesn't work, try JavaScript.
        // if that doesn't work, provide a manual link
        //
    $s_text = GetMessage(MSG_PLSWAIT_REDIR)."\n\n";
    $s_text .= "<script language=\"JavaScript\" type=\"text/javascript\">";
    $s_text .= "window.location.href = '$url';";
    $s_text .= "</script>";
    $s_text .= "\n\n".GetMessage(MSG_IFNOT_REDIR,array("URL"=>$url));
    CreatePage($s_text);
    exit;
}
 
    //
    // JoinLines is just like "implode" except that it checks
    // the end of each array for the separator already being
    // there. This allows us to join a mixture of mail
    // header lines (already terminated) with body lines.
    // This logic works if HEAD_CRLF, for example, is the same
    // as BODY_LF (i.e. both "\r\n") or if BODY_LF is the
    // same as the last character in HEAD_CRLF (i.e.
    // HEAD_CRLF = "\r\n" and BODY_LF = "\n").
    // Other value combinations may break things.
    //
function JoinLines($s_sep,$a_lines)
{
    $s_str = "";
    if (($i_sep_len = strlen($s_sep)) == 0)
            //
            // no separator
            //
        return (implode("",$a_lines));
    $n_lines = count($a_lines);
    for ($ii = 0 ; $ii < $n_lines ; $ii++)
    {
        $s_line = $a_lines[$ii];
        if (substr($s_line,-$i_sep_len) == $s_sep)
            $s_str .= $s_line;
        else
        {
            $s_str .= $s_line;
                //
                // don't append a separator to the last line
                //
            if ($ii < $n_lines-1)
                $s_str .= $s_sep;
        }
    }
    return ($s_str);
}
 
    //
    // Expands an array of mail headers into mail header lines.
    //
function ExpandMailHeaders($a_headers)
{
    $s_hdrs = "";
    foreach ($a_headers as $s_name=>$s_value)
        if ($s_name != "")
        {
            if ($s_hdrs != "")
                $s_hdrs .= HEAD_CRLF;
            $s_hdrs .= $s_name.": ".$s_value;
        }
    return ($s_hdrs);
}
 
    //
    // Expands an array of mail headers into an array containing header lines.
    //
function ExpandMailHeadersArray($a_headers)
{
    $a_hdrs = array();
    foreach ($a_headers as $s_name=>$s_value)
        if ($s_name != "")
            $a_hdrs[] = $s_name.": ".$s_value.HEAD_CRLF;
    return ($a_hdrs);
}
 
    //
    // Low-level email send function; either calls PHP's mail function
    // or uses the PEAR Mail object.
    // NOTE: for some errors, there's no point trying to email
    // an alert message!  So, in these cases, we just display the error to
    // the user.
    //
function DoMail($s_to,$s_subject,$s_mesg,$a_headers)
{
    global  $PEAR_SMTP_HOST,$PEAR_SMTP_PORT,$PEAR_SMTP_USER,$PEAR_SMTP_PWD;
 
    if (isset($PEAR_SMTP_HOST) && !empty($PEAR_SMTP_HOST))
    {
        require_once("Mail.php");
 
        $a_params = array(  "host"=>$PEAR_SMTP_HOST,
                            "port"=>$PEAR_SMTP_PORT);
        if (isset($PEAR_SMTP_USER) && !empty($PEAR_SMTP_USER))
        {
            $a_params["auth"] = TRUE;
            $a_params["username"] = $PEAR_SMTP_USER;
            $a_params["password"] = $PEAR_SMTP_PWD;
        }
        $mailer = Mail::factory("smtp",$a_params);
        if (!is_object($mailer))
        {
            ShowError("pear_error",GetMessage(MSG_PEAR_OBJ),FALSE,FALSE);
            exit;
        }
        if (get_class($mailer) === 'pear_error')
        {
            ShowError("pear_error",$mailer->getMessage(),FALSE,FALSE);
            exit;
        }
        if (!isset($a_headers['To']) && !isset($a_headers['to']))
            $a_headers['To'] = $s_to;
        if (!isset($a_headers['Subject']) && !isset($a_headers['subject']))
            $a_headers['Subject'] = $s_subject;
        $res = $mailer->send($s_to,$a_headers,$s_mesg);
        if ($res === TRUE)
            return (TRUE);
 
        global  $aAlertInfo;
 
        $aAlertInfo[] = GetMessage(MSG_PEAR_ERROR,array("MSG"=>$res->getMessage()));
        return (FALSE);
    }
    return (mail($s_to,$s_subject,$s_mesg,ExpandMailHeaders($a_headers)));
}
 
    //
    // Send an email
    //
function SendCheckedMail($to,$subject,$mesg,$sender,$a_headers = array())
{
    global  $PEAR_SMTP_HOST;
 
    $b_f_option = false;
    $b_form_option = IsMailOptionSet("SendMailFOption");    // this is superseded, but still supported
    if (SENDMAIL_F_OPTION || $b_form_option)
    {
        if (empty($sender))
        {
                //
                // SENDMAIL_F_OPTION with no sender is silently ignored
                //
            if ($b_form_option)
            {
                    //
                    // form has specified SendMailFOption, but there's no
                    // sender address
                    //
                static  $b_in_here = false;
                global  $SERVER;
 
                if (!$b_in_here)        // prevent infinite recursion
                {
                    $b_in_here = true;
                    SendAlert(GetMessage(MSG_NO_FOPT_ADDR));
                    $b_in_here = false;
                }
                    //
                    // if there's no from address, create a dummy one
                    //
                $sender = "dummy@".(isset($SERVER) ? $SERVER : "UnknownServer");
                $a_headers['From'] = $sender;
                $b_f_option = true;
            }
        }
        else
            $b_f_option = true;
    }
    if (INI_SET_FROM && !empty($sender))
        ini_set('sendmail_from',$sender);
 
    if ((!isset($PEAR_SMTP_HOST) || empty($PEAR_SMTP_HOST)) && $b_f_option)
        return (mail($to,$subject,$mesg,ExpandMailHeaders($a_headers),"-f$sender"));
    else
        return (DoMail($to,$subject,$mesg,$a_headers));
}
 
    //
    // Send an alert email
    //
function SendAlert($s_error,$b_filter = true,$b_non_error = false)
{
    global  $SPECIAL_VALUES,$FORMATTED_INPUT,$FROM_USER,$aServerVars,$aStrippedFormVars;
    global  $aAlertInfo,$aCleanedValues,$aFieldOrder;
 
    $s_error = str_replace("\n",BODY_LF,$s_error);
    $b_got_filter = (isset($SPECIAL_VALUES["filter"]) && !empty($SPECIAL_VALUES["filter"]));
 
        //
        // if there is a filter specified and we're not sending the alert
        // through the filter, don't show the user's data.  This is
        // on the assumption that the filter is an encryption program; so,
        // we don't want to send the user's data in clear text inside the
        // alerts.
        //
    $b_show_data = true;
    if ($b_got_filter && !$b_filter)
        $b_show_data = false;
 
    $s_form_subject = $s_alert_to = "";
    $b_check = true;
        //
        // might be too early to have $SPECIAL_VALUES set, so
        // look in the form vars too
        //
    if (isset($SPECIAL_VALUES["alert_to"]))
        $s_alert_to = trim($SPECIAL_VALUES["alert_to"]);
    if (empty($s_alert_to) && isset($aStrippedFormVars["alert_to"]))
        $s_alert_to = trim($aStrippedFormVars["alert_to"]);
 
    if (isset($SPECIAL_VALUES["subject"]))
        $s_form_subject = trim($SPECIAL_VALUES["subject"]);
    if (empty($s_form_subject) && isset($aStrippedFormVars["subject"]))
        $s_form_subject = trim($aStrippedFormVars["subject"]);
 
    if (empty($s_alert_to))
    {
        $s_alert_to = DEF_ALERT;
        $b_check = false;
    }
    if (!empty($s_alert_to))
    {
        $s_from_addr = $s_from = "";
        $a_headers = array();
        if (isset($FROM_USER) && !empty($FROM_USER))
        {
            if ($FROM_USER != "NONE")
            {
                $a_headers['From'] = $FROM_USER;
                $s_from = "From: $FROM_USER";
                $s_from_addr = $FROM_USER;
            }
        }
        else
        {
            global  $SERVER;
 
            $s_from_addr = "FormMail@".$SERVER;
            $a_headers['From'] = $s_from_addr;
            $s_from = "From: $s_from_addr";
        }
        $s_mesg = "To: ".UnMangle($s_alert_to).BODY_LF;
        if (!empty($s_from))
            $s_mesg .= $s_from.BODY_LF;
        $s_mesg .= BODY_LF;
        if (count($aAlertInfo) > 0)
        {
            if ($b_show_data)
            {
                $s_error .= BODY_LF.GetMessage(MSG_MORE_INFO).BODY_LF;
                $s_error .= implode(BODY_LF,$aAlertInfo);
            }
            else
                $s_error .= BODY_LF.GetMessage(MSG_INFO_STOPPED).BODY_LF;
        }
            //
            // some fields aren't security issues - show those in the alert
            //
        $a_safe_fields = array(
                    "email: ".$SPECIAL_VALUES["email"],
                    "realname: ".$SPECIAL_VALUES["realname"],
                        );
        $s_safe_data = implode(BODY_LF,$a_safe_fields);
 
        if ($b_non_error)
        {
            $s_preamble = $s_error.BODY_LF.BODY_LF;
            $s_mesg .= $s_preamble;
            $s_subj = GetMessage(MSG_FM_ALERT);
            if (!empty($s_form_subject))
                $s_subj .= " ($s_form_subject)";
        }
        else
        {
            $s_preamble = GetMessage(MSG_FM_ERROR_LINE).BODY_LF.
                            $s_error.BODY_LF.BODY_LF;
            $s_mesg .= $s_preamble;
            $s_subj = GetMessage(MSG_FM_ERROR);
            if (!empty($s_form_subject))
                $s_subj .= " ($s_form_subject)";
            $s_mesg .= $s_safe_data;
            $s_mesg .= BODY_LF.BODY_LF;
            if ($b_show_data)
                $s_mesg .= implode(BODY_LF,$FORMATTED_INPUT);
            else
                $s_mesg .= GetMessage(MSG_USERDATA_STOPPED);
        }
            
            /*
             * We only need to filter the form fields if the filter that
             * is specified is an encrypting filter.
             */
        if ($b_filter && $b_got_filter &&
                IsFilterAttribSet($SPECIAL_VALUES["filter"],"Encrypts"))
        {
            $s_new_mesg = $s_preamble.$s_safe_data;
            $s_new_mesg .= BODY_LF.BODY_LF;
 
            $s_filter = $SPECIAL_VALUES["filter"];
 
            if (($a_filter_list = GetFilterList()) !== false)
            {
                    //
                    // just filter the critical fields
                    //
                list($s_unfiltered,$s_filtered_results) =
                            GetFilteredOutput($aFieldOrder,$aCleanedValues,
                                    $s_filter,$a_filter_list);
                $s_new_mesg .= $s_unfiltered;
            }
            else
            {
                    //
                    // filter everything
                    //
                $s_filtered_results = Filter($s_filter,$s_mesg);
            }
            $s_new_mesg .= GetMessage(MSG_FILTERED,array("FILTER"=>$s_filter)).
                            BODY_LF.BODY_LF.
                            $s_filtered_results;
            $s_mesg = $s_new_mesg;
        }
        if (isset($aServerVars['HTTP_REFERER']))
            $s_mesg .= BODY_LF.BODY_LF."Referring page was ".$aServerVars['HTTP_REFERER'];
        elseif (isset($SPECIAL_VALUES['this_form']) && $SPECIAL_VALUES['this_form'] !== "")
            $s_mesg .= BODY_LF.BODY_LF."Referring form was ".$SPECIAL_VALUES['this_form'];
 
        if (isset($aServerVars['REMOTE_ADDR']))
            $s_mesg .= BODY_LF.BODY_LF."User IP address was ".$aServerVars['REMOTE_ADDR'];
 
        if ($b_check)
        {
            if (CheckEmailAddress($s_alert_to,$s_valid,$s_invalid))
                return (SendCheckedMail($s_valid,$s_subj,$s_mesg,$s_from_addr,$a_headers));
        }
        else
            return (SendCheckedMail($s_alert_to,$s_subj,$s_mesg,$s_from_addr,$a_headers));
    }
    return (false);
}
 
    //
    // Read the lines in a file and return an array.
    // Each line is stripped of line termination characters.
    //
function ReadLines($fp)
{
    $a_lines = array();
    while (!feof($fp))
    {
        $s_line = fgets($fp,4096);
            //
            // strip carriage returns and line feeds
            //
        $s_line = str_replace("\r","",$s_line);
        $s_line = str_replace("\n","",$s_line);
        $a_lines[] = $s_line;
    }
    return ($a_lines);
}
 
    //
    // Open a URL and return the data from it as a string.
    // Returns false on failure ($s_error has the error string)
    //
function GetURL($s_url,&$s_error)
{
    global  $php_errormsg,$aServerVars,$FM_VERS;
    global  $AUTHENTICATE,$AUTH_USER,$AUTH_PW;
 
        //
        // open the URL with the same session as we have
        //
    if (session_id() !== "")
        $s_url = AddURLParams($s_url,session_name()."=".urlencode(session_id()));
    if (defined("SID"))
        $s_url = AddURLParams($s_url,SID);
        //
        // parse the URL to get the component parts
        //
    $a_parts = parse_url($s_url);
        //
        // must have a host
        //
    if (!isset($a_parts["host"]))
    {
        $s_error = GetMessage(MSG_URL_PARSE);
        return (false);
    }
    $s_host_hdr = $a_parts["host"];
        //
        // if no port number is given, we support http and https
        //
    if (!isset($a_parts["port"]))
    {
        if (!isset($a_parts["scheme"]) || strtolower($a_parts["scheme"]) == "http")
            $a_parts["port"] = 80;
        elseif (strtolower($a_parts["scheme"]) == "https")
            $a_parts["port"] = 443;
        else
        {
           $s_error = GetMessage(MSG_URL_SCHEME,
                                    array("SCHEME"=>$a_parts["scheme"]));
           return (false);
        }
    }
    if ($a_parts["port"] == 443)
            //
            // fsockopen requires ssl:// in the host name
            //
        $a_parts["host"] = "ssl://".$a_parts["host"];
 
        //
        // default the path if empty
        //
    if (!isset($a_parts["path"]) || $a_parts["path"] === "")
        $a_parts["path"] = "/";
 
    $f_sock = @fsockopen($a_parts["host"],(int) $a_parts["port"],$i_errno,$s_errstr,30);
    if ($f_sock === false)
    {
        $s_error = GetMessage(MSG_SOCKET,
                            array("ERRNO"=>$i_errno,
                                "ERRSTR"=>$s_errstr,
                                "PHPERR"=>isset($php_errormsg) ? $php_errormsg : ""));
        return (false);
    }
 
    $s_req = $a_parts["path"];
        //
        // add the query to the path
        // Note that parse_url decodes the query string (urldecode), so
        // we need to split it into its component parameters
        // are re-encode their values.  Calling urlencode($a_parts["query"])
        // encodes the '=' between parameters and this breaks things.
        //
    if (isset($a_parts["query"]))
    {
        $a_params = explode('&',$a_parts["query"]);
        foreach ($a_params as $i_idx=>$s_param)
        {
            if (($i_pos = strpos($s_param,"=")) === false)
                $a_params[$i_idx] = urlencode($s_param);
            else
                $a_params[$i_idx] = substr($s_param,0,$i_pos).'='.
                                        urlencode(substr($s_param,$i_pos+1));
        }
        $s_req .= '?'.implode('&',$a_params);
    }
 
        //
        // add the fragment to the path.  Note, however, this
        // won't actually make the user's browser jump to that
        // location (because we'd need to alter our current URL
        // and add the fragment to achieve that - we might
        // add that feature in a later version if we can
        // figure out how to do it!)
        //
    if (isset($a_parts["fragment"]))
        $s_req .= '#'.urlencode($a_parts["fragment"]);
 
        //
        // Since we might be opening a URL within the same session, we can
        // get locks.  So, close the session for writing to prevent this.
        //
    if (function_exists('session_write_close'))
    {
        session_write_close();
        ob_flush();             // probably a good idea
    }
        //
        // the GET request
        //
    fputs($f_sock,"GET ".$s_req." HTTP/1.0\r\n");
 
        //
        // Determine authentication requirements
        //
    if ($AUTHENTICATE !== "" || $AUTH_USER !== "" || $AUTH_PW !== "")
    {
        if ($AUTHENTICATE === "")
            fputs($f_sock,"Authorization: Basic ".
                        base64_encode("$AUTH_USER:$AUTH_PW")."\r\n");
        else
            fputs($f_sock,"Authorization: $AUTHENTICATE\r\n");
 
    }
    else
    {
        if (isset($a_parts["user"]) || isset($a_parts["pass"]))
        {
            $s_auth_user = isset($a_parts["user"]) ? $a_parts["user"] : "";
            $s_auth_pass = isset($a_parts["pass"]) ? $a_parts["pass"] : "";
        }
        else
        {
            $s_auth_type = isset($aServerVars["PHP_AUTH_TYPE"]) ? $aServerVars["PHP_AUTH_TYPE"] : "";
            $s_auth_user = isset($aServerVars["PHP_AUTH_USER"]) ? $aServerVars["PHP_AUTH_USER"] : "";
            $s_auth_pass = isset($aServerVars["PHP_AUTH_PW"]) ? $aServerVars["PHP_AUTH_PW"] : "";
        }
        if (!isset($s_auth_type) || $s_auth_type === "")
            $s_auth_type = "Basic";
            //
            // Add the authentication header
            //
        if ($s_auth_user !== "" || $s_auth_pass !== "")
            fputs($f_sock,"Authorization: $s_auth_type ".
                        base64_encode("$s_auth_user:$s_auth_pass")."\r\n");
    }
 
        //
        // Specify the host name
        //
    fputs($f_sock,"Host: $s_host_hdr\r\n");
        //
        // Specify the user agent
        //
    fputs($f_sock,"User-Agent: FormMail/$FM_VERS (from www.tectite.com)\r\n");
        //
        // Accept any output
        //
    fputs($f_sock,"Accept: */*\r\n");
        //
        // End of request headers
        //
    fputs($f_sock,"\r\n");
 
        //
        // Read and parse the response header
        //
    $i_http_code = 0;
    $s_status = "";
    while (!feof($f_sock))
    {
        $s_line = fgets($f_sock,4096);
        if ($s_line == "\r\n" || $s_line == "\n")
            break;
        if (substr($s_line,0,4) == "HTTP")
        {
            $i_pos = strpos($s_line," ");
            $s_status = substr($s_line,$i_pos+1);
            $i_end_pos = strpos($s_status," ");
            if ($i_end_pos === false)
                $i_end_pos = strlen($s_status);
            $i_http_code = (int) substr($s_status,0,$i_end_pos);
        }
    }
    if ($i_http_code < 200 || $i_http_code > 299)
    {
        $s_error = GetMessage(MSG_GETURL_OPEN,array("STATUS"=>$s_status));
        $m_buf = false;
    }
    else
    {
            //
            // read content into one big string buffer and return
            //
        $m_buf = "";
        while (!feof($f_sock))
            $m_buf .= fread($f_sock,1024);
    }
    fclose($f_sock);
        //
        // re-open our session
        //
    session_start();
    return ($m_buf);
}
 
    //
    // Load a template file into a string.
    //
function LoadTemplate($s_name,$s_dir,$s_url,$b_ret_lines = false)
{
    global  $php_errormsg;
 
    $s_buf = "";
    $a_lines = array();
    if (!empty($s_dir))
    {
        $s_name = "$s_dir/".basename($s_name);
@       $fp = fopen($s_name,"r");
        if ($fp === false)
        {
            SendAlert(GetMessage(MSG_OPEN_TEMPLATE,array("NAME"=>$s_name,
                                                    "ERROR"=>CheckString($php_errormsg))));
            return (false);
        }
        if ($b_ret_lines)
            $a_lines = ReadLines($fp);
        else
                //
                // load the whole template into a string
                //
            $s_buf = fread($fp,filesize($s_name));
        fclose($fp);
    }
    else
    {
        global  $aServerVars;
 
        $s_name = "$s_url/".basename($s_name);
        if (isset($aServerVars['HTTP_USER_AGENT']))
            $s_name = AddURLParams($s_name,"USER_AGENT=".$aServerVars['HTTP_USER_AGENT']);
 
            //
            // open the URL with the same session as we have
            //
        if (session_id() !== "")
            $s_name = AddURLParams($s_name,session_name()."=".urlencode(session_id()));
        if (defined("SID"))
            $s_name = AddURLParams($s_name,SID);
 
            //
            // Since we might be opening a URL within the same session, we can
            // get locks.  So, close the session for writing to prevent this.
            //
        if (function_exists('session_write_close'))
        {
            session_write_close();
            ob_flush();             // probably a good idea
        }
 
@       $fp = fopen($s_name,"r");
        if ($fp === false)
        {
            SendAlert(GetMessage(MSG_OPEN_TEMPLATE,array("NAME"=>$s_name,
                                                    "ERROR"=>CheckString($php_errormsg))));
            return (false);
        }
        if ($b_ret_lines)
            $a_lines = ReadLines($fp);
        else
                //
                // load the whole template into a string
                //
            while (!feof($fp))
                $s_buf .= fread($fp,4096);
        fclose($fp);
            //
            // now re-open our session
            //
        session_start();
    }
    return ($b_ret_lines ? $a_lines : $s_buf);
}
 
    //
    // To show an error template.  The template must be HTML and, for security
    // reasons, must be a file on the server in the directory specified
    // by $TEMPLATEDIR or $TEMPLATEURL.
    // $a_specs is an array of substitutions to perform, as follows:
    //      tag-name    replacement string
    //
    // For example:
    //      "fmerror"=>"An error message"
    //
function ShowErrorTemplate($s_name,$a_specs,$b_user_error)
{
    global  $TEMPLATEURL,$TEMPLATEDIR;
 
    if (empty($TEMPLATEDIR) && empty($TEMPLATEURL))
    {
        SendAlert(GetMessage(MSG_TEMPLATES));
        return (false);
    }
    if (($s_buf = LoadTemplate($s_name,$TEMPLATEDIR,$TEMPLATEURL)) === false)
        return (false);
 
        //
        // now look for the tags to replace
        //
    foreach ($a_specs as $s_tag=>$s_value)
            //
            // search for
            //      <tagname/>
            // with optional whitespace
            //
        $s_buf = preg_replace('/<\s*'.preg_quote($s_tag,"/").'\s*\/\s*>/ims',
                            nl2br($s_value),$s_buf);
    if ($b_user_error)
    {
            // strip any <fmusererror> and </fmusererror> tags
            //
            // You can show information that's specific to user
            // errors between these special tags.
            //
        $s_buf = preg_replace('/<\s*\/?\s*fmusererror\s*>/ims','',$s_buf);
            //
            // since this isn't a system error, strip anything between
            // <fmsyserror> and </fmsyserror>
            //
        $s_buf = preg_replace('/<\s*fmsyserror\s*>.*<\s*\/\s*fmsyserror\s*>/ims','',$s_buf);
    }
    else
    {
            // strip any <fmsyserror> and </fmsyserror> tags
            //
            // You can show information that's specific to system
            // errors between these special tags.
            //
        $s_buf = preg_replace('/<\s*\/?\s*fmsyserror\s*>/ims','',$s_buf);
            //
            // since this isn't a user error, strip anything between
            // <fmusererror> and </fmusererror>
            //
        $s_buf = preg_replace('/<\s*fmusererror\s*>.*<\s*\/\s*fmusererror\s*>/ims','',$s_buf);
    }
        //
        // just output the page
        //
    echo $s_buf;
    return (true);
}
 
    //
    // To show an error to the user.
    //
function ShowError($error_code,$error_mesg,$b_user_error,
                $b_alerted = false,$a_item_list = array(),$s_extra_info = "")
{
    global  $SPECIAL_FIELDS,$SPECIAL_MULTI,$SPECIAL_VALUES;
    global  $aServerVars,$aSessionVars,$aStrippedFormVars;
 
        //
        // Testing with PHP 4.0.6 indicates that sessions don't always work.
        // So, we'll also add the error to the URL, unless
        // PUT_DATA_IN_URL is false.
        //
    $aSessionVars["FormError"] = $error_mesg;
    $aSessionVars["FormErrorInfo"] = $s_extra_info;
    $aSessionVars["FormErrorCode"] = $error_code;
    $aSessionVars["FormErrorItems"] = $a_item_list;
    $aSessionVars["FormIsUserError"] = $b_user_error;
    $aSessionVars["FormAlerted"] = $b_alerted;
    $aSessionVars["FormData"] = array();
 
    $bad_url = $SPECIAL_VALUES["bad_url"];
    $bad_template = $SPECIAL_VALUES["bad_template"];
    $this_form = $SPECIAL_VALUES["this_form"];
    if (!empty($bad_url))
    {
        $a_params = array();
        $a_params[] = "this_form=".urlencode("$this_form");
        $a_params[] = "bad_template=".urlencode("$bad_template");
        if (PUT_DATA_IN_URL)
        {
            $a_params[] = "error=".urlencode("$error_mesg");
            $a_params[] = "extra=".urlencode("$s_extra_info");
            $a_params[] = "errcode=".urlencode("$error_code");
            $a_params[] = "isusererror=".($b_user_error ? "1" : "0");
            $a_params[] = "alerted=".($b_alerted ? "1" : "0");
            $i_count = 1;
            foreach ($a_item_list as $s_item)
            {
                $a_params[] = "erroritem$i_count=".urlencode("$s_item");
                $i_count++;
            }
        }
        else
                //
                // tell the bad_url to look in the session only
                //
            $a_params[] = "insession=1";
            //
            // Add the posted data to the URL so that an intelligent
            // $bad_url can call the form again
            //
        foreach ($aStrippedFormVars as $s_name=>$m_value)
        {
                //
                // skip special fields
                //
            $b_special = false;
            if (in_array($s_name,$SPECIAL_FIELDS))
                $b_special = true;
            else
            {
                foreach ($SPECIAL_MULTI as $s_multi_fld)
                {
                    $i_len = strlen($s_multi_fld);
                    if (substr($s_name,0,$i_len) == $s_multi_fld)
                    {
                        $i_index = (int) substr($s_name,$i_len);
                        if ($i_index > 0)
                        {
                            $b_special = true;
                            break;
                        }
                    }
                }
            }
            if (!$b_special)
            {
                if (PUT_DATA_IN_URL)
                {
                    if (is_array($m_value))
                        foreach ($m_value as $s_value)
                            $a_params[] = "$s_name".'[]='.
                                        urlencode(substr($s_value,0,MAXSTRING));
                    else
                        $a_params[] = "$s_name=".urlencode(substr($m_value,0,MAXSTRING));
                }
                else
                {
                    if (is_array($m_value))
                        $aSessionVars["FormData"]["$s_name"] = $m_value;
                    else
                        $aSessionVars["FormData"]["$s_name"] = substr($m_value,0,MAXSTRING);
                }
            }
        }
            //
            // Now add the authentication data, if any
            //
        if ((isset($aServerVars["PHP_AUTH_USER"]) &&
                $aServerVars["PHP_AUTH_USER"] !== "") ||
            (isset($aServerVars["PHP_AUTH_PW"]) &&
                $aServerVars["PHP_AUTH_PW"] !== ""))
        {
            if (PUT_DATA_IN_URL)
            {
                if (isset($aServerVars["PHP_AUTH_USER"]))
                    $a_params[] = "PHP_AUTH_USER=".urlencode($aServerVars["PHP_AUTH_USER"]);
 
                if (isset($aServerVars["PHP_AUTH_PW"]))
                    $a_params[] = "PHP_AUTH_PW=".urlencode($aServerVars["PHP_AUTH_PW"]);
 
                if (isset($aServerVars["PHP_AUTH_TYPE"]))
                    $a_params[] = "PHP_AUTH_TYPE=".urlencode($aServerVars["PHP_AUTH_TYPE"]);
            }
            else
            {
                if (isset($aServerVars["PHP_AUTH_USER"]))
                    $aSessionVars["FormData"]["PHP_AUTH_USER"] = $aServerVars["PHP_AUTH_USER"];
 
                if (isset($aServerVars["PHP_AUTH_PW"]))
                    $aSessionVars["FormData"]["PHP_AUTH_PW"] = $aServerVars["PHP_AUTH_PW"];
 
                if (isset($aServerVars["PHP_AUTH_TYPE"]))
                    $aSessionVars["FormData"]["PHP_AUTH_TYPE"] = $aServerVars["PHP_AUTH_TYPE"];
            }
        }
        $bad_url = AddURLParams($bad_url,$a_params,false);
        Redirect($bad_url);
    }
    else
    {
        if (!empty($bad_template))
        {
            $a_specs = array("fmerror"=>htmlspecialchars("$error_mesg"),
                            "fmerrorcode"=>htmlspecialchars("$error_code"),
                            "fmfullerror"=>htmlspecialchars("$error_mesg")."\n".
                                            htmlspecialchars("$s_extra_info"),
                            "fmerrorextra"=>htmlspecialchars("$s_extra_info"),);
            $i_count = 1;
            foreach ($a_item_list as $s_item)
            {
                $a_specs["fmerroritem$i_count"] = htmlspecialchars($s_item);
                $i_count++;
            }
            $s_list = "";
            foreach ($a_item_list as $s_item)
                $s_list .= "<li>".htmlspecialchars($s_item)."</li>\n";
            $a_specs["fmerroritemlist"] = $s_list;
            if (ShowErrorTemplate($bad_template,$a_specs,$b_user_error))
                return;
        }
        $s_text = GetMessage(MSG_ERROR_PROC);
        if ($b_user_error)
            $s_text .= $error_mesg."\n".$s_extra_info;
        else
        {
            if ($b_alerted)
                $s_text .= GetMessage(MSG_ALERT_DONE);
            else
                $s_text .= GetMessage(MSG_PLS_CONTACT);
            $s_text .= GetMessage(MSG_APOLOGY);
        }
        CreatePage($s_text);
            //
            // the session data is not needed now
            //
        ZapSession();
    }
}
 
    //
    // Report an error.  Same as Error, but implements
    // ATTACK_DETECTION_IGNORE_ERRORS.
    //
function ErrorWithIgnore($error_code,$error_mesg,$b_filter = true,$show = true,$int_mesg = "")
{
    $b_alerted = false;
    if (!ATTACK_DETECTION_IGNORE_ERRORS)
        if (SendAlert("$error_code\n *****$int_mesg*****\nError=$error_mesg\n",$b_filter))
            $b_alerted = true;
    if ($show)
        ShowError($error_code,$error_mesg,false,$b_alerted);
    else
            //
            // show something to the user
            //
        ShowError($error_code,GetMessage(MSG_SUBM_FAILED),false,$b_alerted);
    exit;
}
 
    //
    // Report an error
    //
function Error($error_code,$error_mesg,$b_filter = true,$show = true,$int_mesg = "")
{
    $b_alerted = false;
    if (SendAlert("$error_code\n *****$int_mesg*****\nError=$error_mesg\n",$b_filter))
        $b_alerted = true;
    if ($show)
        ShowError($error_code,$error_mesg,false,$b_alerted);
    else
            //
            // show something to the user
            //
        ShowError($error_code,GetMessage(MSG_SUBM_FAILED),false,$b_alerted);
    exit;
}
 
    //
    // Report a user error
    //
function UserError($s_error_code,$s_error_mesg,
                    $s_extra_info = "",$a_item_list = array())
{
    $b_alerted = false;
    if (ALERT_ON_USER_ERROR &&
            SendAlert("$s_error_code\nError=$s_error_mesg\n$s_extra_info\n"))
        $b_alerted = true;
    ShowError($s_error_code,$s_error_mesg,true,$b_alerted,$a_item_list,$s_extra_info);
    exit;
}
 
    //
    // Create a simple page with the given text.
    //
function CreatePage($text)
{
    global  $FM_VERS,$sHTMLCharSet;
 
    echo "<html>\n";
    echo "<head>\n";
    if (isset($sHTMLCharSet) && $sHTMLCharSet !== "")
        echo "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=$sHTMLCharSet\">\n";
    echo "</head>\n";
    echo "<body>\n";
    echo nl2br($text);
    echo "<p /><p><small>";
    echo GetMessage(MSG_ABOUT_FORMMAIL,array("FM_VERS"=>$FM_VERS,
                                            "TECTITE"=>"www.tectite.com"));
    echo "</small></p>\n";
    echo "</body>\n";
    echo "</html>\n";
}
 
    //
    // Strip slashes if magic_quotes_gpc is set.
    //
function StripGPC($s_value)
{
    if (get_magic_quotes_gpc() != 0)
        $s_value = stripslashes($s_value);
    return ($s_value);
}
 
    //
    // return an array, stripped of slashes if magic_quotes_gpc is set
    //
function StripGPCArray($a_values)
{
    if (get_magic_quotes_gpc() != 0)
        foreach ($a_values as $m_key=>$m_value)
            if (is_array($m_value))
                    //
                    // strip arrays recursively
                    //
                $a_values[$m_key] = StripGPCArray($m_value);
            else
                    //
                    // convert scalar to string and strip
                    //
                $a_values[$m_key] = stripslashes("$m_value");
    return ($a_values);
}
 
    //
    // Strip a value of unwanted characters, which might be hacks.
    // If $b_conv_quotes is true, also swaps all double quotes with single quotes.
    //
function Strip($value,$b_conv_quotes = true)
{
    if ($b_conv_quotes)
            //
            // "standard" quote conversion
            //
        $value = str_replace("\"","'",$value);
    $value = preg_replace('/[[:cntrl:][:space:]]+/'," ",$value);    // zap all control chars and multiple blanks
    return ($value);
}
 
    //
    // Clean a value.  This means:
    //  1. convert to string
    //  2. truncate to maximum length
    //  3. strip the value of unwanted or dangerous characters (hacks)
    //  4. trim both ends of whitespace
    // Each element of an array is cleaned as above.  This process occurs
    // recursively, so arrays of arrays work OK too (though there's no
    // need for that in this program).
    //
    // Non-scalar values are changed to the string "<X>" where X is the type.
    // In general, FormMail won't receive non-scalar non-array values, so this
    // is more a future-proofing measure.
    //
function CleanValue($m_value,$b_conv_quotes = true)
{
    if (is_array($m_value))
    {
        foreach ($m_value as $m_key=>$m_item)
            $m_value[$m_key] = CleanValue($m_item,$b_conv_quotes);
    }
    elseif (!is_scalar($m_value))
        $m_value = "<".gettype($m_value).">";
    else
    {
            //
            // convert to string and truncate
            //
        $m_value = substr("$m_value",0,MAXSTRING);
            //
            // strip unwanted chars and trim
            //
        $m_value = trim(Strip($m_value,$b_conv_quotes));
    }
    return ($m_value);
}
 
    //
    // Clean a special value.  Special values listed in $SPECIAL_NOSTRIP
    // will not be cleaned.
    //
function SpecialCleanValue($s_name,$m_value)
{
    global  $SPECIAL_NOSTRIP;
 
    if (!in_array($s_name,$SPECIAL_NOSTRIP))
        $m_value = CleanValue($m_value);
    return ($m_value);
}
 
    //
    // Return the fields and their values in a string containing one
    // field per line.
    //
function MakeFieldOutput($a_order,$a_fields,$s_line_feed = BODY_LF)
{
    $n_order = count($a_order);
    $s_output = "";
    for ($ii = 0 ; $ii < $n_order ; $ii++)
    {
        $s_name = $a_order[$ii];
        if (isset($a_fields[$s_name]))
            $s_output .= "$s_name: ".$a_fields[$s_name].$s_line_feed;
    }
    return ($s_output);
}
 
    //
    // Check if a field name is special. Returns true if it is.
    //
function IsSpecialField($s_name)
{
    global  $SPECIAL_FIELDS;
 
    return (in_array($s_name,$SPECIAL_FIELDS));
}
 
    //
    // Set a special field value.
    //
function SetSpecialField($s_name,$m_value)
{
    global  $SPECIAL_VALUES;
 
        //
        // special values cannot be arrays; ignore them if they are
        //
    if (!is_array($m_value))
        $SPECIAL_VALUES[$s_name] = SpecialCleanValue($s_name,$m_value);
}
 
    //
    // Check if a field name is a special "multi" field.
    // A multi field is the name plus a sequence number.  For example,
    //      conditions1
    //      conditions2
    // Returns a list (array) if it is, otherwise false if not.
    // The list contains:
    //      1. the name of the special multi field
    //      2. the index number for multi field
    //
function IsSpecialMultiField($s_name)
{
    global  $SPECIAL_MULTI;
 
    foreach ($SPECIAL_MULTI as $s_multi_fld)
    {
        $i_len = strlen($s_multi_fld);
            //
            // look for nameN where N is a number starting from 1
            //
        if (substr($s_name,0,$i_len) == $s_multi_fld)
        {
            $i_index = (int) substr($s_name,$i_len);
            if ($i_index > 0)
            {
                    //
                    // re-index to zero
                    //
                --$i_index;
                return (array($s_multi_fld,$i_index));
            }
        }
    }
    return (false);
}
 
    //
    // Set a multi field value.
    //
function SetSpecialMultiField($s_name,$i_index,$m_value)
{
    global  $SPECIAL_VALUES;
 
        //
        // special fields cannot be arrays - ignore if it is
        //
    if (!is_array($m_value))
        $SPECIAL_VALUES[$s_name][$i_index] = SpecialCleanValue($s_name,$m_value);
}
 
    //
    // Process a field
    //
function ProcessField($s_name,$raw_value,&$a_order,&$a_fields,&$a_raw_fields)
{
    global  $FORMATTED_INPUT;
 
        //
        // fields go into an array of special values or an array of other values
        //
    $b_special = false;
    if (IsSpecialField($s_name))
    {
        SetSpecialField($s_name,$raw_value);
        $b_special = true;
    }
        //
        // check for multiple valued special fields
        //
    if (($a_multi_fld = IsSpecialMultiField($s_name)) !== false)
    {
        SetSpecialMultiField($a_multi_fld[0],$a_multi_fld[1],$raw_value);
        $b_special = true;
    }
    if (!$b_special)
    {
            //
            // return the raw value unchanged in the $a_raw_fields array
            //
        $a_raw_fields[$s_name] = $raw_value;
            //
            // handle checkboxes and multiple-selection lists
            // Thanks go to Theodore Boardman for the suggestion
            // and initial working code.
            //
        if (is_array($raw_value))
        {
                //
                // the array must be an array of scalars (not an array
                // of arrays, for example)
                //
            if (is_scalar($raw_value[0]))
            {
                $a_cleaned_values = CleanValue($raw_value);
                    //
                    // the output is a comma separated list of values for the
                    // checkbox.  For example,
                    //          events: Diving,Cycling,Running
                    //
                    // Set the clean value to the list of cleaned checkbox
                    // values.
                    // First, remove any commas in the values themselves.
                    //
                $a_cleaned_values = str_replace(",","",$a_cleaned_values);
                $s_cleaned_value = implode(",",$a_cleaned_values);
            }
            else
                $s_cleaned_value = "<invalid list>";
        }
        else
        {
                //
                // NOTE: there is a minor bug here now that we support
                // $FORM_INI_FILE. The INI file is processed at the end
                // so if you set the mail_options below in the INI file they
                // won't get processed here.  This means you must set
                // the following mail_options in the HTML form for now.
                // (To be fixed at a later date.  RJR 17-Feb-06).
                //
 
                //
                // if the form specifies the "KeepLines" option,
                // don't strip new lines
                //
            if (IsMailOptionSet("KeepLines") && strpos($raw_value,"\n") !== false)
            {
                    //
                    // truncate first
                    //
                $s_truncated = substr("$raw_value",0,MAXSTRING);
                    //
                    // split into lines, clean each individual line,
                    // then put it back together again
                    //
                $a_lines = explode("\n",$s_truncated);
                $a_lines = CleanValue($a_lines);
                $s_cleaned_value = implode(BODY_LF,$a_lines);
                    //
                    // and, for this special case, prepend a new line
                    // so that the value is shown on a fresh line
                    //
                $s_cleaned_value = BODY_LF.$s_cleaned_value;
            }
            else
                $s_cleaned_value = CleanValue($raw_value);
        }
            //
            // if the form specifies the "NoEmpty" option, skip
            // empty values.
            //
        if (!IsMailOptionSet("NoEmpty") || !IsFieldEmpty($s_cleaned_value))
            if (!IsMailExcluded($s_name))
            {
                    //
                    // by default, we maintain the order as passed in
                    // the HTTP request
                    //
                $a_order[] = $s_name;
                $a_fields[$s_name] = $s_cleaned_value;
            }
 
            //
            // add to the $FORMATTED_INPUT array for debugging and
            // error reporting
            //
        array_push($FORMATTED_INPUT,"$s_name: '$s_cleaned_value'");
    }
}
 
    //
    // Parse the input variables and return:
    //  1. an array that specifies the required field order in the output
    //  2. an array containing the non-special cleaned field values indexed
    //     by field name.
    //  3. an array containing the non-special raw field values indexed by
    //     field name.
    //
function ParseInput($a_vars)
{
    $a_order = array();
    $a_fields = array();
    $a_raw_fields = array();
        //
        // scan the array of values passed in (name-value pairs) and
        // produce slightly formatted (not HTML) textual output
        // and extract any special values found.
        //
    foreach ($a_vars as $s_name=>$raw_value)
        ProcessField($s_name,$raw_value,$a_order,$a_fields,$a_raw_fields);
 
    return (array($a_order,$a_fields,$a_raw_fields));
}
 
    //
    // Get the URL for sending to the CRM.
    //
function GetCRMURL($spec,$vars,$url)
{
    $bad = false;
    $list = TrimArray(explode(",",$spec));
    $map = array();
    for ($ii = 0 ; $ii < count($list) ; $ii++)
    {
        $name = $list[$ii];
        if ($name)
        {
                //
                // the specification must be in this format:
                //      form-field-name:CRM-field-name
                //
            if (($i_crm_name_pos = strpos($name,":")) > 0)
            {
                $s_crm_name = substr($name,$i_crm_name_pos + 1);
                $name = substr($name,0,$i_crm_name_pos);
                if (isset($vars[$name]))
                {
                    $map[] = $s_crm_name."=".urlencode($vars[$name]);
                    $map[] = "Orig_".$s_crm_name."=".urlencode($name);
                }
            }
            else
            {
                    //
                    // not the right format, so just include as a parameter
                    // check for name=value format to choose encoding
                    //
                $a_values = explode("=",$name);
                if (count($a_values) > 1)
                    $map[] = urlencode($a_values[0])."=".urlencode($a_values[1]);
                else
                    $map[] = urlencode($a_values[0]);
            }
        }
    }
    if (count($map) == 0)
        return ("");
    return (AddURLParams($url,$map,false));
}
 
    //
    // strip the HTML from a string
    //
function StripHTML($s_str,$s_line_feed = "\n")
{
        //
        // strip HTML comments (s option means include new lines in matches)
        //
    $s_str = preg_replace('/<!--([^-]*([^-]|-([^-]|-[^>])))*-->/s','',$s_str);
        //
        // strip any scripts (i option means case-insensitive)
        //
    $s_str = preg_replace('/<script[^>]*?>.*?<\/script[^>]*?>/si','',$s_str);
        //
        // replace paragraphs with new lines (line feeds)
        //
    $s_str = preg_replace('/<p[^>]*?>/i',$s_line_feed,$s_str);
        //
        // replace breaks with new lines (line feeds)
        //
    $s_str = preg_replace('/<br[[:space:]]*\/?[[:space:]]*>/i',$s_line_feed,$s_str);
        //
        // overcome this bug: http://bugs.php.net/bug.php?id=21311
        //
    $s_str = preg_replace('/<![^>]*>/s','',$s_str);
        //
        // get rid of all HTML tags
        //
    $s_str = strip_tags($s_str);
    return ($s_str);
}
 
    //
    // Check for valid URL in TARGET_URLS
    //
function CheckValidURL($s_url)
{
    global  $TARGET_URLS;
 
    foreach ($TARGET_URLS as $s_prefix)
        if (!empty($s_prefix) &&
                strtolower(substr($s_url,0,strlen($s_prefix))) ==
                strtolower($s_prefix))
            return (true);
    return (false);
}
 
    //
    // Scan the given data for fields returned from the CRM.
    // A field has this following format:
    //      __FIELDNAME__=value
    // terminated by a line feed.
    //
function FindCRMFields($s_data)
{
    $a_ret = array();
    if (preg_match_all('/^__([A-Za-z][A-Za-z0-9_]*)__=(.*)$/m',$s_data,$a_matches) === false)
        SendAlert(GetMessage(MSG_PREG_FAILED));
    else
    {
        $n_matches = count($a_matches[0]);
    //  SendAlert("$n_matches on '$s_data'");
        for ($ii = 0 ; $ii < $n_matches ; $ii++)
            if (isset($a_matches[1][$ii]) && isset($a_matches[2][$ii]))
                $a_ret[$a_matches[1][$ii]] = $a_matches[2][$ii];
    }
    return ($a_ret);
}
 
    //
    // open the given URL to send data to it, we expect the response
    // to contain at least '__OK__=' followed by true or false
    //
function SendToCRM($s_url,&$a_data)
{
    global  $php_errormsg;
 
    if (!CheckValidURL($s_url))
    {
        SendAlert(GetMessage(MSG_URL_INVALID,array("URL"=>$s_url)));
        return (false);
    }
@   $fp = fopen($s_url,"r");
    if ($fp === false)
    {
        SendAlert(GetMessage(MSG_URL_OPEN,array("URL"=>$s_url,
                                        "ERROR"=>CheckString($php_errormsg))));
        return (false);
    }
    $s_mesg = "";
    while (!feof($fp))
    {
        $s_line = fgets($fp,4096);
        $s_mesg .= $s_line;
    }
    fclose($fp);
    $s_mesg = StripHTML($s_mesg);
    $s_result = preg_match('/__OK__=(.*)/',$s_mesg,$a_matches);
    if (count($a_matches) < 2 || $a_matches[1] === "")
    {
            //
            // no agreed __OK__ value returned - assume system error
            //
        SendAlert(GetMessage(MSG_CRM_FAILED,array("URL"=>$s_url,
                                                "MSG"=>$s_mesg)));
        return (false);
    }
        //
        // look for fields to return
        //
    $a_data = FindCRMFields($s_mesg);
        //
        // check for success or user error
        //
    switch (strtolower($a_matches[1]))
    {
    case "true":
        break;
    case "false":
            //
            // check for user error
            //
        if (isset($a_data["USERERRORCODE"]))
        {
            $s_error_code = "crm_error";
            $s_error_mesg = GetMessage(MSG_CRM_FORM_ERROR);
            $s_error_code .= $a_data["USERERRORCODE"];
            if (isset($a_data["USERERRORMESG"]))
                $s_error_mesg = $a_data["USERERRORMESG"];
            UserError($s_error_code,$s_error_mesg);
                // no return
        }
        return (false);
    }
    return (true);
}
 
    //
    // Split into field name and friendly name; returns an array with
    // two elements.
    // Format is:
    //      fieldname:Nice printable name for displaying
    //
function GetFriendlyName($s_name)
{
    if (($i_pos = strpos($s_name,':')) === false)
        return (array(trim($s_name),trim($s_name)));
    return (array(trim(substr($s_name,0,$i_pos)),trim(substr($s_name,$i_pos+1))));
}
 
define("REQUIREDOPS","|^!=");       // operand characters for advanced required processing
 
    //
    // Perform a field comparison test.
    //
function FieldTest($s_oper,$s_fld1,$s_fld2,$a_vars,&$s_error_mesg,
                        $s_friendly1 = "",$s_friendly2 = "")
{
    $b_ok = true;
        //
        // perform the test
        //
    switch ($s_oper)
    {
    case '&':       // both fields must be present
        if (!TestFieldEmpty($s_fld1,$a_vars,$s_empty1) &&
            !TestFieldEmpty($s_fld2,$a_vars,$s_empty2))
            ;       // OK
        else
        {
                //
                // failed
                //
            $s_error_mesg = GetMessage(MSG_AND,array("ITEM1"=>$s_friendly1,
                                                    "ITEM2"=>$s_friendly2));
            $b_ok = false;
        }
        break;
    case '|':       // either field or both must be present
        if (!TestFieldEmpty($s_fld1,$a_vars,$s_empty1) ||
            !TestFieldEmpty($s_fld2,$a_vars,$s_empty2))
            ;       // OK
        else
        {
                //
                // failed
                //
            $s_error_mesg = GetMessage(MSG_OR,array("ITEM1"=>$s_friendly1,
                                                    "ITEM2"=>$s_friendly2));
            $b_ok = false;
        }
        break;
    case '^':       // either field but not both must be present
        $b_got1 = !TestFieldEmpty($s_fld1,$a_vars,$s_empty1);
        $b_got2 = !TestFieldEmpty($s_fld2,$a_vars,$s_empty2);
        if ($b_got1 || $b_got2)
        {
            if ($b_got1 && $b_got2)
            {
                    //
                    // failed
                    //
                $s_error_mesg = GetMessage(MSG_NOT_BOTH,
                                            array("ITEM1"=>$s_friendly1,
                                                  "ITEM2"=>$s_friendly2));
                $b_ok = false;
            }
        }
        else
        {
                //
                // failed
                //
            $s_error_mesg = GetMessage(MSG_XOR,
                                        array("ITEM1"=>$s_friendly1,
                                              "ITEM2"=>$s_friendly2));
            $b_ok = false;
        }
        break;
    case '!=':
    case '=':
        $b_got1 = !TestFieldEmpty($s_fld1,$a_vars,$s_empty1);
        $b_got2 = !TestFieldEmpty($s_fld2,$a_vars,$s_empty2);
        if ($b_got1 && $b_got2)
            $b_match = (GetFieldValue($s_fld1,$a_vars) ==
                            GetFieldValue($s_fld2,$a_vars));
        elseif (!$b_got1 && !$b_got2)
                //
                // haven't got either value - they match
                //
            $b_match = true;
        else
                //
                // got one value, but not the other - they don't match
                //
            $b_match = false;
        if ($s_oper != '=')
        {
                //
                // != operator
                //
            $b_match = !$b_match;
            $s_desc = GetMessage(MSG_IS_SAME_AS,
                                        array("ITEM1"=>$s_friendly1,
                                              "ITEM2"=>$s_friendly2));
        }
        else
            $s_desc = GetMessage(MSG_IS_NOT_SAME_AS,
                                        array("ITEM1"=>$s_friendly1,
                                              "ITEM2"=>$s_friendly2));
        if (!$b_match)
        {
                //
                // failed
                //
            $s_error_mesg = $s_desc;
            $b_ok = false;
        }
        break;
    }
    return ($b_ok);
}
 
    //
    // Process advanced "required" conditionals
    //
function AdvancedRequired($s_cond,$i_span,$a_vars,&$s_missing,&$a_missing_list)
{
    $b_ok = true;
        //
        // get first field name
        //
    list($s_fld1,$s_friendly1) = GetFriendlyName(substr($s_cond,0,$i_span));
        //
        // get the operator
        //
    $s_rem = substr($s_cond,$i_span);
    $i_span = strspn($s_rem,REQUIREDOPS);
    $s_oper = substr($s_rem,0,$i_span);
    switch ($s_oper)
    {
    case '|':
    case '^':
    case '=':
    case '!=':
            //
            // second component is a field name
            //
        list($s_fld2,$s_friendly2) = GetFriendlyName(substr($s_rem,$i_span));
        if (!FieldTest($s_oper,$s_fld1,$s_fld2,$a_vars,$s_error_mesg,
                                                    $s_friendly1,$s_friendly2))
        {
                //
                // failed
                //
            $s_missing .= "$s_error_mesg\n";
            $a_missing_list[] = "$s_error_mesg";
            $b_ok = false;
        }
        break;
    default:
        SendAlert(GetMessage(MSG_REQD_OPER,array("OPER"=>$s_oper)));
        break;
    }
    return ($b_ok);
}
 
    //
    // Check the input for required values.  The list of required fields
    // is a comma-separated list of field names or conditionals
    //
function CheckRequired($s_reqd,$a_vars,&$s_missing,&$a_missing_list)
{
    $b_bad = false;
    $a_list = TrimArray(explode(",",$s_reqd));
    $s_missing = "";
    $a_missing_list = array();
    for ($ii = 0 ; $ii < count($a_list) ; $ii++)
    {
        $s_cond = $a_list[$ii];
        $i_len = strlen($s_cond);
        if ($i_len <= 0)
            continue;
        if (($i_span = strcspn($s_cond,REQUIREDOPS)) >= $i_len)
        {
                //
                // no advanced operator; just a field name
                //
            list($s_fld,$s_friendly) = GetFriendlyName($s_cond);
            if (TestFieldEmpty($s_fld,$a_vars,$s_mesg))
            {
                if ($s_mesg === "")
                    $s_mesg = "$s_friendly";
                else
                    $s_mesg = "$s_friendly ($s_mesg)";
                $b_bad = true;
                $s_missing .= "$s_mesg\n";
                $a_missing_list[] = "$s_mesg";
            }
        }
        elseif (!AdvancedRequired($s_cond,$i_span,$a_vars,
                                    $s_missing,$a_missing_list))
            $b_bad = true;
    }
    return (!$b_bad);
}
 
    //
    // Run a condition test
    //
function RunTest($s_test,$a_vars)
{
    global  $aAlertInfo;
 
    $s_op_chars = "&|^!=~#<>";      // these are the characters for the operators
    $i_len = strlen($s_test);
    $b_ok = true;
    if ($i_len <= 0)
            //
            // empty test - true
            //
        ;
    elseif ($s_test == "!")
            //
            // test asserts false
            //
        $b_ok = false;
    elseif (($i_span = strcspn($s_test,$s_op_chars)) >= $i_len)
            //
            // no operator - just check field presence
            //
        $b_ok = !TestFieldEmpty($s_test,$a_vars,$s_mesg);
    else
    {
            //
            // get first field name
            //
        $s_fld1 = trim(substr($s_test,0,$i_span));
            //
            // get the operator
            //
        $s_rem = substr($s_test,$i_span);
        $i_span = strspn($s_rem,$s_op_chars);
        $s_oper = substr($s_rem,0,$i_span);
        switch ($s_oper)
        {
        case '&':
        case '|':
        case '^':
        case '=':
        case '!=':
                //
                // get the second field name
                //
            $s_fld2 = trim(substr($s_rem,$i_span));
            $b_ok = FieldTest($s_oper,$s_fld1,$s_fld2,$a_vars,$s_error_mesg);
            break;
        case '~':
        case '!~':
                //
                // get the regular expression
                //
            $s_pat = trim(substr($s_rem,$i_span));
            if (!TestFieldEmpty($s_fld1,$a_vars,$s_mesg))
                $s_value = GetFieldValue($s_fld1,$a_vars);
            else
                $s_value = "";
            //echo "<p>Pattern: '".htmlspecialchars($s_pat)."': count=".preg_match($s_pat,$s_value)."<br /></p>";
                //
                // match the regular expression
                //
            if (preg_match($s_pat,$s_value) > 0)
                $b_ok = ($s_oper == '~');
            else
                $b_ok = ($s_oper == '!~');
            if (!$b_ok)
                $aAlertInfo[] = GetMessage(MSG_PAT_FAILED,array("OPER"=>$s_oper,
                                                            "PAT"=>$s_pat,
                                                            "VALUE"=>$s_value));
            break;
        case '#=':
        case '#!=':
        case '#<':
        case '#>':
        case '#<=':
        case '#>=':
                //
                // numeric tests
                //
            $s_num = trim(substr($s_rem,$i_span));
                //
                // if this is a file field, get the size of the file for
                // numeric tests
                //
            if (($s_value = GetFileSize($s_fld1)) === false)
                $s_value = $a_vars[$s_fld1];
            if (strpos($s_num,'.') === false)
            {
                    //
                    // treat as integer
                    //
                $m_num = (int) $s_num;
                $m_fld = (int) $s_value;
            }
            else
            {
                    //
                    // treat as floating point
                    //
                $m_num = (float) $s_num;
                $m_fld = (float) $s_value;
            }
            switch ($s_oper)
            {
            case '#=':
                $b_ok = ($m_fld == $m_num);
                break;
            case '#!=':
                $b_ok = ($m_fld != $m_num);
                break;
            case '#<':
                $b_ok = ($m_fld < $m_num);
                break;
            case '#>':
                $b_ok = ($m_fld > $m_num);
                break;
            case '#<=':
                $b_ok = ($m_fld <= $m_num);
                break;
            case '#>=':
                $b_ok = ($m_fld >= $m_num);
                break;
            }
            break;
        default:
            SendAlert(GetMessage(MSG_COND_OPER,array("OPER"=>$s_oper)));
            break;
        }
    }
    return ($b_ok);
}
 
    //
    // Check the input for condition tests.
    //
function CheckConditions($m_conditions,$a_vars,&$s_missing,&$a_missing_list,$m_id = false)
{
    if (is_array($m_conditions))
    {
            //
            // Sort the conditions by their numeric value.  This ensures
            // conditions are executed in the right order.
            //
        ksort($m_conditions,SORT_NUMERIC);
        foreach ($m_conditions as $m_key=>$s_cond)
            if (!CheckConditions($s_cond,$a_vars,$s_missing,$a_missing_list,$m_key))
                return (false);
        return (true);
    }
    $s_fld_name = "conditions".($m_id === false ? "" : ($m_id+1));
    if (!is_string($m_conditions))
    {
        SendAlert(GetMessage(MSG_INV_COND,array("FLD"=>$s_fld_name)));
        return (true);  // pass invalid conditions
    }
    if ($m_conditions == "")
        return (true);  // pass empty conditions
    $s_cond = $m_conditions;
        //
        // extract the separator characters
        //
    if (strlen($s_cond) < 2)
    {
        SendAlert(GetMessage(MSG_COND_CHARS,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond)));
        return (true);  // pass invalid conditions
    }
    $s_list_sep = $s_cond{0};
    $s_int_sep = $s_cond{1};
    $s_full_cond = $s_cond = substr($s_cond,2);
    $b_bad = false;
    $a_list = TrimArray(explode($s_list_sep,$s_cond));
    $s_missing = "";
    $a_missing_list = array();
    for ($ii = 0 ; $ii < count($a_list) ; $ii++)
    {
        $s_cond = $a_list[$ii];
        $i_len = strlen($s_cond);
        if ($i_len <= 0)
            continue;
            //
            // split the condition into its internal components
            //
        $a_components = TrimArray(explode($s_int_sep,$s_cond));
        if (count($a_components) < 5)
        {
            SendAlert(GetMessage(MSG_COND_INVALID,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_int_sep)));
                //
                // the smallest condition has 5 components
                //
            continue;
        }
            //
            // first component is ignored (it's blank)
            //
        $a_components = array_slice($a_components,1);
        switch ($a_components[0])
        {
        case "TEST":
            if (count($a_components) > 5)
            {
                SendAlert(GetMessage(MSG_COND_TEST_LONG,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_list_sep)));
                continue;
            }
            if (!RunTest($a_components[1],$a_vars))
            {
                $s_missing .= $a_components[2]."\n";
                $a_missing_list[] = $a_components[2];
                $b_bad = true;
            }
            break;
        case "IF":
            if (count($a_components) < 6)
            {
                SendAlert(GetMessage(MSG_COND_IF_SHORT,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_int_sep)));
                continue;
            }
            if (count($a_components) > 7)
            {
                SendAlert(GetMessage(MSG_COND_IF_LONG,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_list_sep)));
                continue;
            }
            if (RunTest($a_components[1],$a_vars))
                $b_test = RunTest($a_components[2],$a_vars);
            else
                $b_test = RunTest($a_components[3],$a_vars);
            if (!$b_test)
            {
                $s_missing .= $a_components[4]."\n";
                $a_missing_list[] = $a_components[4];
                $b_bad = true;
            }
            break;
        default:
            SendAlert(GetMessage(MSG_COND_UNK,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "CMD"=>$a_components[0])));
            break;
        }
    }
    return (!$b_bad);
}
 
    //
    // Return a formatted list of the given environment variables.
    //
function GetEnvVars($list,$s_line_feed)
{
    global  $VALID_ENV,$aServerVars;
 
    $output = "";
    for ($ii = 0 ; $ii < count($list) ; $ii++)
    {
        $name = $list[$ii];
        if ($name && array_search($name,$VALID_ENV,true) !== false)
        {
                //
                // if the environment variable is empty or non-existent, try
                // looking for the value in the server vars.
                //
            if (($s_value = getenv($name)) === "" || $s_value === false)
                if (isset($aServerVars[$name]))
                    $s_value = $aServerVars[$name];
                else
                    $s_value = "";
            $output .= $name."=".$s_value.$s_line_feed;
        }
    }
    return ($output);
}
    //
    // open a socket connection to a filter and post the data there
    //
function SocketFilter($filter,$a_filter_info,$m_data)
{
    static  $b_in_here = false;
    global  $php_errormsg;
 
        //
        // prevent recursive errors
        //
    if ($b_in_here)
        return ("<DATA DISCARDED>");
    $b_in_here = true;
 
    $a_errors = array();
    if (!isset($a_filter_info["site"]))
        $a_errors[] = GetMessage(MSG_MISSING,array("ITEM"=>"site"));
    else
        $s_site = $a_filter_info["site"];
 
    if (!isset($a_filter_info["port"]))
        $a_errors[] = GetMessage(MSG_MISSING,array("ITEM"=>"port"));
    else
        $i_port = (int) $a_filter_info["port"];
 
    if (!isset($a_filter_info["path"]))
        $a_errors[] = GetMessage(MSG_MISSING,array("ITEM"=>"path"));
    else
        $s_path = $a_filter_info["path"];
 
    if (!isset($a_filter_info["params"]))
        $a_params = array();
    elseif (!is_array($a_filter_info["params"]))
        $a_errors[] = GetMessage(MSG_NEED_ARRAY,array("ITEM"=>"params"));
    else
        $a_params = $a_filter_info["params"];
 
    if (!empty($a_errors))
    {
        Error("bad_filter",GetMessage(MSG_FILTER_WRONG,array(
                            "FILTER"=>$filter,
                            "ERRORS"=>implode(', ',$a_errors))),false,false);
        exit;
    }
 
        //
        // ready to build the socket - we need a longer time limit for the
        // script if we're doing this; we allow 30 seconds for the connection
        // (should be instantaneous, especially if it's the same domain)
        //
    set_time_limit(60);
@   $f_sock = fsockopen($s_site,$i_port,$i_errno,$s_errstr,30);
    if ($f_sock === false)
    {
        Error("filter_connect",GetMessage(MSG_FILTER_CONNECT,array(
                            "FILTER"=>$filter,
                            "SITE"=>$s_site,
                            "ERRNUM"=>$i_errno,
                            "ERRSTR"=>"$s_errstr (".CheckString($php_errormsg).")")),
                            false,false);
        exit;
    }
        //
        // build the data to send
        //
    $m_request_data = array();
    $i_count = 0;
    foreach ($a_params as $m_var)
    {
        $i_count++;
            //
            // if the parameter spec is an array, process it specially;
            // it must have "name" and "file" elements
            //
        if (is_array($m_var))
        {
            if (!isset($m_var["name"]))
            {
                Error("bad_filter",GetMessage(MSG_FILTER_PARAM,
                                    array("FILTER"=>$filter,
                                          "NUM"=>$i_count,
                                          "NAME"=>"name")),false,false);
                fclose($f_sock);
                exit;
            }
            $s_name = $m_var["name"];
            if (!isset($m_var["file"]))
            {
                Error("bad_filter",GetMessage(MSG_FILTER_PARAM,
                                    array("FILTER"=>$filter,
                                          "NUM"=>$i_count,
                                          "NAME"=>"file")),false,false);
                fclose($f_sock);
                exit;
            }
                //
                // open the file and read its contents
                //
@           $fp = fopen($m_var["file"],"r");
            if ($fp === false)
            {
                Error("filter_error",GetMessage(MSG_FILTER_OPEN_FILE,
                                    array("FILTER"=>$filter,
                                          "FILE"=>$m_var["file"],
                                          "ERROR"=>CheckString($php_errormsg))),false,false);
                fclose($f_sock);
                exit;
            }
            $s_data = "";
            $n_lines = 0;
            while (!feof($fp))
            {
                if (($s_line = fgets($fp,2048)) === false)
                    if (feof($fp))
                        break;
                    else
                    {
                        Error("filter_error",GetMessage(MSG_FILTER_FILE_ERROR,
                                    array("FILTER"=>$filter,
                                          "FILE"=>$m_var["file"],
                                          "ERROR"=>CheckString($php_errormsg),
                                          "NLINES"=>$n_lines)),false,false);
                        fclose($f_sock);
                        exit;
                    }
                $s_data .= $s_line;
                $n_lines++;
            }
 
            fclose($fp);
            $m_request_data[] = "$s_name=".urlencode($s_data);
        }
        else
            $m_request_data[] = (string) $m_var;
    }
        //
        // add the data
        //
    if (is_array($m_data))
        $m_request_data[] = "data=".urlencode(implode(BODY_LF,$m_data));
    else
        $m_request_data[] = "data=".urlencode($m_data);
    $s_request = implode("&",$m_request_data);
 
    if (($i_pos = strpos($s_site,"://")) !== false)
        $s_site_name = substr($s_site,$i_pos+3);
    else
        $s_site_name = $s_site;
 
    fputs($f_sock,"POST $s_path HTTP/1.0\r\n");
    fputs($f_sock,"Host: $s_site_name\r\n");
    fputs($f_sock,"Content-Type: application/x-www-form-urlencoded\r\n");
    fputs($f_sock,"Content-Length: ".strlen($s_request)."\r\n");
    fputs($f_sock,"\r\n");
    fputs($f_sock,"$s_request\r\n");
 
        //
        // now read the response
        //
    $m_hdr = "";
    $m_data = "";
    $b_in_hdr = true;
    $b_ok = false;
    while (!feof($f_sock))
    {
        if (($s_line = fgets($f_sock,2048)) === false)
            if (feof($f_sock))
                break;
            else
            {
                Error("filter_failed",GetMessage(MSG_FILTER_READ_ERROR,
                            array("FILTER"=>$filter,
                                  "ERROR"=>CheckString($php_errormsg))),false,false);
                fclose($f_sock);
                exit;
            }
            //
            // look for an "__OK__" line
            //
        if (trim($s_line) == "__OK__")
            $b_ok = true;
        elseif ($b_in_hdr)
        {
                //
                // blank line signals end of header
                //
            if (trim($s_line) == "")
                $b_in_hdr = false;
            else
                $m_hdr .= $s_line;
        }
        else
            $m_data .= $s_line;
    }
        //
        // if not OK, then report error
        //
    if (!$b_ok)
    {
        Error("filter_failed",GetMessage(MSG_FILTER_NOT_OK,
                    array("FILTER"=>$filter,
                          "DATA"=>$m_data)),false,false);
        fclose($f_sock);
        exit;
    }
    fclose($f_sock);
    $b_in_here = false;
    return ($m_data);
}
 
    //
    // run data through a supported filter
    //
function Filter($filter,$m_data)
{
    global  $FILTERS,$SOCKET_FILTERS;
    global  $php_errormsg;
    static  $b_in_here = false;
 
        //
        // prevent recursive errors
        //
    if ($b_in_here)
        return ("<DATA DISCARDED>");
    $b_in_here = true;
 
        //
        // Any errors sent in an alert are flagged to not run through the
        // filter - this also means the user's data won't be included in the
        // alert.
        // The reason for this is that the Filter is typically an encryption
        // program. If the filter fails, then sending the user's data in
        // clear text in an alert breaks the security of having encryption
        // in the first place!
        //
 
        //
        // find the filter
        //
    if (!isset($FILTERS[$filter]) || $FILTERS[$filter] == "")
    {
            //
            // check for SOCKET_FILTERS
            //
        if (!isset($SOCKET_FILTERS[$filter]) || $SOCKET_FILTERS[$filter] == "")
        {
            ErrorWithIgnore("bad_filter",GetMessage(MSG_FILTER_UNK,
                        array("FILTER"=>$filter)),false,false);
            exit;
        }
        $m_data = SocketFilter($filter,$SOCKET_FILTERS[$filter],$m_data);
    }
    elseif ($FILTERS[$filter] == "null")
            //
            // do nothing - just return the original data unchanged
            //
        ;
    elseif ($FILTERS[$filter] == "csv")
        $m_data = BuiltinFilterCSV();
    else
    {
        $cmd = $FILTERS[$filter];
            //
            // get the program name - assumed to be the first blank-separated word
            //
        $a_words = preg_split('/\s+/',$cmd);
        $prog = $a_words[0];
 
        $s_cwd = getcwd();
            //
            // change to the directory that contains the filter program
            //
        $dirname = dirname($prog);
        if ($dirname != "" && $dirname != "." && !chdir($dirname))
        {
            Error("chdir_filter",GetMessage(MSG_FILTER_CHDIR,
                        array("DIR"=>$dirname,"FILTER"=>$filter,
                              "ERROR"=>CheckString($php_errormsg))),false,false);
            exit;
        }
 
            //
            // the output of the filter goes to a temporary file; this works
            // OK on Windows too, even with the Unix shell syntax.
            //
        $temp_file = GetTempName("FMF");
        $cmd = "$cmd > $temp_file 2>&1";
            //
            // start the filter
            //
        $pipe = popen($cmd,"w");
        if ($pipe === false)
        {
            $s_sv_err = CheckString($php_errormsg);
            $err = join('',file($temp_file));
            unlink($temp_file);
            Error("filter_not_found",GetMessage(MSG_FILTER_NOTFOUND,
                        array("CMD"=>$cmd,"FILTER"=>$filter,
                              "ERROR"=>$s_sv_err)),false,false,$err);
            exit;
        }
            //
            // write the data to the filter
            //
        if (is_array($m_data))
            fwrite($pipe,implode(BODY_LF,$m_data));
        else
            fwrite($pipe,$m_data);
        if (($i_st = pclose($pipe)) != 0)
        {
            $s_sv_err = CheckString($php_errormsg);
            $err = join('',file($temp_file));
            unlink($temp_file);
            Error("filter_failed",GetMessage(MSG_FILTER_ERROR,
                        array("FILTER"=>$filter,
                              "ERROR"=>$s_sv_err,
                              "STATUS"=>$i_st)),false,false,$err);
            exit;
        }
            //
            // read in the filter's output and return as the data to be sent
            //
        $m_data = join('',file($temp_file));
        unlink($temp_file);
 
            //
            // return to previous directory
            //
        chdir($s_cwd);
    }
    $b_in_here = false;
    return ($m_data);
}
 
/*
 * Class:       CSVFormat
 * Description:     
 *  Manages formatting of CSV content.
 */
class   CSVFormat
{
    var         $_cSep;         /* field separator character */
    var         $_cQuote;       /* field quote character */
    var         $_cIntSep;      /* internal separator character (for lists) */
    var         $_sEscPolicy;   /* escape processing policy */
    var         $_sCleanFunc;   /* cleaning function for fields */
 
    /*
     * Method:      CSVFormat ctor
     * Parameters:  $c_sep          the field separator
     *              $c_quote        the quote character to use
     *              $c_int_sep      the internal field separator to use
     *              $s_esc_policy   escape processing policy to use
     *              $s_clean_func   a cleaning function
     * Returns:     n/a
     * Description: 
     *  Constructs the object.
     */
    function    CSVFormat($c_sep = ',',$c_quote = '"',$c_int_sep = ';',
                            $s_esc_policy = "backslash",$s_clean_func = NULL)
    {
        $this->SetSep($c_sep);
        $this->SetQuote($c_quote);
        $this->SetIntSep($c_int_sep);
        $this->SetEscPolicy($s_esc_policy);
        $this->SetCleanFunc($s_clean_func);
    }
 
    /*
     * Method:      SetEscPolicy
     * Parameters:  $s_esc_policy   a string specifying the escape processing
     *                              policy to use
     * Returns:     void
     * Description: 
     *  Set the escape processing policy.
     */
 
    function    SetEscPolicy($s_esc_policy)
    {
        switch ($s_esc_policy)
        {
        default:        /* should generate a warning */
        case "backslash":
                $this->_sEscPolicy = "b";
                break;
        case "double":
                $this->_sEscPolicy = "d";
                break;
        case "strip":
                $this->_sEscPolicy = "s";
                break;
        case "conv":
                $this->_sEscPolicy = "c";
                break;
        }
    }
 
    /*
     * Method:      SetSep
     * Parameters:  $c_sep      the separator character to use
     * Returns:     void
     * Description: 
     *  Set the separator character for between fields.
     */
    function    SetSep($c_sep)
    {
        $this->_cSep = $c_sep;
    }
 
    /*
     * Method:      SetQuote
     * Parameters:  $c_quote      the quote character to use
     * Returns:     void
     * Description: 
     *  Set the quote character for quoting fields.
     */
    function    SetQuote($c_quote)
    {
        $this->_cQuote = $c_quote;
    }
 
    /*
     * Method:      SetIntSep
     * Parameters:  $c_int_sep      the internal separator character to use
     * Returns:     void
     * Description: 
     *  Set the internal separator character for inside fields.
     */
    function    SetIntSep($c_int_sep)
    {
        $this->_cIntSep = $c_int_sep;
    }
 
    /*
     * Method:      SetCleanFunc
     * Parameters:  $s_clean_func   the name of a cleaning function (can be NULL)
     * Returns:     void
     * Description: 
     *  Set the cleaning function for fields.
     */
    function    SetCleanFunc($s_clean_func)
    {
        $this->_sCleanFunc = $s_clean_func;
    }
 
    /*
     * Method:      _Escape
     * Parameters:  $m_value    the field value; string or array of strings 
     * Returns:     mixed       the field value escaped according to the
     *                          escape processing policy
     * Description: 
     *  Escapes a field value according to the configured requirements.
     */
    function    _Escape($m_value)
    {
        switch ($this->_sEscPolicy)
        {
        default:            /* should generate an error */
        case "b":
                    /*
                     * 'backslash' escape policy: replace \ with \\ and
                     * " with \"
                     */
                $m_value = str_replace("\\","\\\\",$m_value);
                $m_value = str_replace($this->_cQuote,"\\".$this->_cQuote,
                                                                    $m_value);
                break;
        case "d":
                    /*
                     * 'double' escape policy: replace " with ""
                     * This is suitable for Microsoft apps such as Excel
                     * and Access. It also meets the specification of
                     * RFC4180, though this RFC only specified double
                     * quotes whereas we handle any quote character.
                     */
                $m_value = str_replace($this->_cQuote,
                                        $this->_cQuote.$this->_cQuote,$m_value);
                break;
        case "s":
                    /*
                     * 'strip' escape policy: strip quotes
                     */
                $m_value = str_replace($this->_cQuote,"",$m_value);
                break;
        case "c":
                    /*
                     * 'conv' escape policy: convert quotes to the other quotes
                     */
                switch ($this->_cQuote)
                {
                case '"':
                        /*
                         * convert double quotes in the data to single quotes
                         */
                    $m_value = str_replace("\"","'",$m_value);
                    break;
                case '\'':
                        /*
                         * convert single quotes in the data to double quotes
                         */
                    $m_value = str_replace("'","\"",$m_value);
                    break;
                default:
                        /*
                         * otherwise, leave the data unchanged
                         */
                    break;
                }
                break;
        }
        return ($m_value);
    }
 
    function    _Format($m_value)
    {
        $m_value = $this->_Escape($m_value);
            /*
             * we handle strings and arrays of strings
             */
        if (is_array($m_value))
                /*
                 * separate the values with the internal field separator
                 */
            $m_value = implode($this->_cIntSep,$m_value);
        return ($this->_cQuote.$m_value.$this->_cQuote);
    }
 
    /*
     * Method:      MakeCSVRecord
     * Parameters:  $a_column_list  a list of column names (field names) to
     *                              include
     *              $a_vars         raw data array indexed by column name
     *                              (field name).
     *                              A data value can be a string or an array
     *                              of strings.
     * Returns:     string          the comma-separated value    
     * Description: 
     *  Creates a single CSV record for a list of columns.
     */
    function    MakeCSVRecord($a_column_list,$a_vars)
    {
        $s_rec = "";
        $n_columns = count($a_column_list);
        for ($ii = 0 ; $ii < $n_columns ; $ii++)
        {
            $s_col_name = $a_column_list[$ii];
                /*
                 * if a column is specified it must be included, even if there
                 * is no data for it.
                 */
            if (isset($a_vars[$s_col_name]))
            {
                $m_value = $a_vars[$s_col_name];
                if (isset($this->_sCleanFunc))
                {
                    $s_func = $this->_sCleanFunc;
                    $m_value = $s_func($m_value);
                }
            }
            else
                $m_value = "";
 
            $m_value = $this->_Format($m_value);
            if ($ii > 0)
                    /*
                     * prepend the separator from the second field onwards
                     */
                $s_rec .= $this->_cSep;
            $s_rec .= $m_value;
        }
        return ($s_rec);
    }
 
    /*
     * Method:      MakeHeading
     * Parameters:  $a_column_list  a list of column names (field names) to
     *                              include
     * Returns:     string          the comma-separated heading record    
     * Description: 
     *  Creates a heading record for the CSV data.
     */
    function    MakeHeading($a_column_list)
    {
        $s_rec = "";
        $n_columns = count($a_column_list);
        for ($ii = 0 ; $ii < $n_columns ; $ii++)
        {
            $s_col_name = $a_column_list[$ii];
            $m_value = $this->_Format($s_col_name);
            if ($ii > 0)
                    /*
                     * prepend the separator from the second field onwards
                     */
                $s_rec .= $this->_cSep;
            $s_rec .= $m_value;
        }
        return ($s_rec);
    }
};
 
    /*
     * Built-in filter.  Generates CSV (comma separated values) content from
     * the submitted fields. The special field "filter_fields" determines
     * which fields to include in the CSV content.
     * The following options are support in "filter_options":
     *      CSVHeading  if set, includes a heading line first with the field names
     *      CSVSep      specifies a separator character instead of comma
     *      CSVIntSep   specifies an internal separator character for lists
     *      CSVQuote    specifies the character to use to quote each column; default
     *                  is double quotes
     *      CSVEscPolicy controls the way quotes are escaped in the data.  Supported
     *                  values are: backslash (the default),double,strip
     *      CSVRaw      if set, then the fields are recorded as raw values and
     *                  are *not* cleaned according to FormMail's normal field
     *                  cleaning process.
     * If the "filter_fields" field does not exist, then the "csvcolumns" field is
     * used instead.  If neither exist, then all fields are included along with
     * a Heading line.
     */
function BuiltinFilterCSV()
{
    global  $aAllRawValues,$aRawDataValues,$SPECIAL_VALUES,$CSVLINE;
 
    $b_heading = false;
    $a_column_list = array();
    $s_cols = $SPECIAL_VALUES["filter_fields"];
    if (!isset($s_cols) || empty($s_cols) || !is_string($s_cols))
    {
        $s_cols = $SPECIAL_VALUES["csvcolumns"];
        if (!isset($s_cols) || empty($s_cols) || !is_string($s_cols))
        {
                /*
                 * neither filter_fields nor csvcolumns defined - get all
                 * columns
                 */
            $s_cols = "";
                /*
                 * special case - include these two special fields
                 */
            $a_column_list = array("email","realname");
                /*
                 * now include all the data fields
                 */
            $a_column_list = array_merge($a_column_list,
                                            array_keys($aRawDataValues));
            $b_heading = true;
        }
    }
    if (empty($a_column_list))
        $a_column_list = TrimArray(explode(",",$s_cols));
 
    $csv_format = new CSVFormat();
 
        /*
         * get the various options and set them
         */
    $m_temp = GetFilterOption("CSVQuote");
    if (isset($m_temp))
        $csv_format->SetQuote($m_temp);
    $m_temp = GetFilterOption("CSVSep");
    if (isset($m_temp))
        $csv_format->SetSep($m_temp);
    $m_temp = GetFilterOption("CSVIntSep");
    if (isset($m_temp))
        $csv_format->SetIntSep($m_temp);
    $m_temp = GetFilterOption("CSVEscPolicy");
    if (isset($m_temp))
        $csv_format->SetEscPolicy($m_temp);
    $m_temp = GetFilterOption("CSVHeading");
    if (isset($m_temp))
        $b_heading = true;
 
        /*
         * clean fields unless CSVRaw is specified
         */
    $m_temp = GetFilterOption("CSVRaw");
    if (!isset($m_temp))
        $csv_format->SetCleanFunc(create_function('$m_value',
                                    'return CleanValue($m_value,false);'));
 
    $s_csv = $csv_format->MakeCSVRecord($a_column_list,$aAllRawValues);
 
    if ($b_heading)
    {
        $s_head = $csv_format->MakeHeading($a_column_list);
            /*
             * return the heading and the record with $CSVLINE as record separator
             */
        return ($s_head.$CSVLINE.$s_csv.$CSVLINE);
    }
    else
            /*
             * return this record with $CSVLINE appended
             */
        return ($s_csv.$CSVLINE);
}
 
$aSubstituteErrors = array();
$aSubstituteValues = NULL;
$sSubstituteMissing = NULL;
 
    //
    // Run htmlspecialchars on every value in an array.
    //
function ArrayHTMLSpecialChars($a_list)
{
    $a_new = array();
    foreach ($a_list as $m_key=>$m_value)
        if (is_array($m_value))
            $a_new[$m_key] = ArrayHTMLSpecialChars($m_value);
        else
            $a_new[$m_key] = htmlspecialchars($m_value);
    return ($a_new);
}
 
    //
    // Worker function for SubstituteValue and SubstituteValueForPage.
    // Returns the value of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, an error is reported or the given
    // replacement string is used.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValueWorker($a_matches,$s_repl,$b_html = true)
{
    global  $aSubstituteErrors,$aSubstituteValues,$SPECIAL_VALUES;
 
    $b_insert_br = true;       // option to put "<br />" tags before newlines in HTML templates
 
    $s_name = $a_matches[0];
    assert(strlen($s_name) > 1 && $s_name{0} == '$');
    $s_name = substr($s_name,1);
    if (($i_len = strlen($s_name)) > 0 && $s_name{0} == '{')
    {
        assert($s_name{$i_len-1} == '}');
        $s_name = substr($s_name,1,-1);
            //
            // grab any processing options
            //
        $a_args = explode(":",$s_name);
        $s_name = $a_args[0];
        if (($n_args = count($a_args)) > 1)
        {
            for ($ii = 1 ; $ii < $n_args ; $ii++)
            {
                switch ($a_args[$ii])
                {
                case "nobr":
                    $b_insert_br = false;
                    break;
                }
            }
        }
    }
    $s_value = "";
    if (IsFieldSet($s_name,$aSubstituteValues) &&
        !TestFieldEmpty($s_name,$aSubstituteValues,$s_mesg))
    {
        if (is_array($aSubstituteValues[$s_name]))
                //
                // note that the separator can include HTML special chars
                //
            $s_value = implode($SPECIAL_VALUES['template_list_sep'],
                            $b_html ?
                            ArrayHTMLSpecialChars($aSubstituteValues[$s_name]) :
                            $aSubstituteValues[$s_name]);
        else
        {
            $s_value = GetFieldValue($s_name,$aSubstituteValues);
            if ($b_html)
                $s_value = htmlspecialchars($s_value);
        }
        if ($b_html && $b_insert_br)
                //
                // Insert HTML line breaks before newlines.
                //
            $s_value = nl2br($s_value);
    }
    elseif (isset($SPECIAL_VALUES[$s_name]))
        $s_value = $b_html ?
                        htmlspecialchars((string) $SPECIAL_VALUES[$s_name]) :
                        (string) $SPECIAL_VALUES[$s_name];
    elseif (isset($s_repl))
            //
            // If a replacement value has been specified use it, and
            // don't call htmlspecialchars.  This allows the use
            // of HTML tags in a replacement string.
            //
        $s_value = $s_repl;
    else
        $aSubstituteErrors[] = GetMessage(MSG_FLD_NOTFOUND,array("FIELD"=>$s_name));
    return ($s_value);
}
 
    //
    // Callback function for preg_replace_callback.  Returns the value
    // of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, an error is reported or an special
    // replacement string is used.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValue($a_matches)
{
    global  $sSubstituteMissing;
 
    return (SubstituteValueWorker($a_matches,$sSubstituteMissing));
}
 
    //
    // Callback function for preg_replace_callback.  Returns the value
    // of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, an error is reported or an special
    // replacement string is used.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValuePlain($a_matches)
{
    global  $sSubstituteMissing;
 
    return (SubstituteValueWorker($a_matches,$sSubstituteMissing,false));
}
 
    //
    // Callback function for preg_replace_callback.  Returns the value
    // of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, the empty string is substituted.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValueForPage($a_matches)
{
    return (SubstituteValueWorker($a_matches,""));
}
 
    //
    // Process the given HTML template and fill the fields.
    //
function DoProcessTemplate($s_dir,$s_url,$s_template,&$a_lines,
                            $a_values,$s_missing,$s_subs_func)
{
    global  $aSubstituteErrors,$aSubstituteValues,$sSubstituteMissing;
 
    if (($a_template_lines = LoadTemplate($s_template,$s_dir,
                                            $s_url,true)) === false)
        return (false);
 
    $b_ok = true;
        //
        // initialize the errors list
        //
    $aSubstituteErrors = array();
        //
        // initialize the values
        //
    $aSubstituteValues = $a_values;
    $sSubstituteMissing = $s_missing;
 
    foreach ($a_template_lines as $s_line)
    {
            //
            // search for words in these forms:
            //      $word
            //      ${word:options}
            // where word begins with an alphabetic character and
            // consists of alphanumeric and underscore
            //
        $a_lines[] = preg_replace_callback('/\$[a-z][a-z0-9_]*|\$\{[a-z][a-z0-9_]*(:[^\}]*)*\}/i',
                                            $s_subs_func,$s_line);
    }
 
//  SendAlert("Error count=".count($aSubstituteErrors));
    if (count($aSubstituteErrors) != 0)
    {
        SendAlert(GetMessage(MSG_TEMPLATE_ERRORS,array("NAME"=>$s_template)).
                            implode("\n",$aSubstituteErrors));
        $b_ok = false;
    }
    global  $FMCTemplProc;
 
        //
        // note that it's possible for an old version of FormMail Computation
        // module to get loaded which doesn't provide FMCTemplProc
        //
    if ($b_ok && ADVANCED_TEMPLATES && isset($FMCTemplProc))
    {
        $a_mesgs = array();
        /*foreach ($a_lines as $i_lno=>$s_line)
            if (strpos($s_line,"\n") !== false)
                SendAlert("Line $i_lno has a newline");*/
        set_time_limit(60);
        if (($m_result = $FMCTemplProc->Process(implode("\n",$a_lines),$a_mesgs)) === false)
        {
            $s_msgs = "\n";
            foreach ($a_mesgs as $a_msg)
            {
                $s_msgs .= "Line ".$a_msg["LINE"];
                $s_msgs .= ", position ".$a_msg["CHAR"].": ";
                $s_msgs .= $a_msg["MSG"]."\n";
            }
            Error("fmadvtemplates",GetMessage(MSG_TEMPL_PROC,
                        array("ERRORS"=>$s_msgs)),false,false);
            $b_ok = false;
        }
        else
        {
            /*foreach ($m_result as $i_lno=>$s_line)
                if (($nn = substr_count($s_line,"\n")) > 1)
                    SendAlert("Result line $i_lno has $nn newlines");*/
                //
                // strip the new lines
                //
            $a_lines = explode("\n",implode("",$m_result));
        }
        $a_alerts = $FMCTemplProc->GetAlerts();
        if (count($a_alerts) > 0)
            SendAlert(GetMessage(MSG_TEMPL_ALERT,
                        array("ALERTS"=>implode("\n",$a_alerts))));
        $a_debug = $FMCTemplProc->GetDebug();
        if (count($a_debug) > 0)
            SendAlert(GetMessage(MSG_TEMPL_DEBUG,
                        array("DEBUG"=>implode("\n",$a_debug))));
    }
 
    return ($b_ok);
}
 
    //
    // Process the given HTML template and fill the fields.
    //
function ProcessTemplate($s_template,&$a_lines,$a_values,$s_missing = NULL,
                            $s_subs_func = 'SubstituteValue')
{
    global  $TEMPLATEURL,$TEMPLATEDIR;
 
    if (empty($TEMPLATEDIR) && empty($TEMPLATEURL))
    {
        SendAlert(GetMessage(MSG_TEMPLATES));
        return (false);
    }
    return (DoProcessTemplate($TEMPLATEDIR,$TEMPLATEURL,$s_template,$a_lines,
                                $a_values,$s_missing,$s_subs_func));
}
 
    //
    // Output the given HTML template after filling in the fields.
    //
function OutputTemplate($s_template,$a_values)
{
    $a_lines = array();
    if (!ProcessTemplate($s_template,$a_lines,$a_values,"",'SubstituteValueForPage'))
        Error("template_failed",GetMessage(MSG_TEMPLATE_FAILED,
                                    array("NAME"=>$s_template)),false,false);
    else
    {
        for ($ii = 0 ; $ii < count($a_lines) ; $ii++)
            echo $a_lines[$ii]."\n";
    }
}
 
    //
    // This function handles input type "text" and "password"
    //
function FixInputText($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <input type="text" name="thename"...
        // and change it to:
        //  <input type="text" name="thename" value="thevalue" ...
        //
        // Note that the value attribute must appear *after* the
        // type and name attributes.
        //
 
        //
        // first strip any current value attribute for the field
        //
 
        //
        // (?:) is a grouping subpattern that does no capturing
        //
 
        // handle type attribute first
    $s_pat  = '/(<\s*input[^>]*type="(?:text|password)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*)(value="[^"]*")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:text|password)"[^>]*)(value="[^"]*")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        //
        // now add in the new value
        //
    $s_repl  = '$1 value="'.htmlspecialchars($s_value).'" $2>';
 
        // handle type attribute first
    $s_pat  = '/(<\s*input[^>]*type="(?:text|password)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:text|password)"[^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles textareas.
    //
function FixTextArea($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <textarea name="thename"...>value</textarea>
        // and change it to:
        //  <textarea name="thename"...>new value</textarea>
        //
 
    $s_pat  = '/(<\s*textarea[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*)>.*?<\s*\/\s*textarea\s*>';
    $s_pat .= '/ims';
        //
        // we exclude the closing '>' from the match above so that
        // we can put it below.  We need to do this so that the replacement
        // string is not faulty if the value begins with a digit:
        //      $19 Some Street
        //
    $s_repl = '$1>'.htmlspecialchars($s_value).'</textarea>';
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles radio buttons and non-array checkboxes.
    //
function FixButton($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <input type="radio" name="thename" value="thevalue" ...
        // and change it to:
        //  <input type="radio" name="thename" value="thevalue" checked="checked"
        //
        // Note that the value attribute must appear *after* the
        // type and name attributes.
        //
 
        //
        // first strip any current checked attributes
        //
 
        //
        // (?:) is a grouping subpattern that does no capturing
        //
 
        // handle type attribute first
        // match: input tag with type 'radio' or 'checkbox' with attribute
        // 'checked' or 'checked="checked"'
        //              <A NAME="PatternInfo">
        //      [^>]*?[^"\w] matches up to a word boundary starting with
        //      'checked' but not '"checked'
        //      (="checked"|(?=[^"\w]))? this matches:
        //              nothing
        //              ="checked"
        //              any character except a word character or " (without
        //              consuming it)
        //
    $s_pat  = '/(<\s*input[^>]*type="(?:radio|checkbox)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:radio|checkbox)"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle type attribute first
    $s_pat  = '/(<\s*input[^>]*type="(?:radio|checkbox)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*value="';
    $s_pat .= preg_quote($s_value,"/");
    $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$2 checked="checked" $3>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:radio|checkbox)"[^>]*value="';
    $s_pat .= preg_quote($s_value,"/");
    $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$2 checked="checked" $3>',$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles checkboxes as an array of values.
    //
function FixCheckboxes($s_name,$a_values,$s_buf)
{
    //global $aDebug;
 
        //
        // we search for:
        //  <input type="checkbox" name="thename" value="thevalue" ...
        // and change it to:
        //  <input type="checkbox" name="thename" value="thevalue" checked
        //
        // Note that the value attribute must appear *after* the
        // type and name attributes.
        //
 
        //
        // first strip any current checked attributes
        //
    //$aDebug[] = "FixCheckboxes: Name='$s_name'";
 
        // handle type attribute first
        // see <A HREF="fmbadhandler.php#PatternInfo">
    $s_pat  = '/(<\s*input[^>]*type="checkbox"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '\[]"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '\[]"[^>]*type="checkbox"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
    foreach ($a_values as $s_value)
    {
            // handle type attribute first
        $s_pat  = '/(<\s*input[^>]*type="checkbox"[^>]*name="';
        $s_pat .= preg_quote($s_name,"/");
        $s_pat .= '\[\]"[^>]*value="';
        $s_pat .= preg_quote($s_value,"/");
        $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
        $s_pat .= '/ims';
        $s_buf = preg_replace($s_pat,'$1$2 checked="checked"$3>',$s_buf);
        //$aDebug[] = "Name='$s_name', pat='$s_pat'";
 
            // handle name attribute first
        $s_pat  = '/(<\s*input[^>]*name="';
        $s_pat .= preg_quote($s_name,"/");
        $s_pat .= '\[\]"[^>]*type="checkbox"[^>]*value="';
        $s_pat .= preg_quote($s_value,"/");
        $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
        $s_pat .= '/ims';
        $s_buf = preg_replace($s_pat,'$1$2 checked="checked">',$s_buf);
    }
    return ($s_buf);
}
 
    //
    // This function handles selects.
    //
function FixSelect($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <select name="thename"...>
        //  <option value="thevalue">...</option>
        //  </select>
        //
 
    $s_pat  = '/(<\s*select[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '".*?<\s*option[^>]*value="';
    $s_pat .= preg_quote($s_value,"/");
    $s_pat .= '"[^>]*)>';
    $s_pat .= '/ims';
    $s_repl = '$1 selected="selected">';
//  echo "<p>pat: ".htmlspecialchars($s_pat);
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles multiple selects.
    //
function FixMultiSelect($s_name,$a_values,$s_buf)
{
        //
        // we search for:
        //  <select name="thename"...>
        //  <option value="thevalue">...</option>
        //  </select>
        //
 
    foreach ($a_values as $s_value)
    {
        $s_pat  = '/(<\s*select[^>]*name="';
        $s_pat .= preg_quote($s_name,"/");
        $s_pat .= '\[\]".*?<\s*option[^>]*value="';
        $s_pat .= preg_quote($s_value,"/");
        $s_pat .= '"[^>]*)>';
        $s_pat .= '/ims';
        $s_repl = '$1 selected="selected">';
    //  echo "<p>pat: ".htmlspecialchars($s_pat);
        $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
    }
    return ($s_buf);
}
 
    //
    // This function unchecks all checkboxes and select options.
    //
function UnCheckStuff($s_buf)
{
    global  $php_errormsg;
 
        //
        // we search for:
        //  <input type="checkbox" ... checked
        // and remove "checked" (checked="checked" is OK too)
        //
        // Note that the check attribute must appear *after* the
        // type attribute.
        // see <A HREF="fmbadhandler.php#PatternInfo">
        //
 
    $s_pat  = '/(<\s*input[^>]*type="checkbox"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        //
        // we search for:
        //  <option... selected
        // and remove "selected" (selected="selected" is OK too)
        // see <A HREF="fmbadhandler.php#PatternInfo">
        //
 
    $s_pat  = '/(<\s*option[^>]*?[^"\w])selected(="selected"|(?=[^"\w]))?([^>]*)>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3>',$s_buf);
 
    return ($s_buf);
}
 
    //
    // Add the user agent to the url as a parameter called USER_AGENT.
    // This allows dynamic web sites to know what the user's browser is.
    //
function AddUserAgent($s_url)
{
    global  $aServerVars;
 
        //
        // check for ? in the name
        //
    $b_quest = (strpos($s_url,'?') !== false);
    unset($s_agent);
    if (isset($aServerVars['HTTP_USER_AGENT']))
        $s_agent = $aServerVars['HTTP_USER_AGENT'];
    if (isset($s_agent))
        $s_url .= ($b_quest ? '&' : '?')."USER_AGENT=".urlencode($s_agent);
    return ($s_url);
}
 
    //
    // Sets previous values in a form.
    //
function SetPreviousValues($s_form_buf,$a_values)
{
        //
        // Uncheck any checkboxes and select options
        //
    $s_form_buf = UnCheckStuff($s_form_buf);
    foreach ($a_values as $s_name=>$m_value)
    {
        if (is_array($m_value))
        {
                //
                // note that if no values are selected for a field,
                // then we will never get here for that field
                //
            $s_form_buf = FixCheckboxes($s_name,$m_value,$s_form_buf);
            $s_form_buf = FixMultiSelect($s_name,$m_value,$s_form_buf);
        }
        else
        {
                //
                // Fix the field if it's an input type "text" or "password".
                //
            $s_form_buf = FixInputText($s_name,$m_value,$s_form_buf);
                //
                // Fix the field if it's radio button.
                //
            $s_form_buf = FixButton($s_name,$m_value,$s_form_buf);
                //
                // Fix the field if it's a "textarea".
                //
            $s_form_buf = FixTextArea($s_name,$m_value,$s_form_buf);
                //
                // Fix the field if it's a "select".
                //
            $s_form_buf = FixSelect($s_name,$m_value,$s_form_buf);
        }
    }
    return ($s_form_buf);
}
 
    //
    // Open a URL, do value substitutions, and send to browser.
    //
function ProcessReturnToForm($s_url,$a_values)
{
    global  $aSubstituteErrors,$aSubstituteValues,$sSubstituteMissing;
    global  $php_errormsg;
 
        //
        // read the original form, and modify it to provide values
        // for the fields
        //
    if (!CheckValidURL($s_url))
        Error("invalid_url",GetMessage(MSG_RETURN_URL_INVALID,
                                    array("URL"=>$s_url)),false,false);
 
    $s_form_url = AddUserAgent($s_url);
    $s_error = "";
    $s_form_buf = GetURL($s_form_url,$s_error);
    if ($s_form_buf === false)
        Error("invalid_url",GetMessage(MSG_OPEN_URL,
                                array("URL"=>$s_form_url,
                                      "ERROR"=>$s_error.": ".(isset($php_errormsg) ?
                                            $php_errormsg : ""))),false,false);
 
    /*****
        This is not correct here, because this function is only called
        for non-template URLs.
        //
        // First, we do any "$var" substitutions
        //
 
        //
        // initialize the errors list
        //
    $aSubstituteErrors = array();
        //
        // initialize the values
        //
    $aSubstituteValues = $a_values;
    $sSubstituteMissing = $s_missing;
 
        //
        // search for words in this form:
        //      $word
        // where word begins with an alphabetic character and
        // consists of alphanumeric and underscore
        //
//    $s_form_buf = preg_replace_callback('/\$([a-z][a-z0-9_]*)/i',
//                                      'SubstituteValueForPage',$s_form_buf);
 
//  SendAlert("Error count=".count($aSubstituteErrors));
    if (count($aSubstituteErrors) != 0)
        Error("template_failed",
                    GetMessage(MSG_TEMPLATE_ERRORS,array("NAME"=>$s_template)).
                            implode("\n",$aSubstituteErrors),false,false);
    ******/
 
        //
        // Next, we replace or set actual field values.
        //
    echo SetPreviousValues($s_form_buf,$a_values);
}
 
    //
    // To return the URL for returning to a particular multi-page form URL.
    //
function GetReturnLink($s_this_script,$i_form_index)
{
    if (!CheckValidURL($s_this_script))
        Error("not_valid_url",GetMessage(MSG_RETURN_URL_INVALID,
                                array("URL"=>$s_this_script)),false,false);
 
    $a_params = array();
    $a_params[] = "return=$i_form_index";
    if (isset($aServerVars["QUERY_STRING"]))
        $a_params[] = $aServerVars["QUERY_STRING"];
    $a_params[] = session_name()."=".session_id();
    return (AddURLParams($s_this_script,$a_params));
}
 
    //
    // Process a multi-page form template.
    //
function ProcessMultiFormTemplate($s_template,$a_values,&$a_lines)
{
    global  $MULTIFORMURL,$MULTIFORMDIR,$SPECIAL_VALUES,$aSessionVars;
 
    if (empty($MULTIFORMDIR) && empty($MULTIFORMURL))
    {
        SendAlert(GetMessage(MSG_MULTIFORM));
        return (false);
    }
    $i_index = $aSessionVars["FormIndex"];
    $a_values["this_form_url"] = $aSessionVars["FormList"][$i_index]["URL"];
    //$a_values["prev_form"] = GetReturnLink($SPECIAL_VALUES["this_form"]);
    return (DoProcessTemplate($MULTIFORMDIR,$MULTIFORMURL,$s_template,$a_lines,
                            $a_values,"",'SubstituteValueForPage'));
}
 
    //
    // Output the multi-form template after filling in the fields.
    //
function OutputMultiFormTemplate($s_template,$a_values)
{
    $a_lines = array();
    if (!ProcessMultiFormTemplate($s_template,$a_values,$a_lines))
        Error("multi_form_failed",GetMessage(MSG_MULTIFORM_FAILED,
                                    array("NAME"=>$s_template)),false,false);
    else
    {
        $n_lines = count($a_lines);
        $s_buf = "";
        for ($ii = 0 ; $ii < $n_lines ; $ii++)
        {
            $s_buf .= $a_lines[$ii]."\n";
            unset($a_lines[$ii]);       // free memory (hopefully)
        }
        unset($a_lines);       // free memory (hopefully)
 
        global  $aSessionVars;
 
        if (isset($aSessionVars["FormKeep"]))
                //
                // put in any values that are being forward-remembered
                //
            echo SetPreviousValues($s_buf,$aSessionVars["FormKeep"]);
        else
            echo $s_buf;
    }
}
 
    //
    // Insert a preamble into a MIME message.
    //
function MimePreamble(&$a_lines,$a_mesg = array())
{
    $a_preamble = explode("\n",GetMessage(MSG_MIME_PREAMBLE));
    foreach ($a_preamble as $s_line)
        $a_lines[] = $s_line.HEAD_CRLF;
 
    $a_lines[] = HEAD_CRLF;     // blank line
    $b_need_blank = false;
    foreach ($a_mesg as $s_line)
    {
        $a_lines[] = $s_line.HEAD_CRLF;
        if (!empty($s_line))
            $b_need_blank = true;
    }
    if ($b_need_blank)
        $a_lines[] = HEAD_CRLF;     // blank line
}
 
    //
    // Create the HTML mail
    //
function HTMLMail(&$a_lines,&$a_headers,$s_body,$s_template,$s_missing,$s_filter,
                            $s_boundary,$a_raw_fields,$b_no_plain)
{
    $s_charset = GetMailOption("CharSet");
    if (!isset($s_charset))
        $s_charset = "ISO-8859-1";
    if ($b_no_plain)
    {
        $b_multi = false;
            //
            // don't provide a plain text version - just the HTML
            //
        $a_headers['Content-Type'] = "text/html; charset=$s_charset";
    }
    else
    {
        $b_multi = true;
        $a_headers['Content-Type'] = "multipart/alternative; boundary=\"$s_boundary\"";
 
        $a_pre_lines = explode("\n",GetMessage(MSG_MIME_HTML,
                                                array("NAME"=>$s_template)));
 
        MimePreamble($a_lines,$a_pre_lines);
 
            //
            // first part - the text version only
            //
        $a_lines[] = "--$s_boundary".HEAD_CRLF;
        $a_lines[] = "Content-Type: text/plain; charset=$s_charset".HEAD_CRLF;
        $a_lines[] = HEAD_CRLF;     // blank line
            //
            // treat the body like one line, even though it isn't
            //
        $a_lines[] = $s_body;
        $a_lines[] = HEAD_CRLF;     // blank line
            //
            // second part - the HTML version
            //
        $a_lines[] = "--$s_boundary".HEAD_CRLF;
        $a_lines[] = "Content-Type: text/html; charset=$s_charset".HEAD_CRLF;
        $a_lines[] = HEAD_CRLF;     // blank line
    }
 
    $a_html_lines = array();
    if (!ProcessTemplate($s_template,$a_html_lines,$a_raw_fields,$s_missing))
        return (false);
 
    if (!empty($s_filter))
            //
            // treat the data like one line, even though it isn't
            //
        $a_lines[] = Filter($s_filter,$a_html_lines);
    else
        foreach ($a_html_lines as $s_line)
            $a_lines[] = $s_line;
 
    if ($b_multi)
    {
            //
            // end
            //
        $a_lines[] = "--$s_boundary--".HEAD_CRLF;
        $a_lines[] = HEAD_CRLF;     // blank line
    }
    return (true);
}
 
    //
    // Add the contents of a file in base64 encoding.
    //
function AddFile(&$a_lines,$s_file_name,$i_file_size,$b_remove = true)
{
    global  $php_errormsg;
 
@   $fp = fopen($s_file_name,"rb");
    if ($fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$s_file_name,
                                            "TYPE"=>"attachment",
                                            "ERROR"=>CheckString($php_errormsg))));
        return (false);
    }
        //
        // PHP under IIS has problems with the filesize function when
        // the file is on another drive.  So, we replaced a call
        // to filesize with the $i_file_size parameter (this occurred
        // in version 3.01).
        //
    $s_contents = fread($fp,$i_file_size);
        //
        // treat as a single line, even though it isn't
        //
    $a_lines[] = chunk_split(base64_encode($s_contents));
    fclose($fp);
    if ($b_remove)
        @unlink($s_file_name);
    return (true);
}
 
    //
    // Add the contents of a string in base64 encoding.
    //
function AddData(&$a_lines,$s_data)
{
        //
        // treat as a single line, even though it isn't
        //
    $a_lines[] = chunk_split(base64_encode($s_data));
    return (true);
}
    //
    // Check if a file is a valid uploaded file.
    //
function IsUploadedFile($a_file_spec)
{
        //
        // $a_file_spec['moved'] is our own internal flag to say we've
        // saved the file
        //
    if (isset($a_file_spec['moved']) && $a_file_spec['moved'])
        return (true);
    return (is_uploaded_file($a_file_spec['tmp_name']));
}
 
    //
    // Save an uploaded file to the repository directory.
    //
function SaveFileInRepository(&$a_file_spec)
{
    global  $php_errormsg,$FILE_REPOSITORY;
 
        //
        // if a replacement name has been specified, use that, otherwise
        // use the original name
        //
    if (isset($a_file_spec['new_name']))
        $s_file_name = basename($a_file_spec['new_name']);
    else
        $s_file_name = basename($a_file_spec['name']);
    $s_dest = $FILE_REPOSITORY."/".$s_file_name;
 
    $b_ok = true;
    $s_error = "";
 
    if (isset($a_file_spec['saved_as']) && !empty($a_file_spec['saved_as']))
        $s_srce = $a_file_spec['saved_as'];
    else
        $s_srce = $a_file_spec['tmp_name'];
 
    if (!FILE_OVERWRITE)
    {
        clearstatcache();
        if (@file_exists($s_dest))
        {
            $b_ok = false;
            $s_error = GetMessage(MSG_SAVE_FILE_EXISTS,array("FILE"=>$s_dest));
        }
    }
    if (MAX_FILE_UPLOAD_SIZE != 0 &&
        $a_file_spec['size'] > MAX_FILE_UPLOAD_SIZE*1024)
            //
            // this exits
            //
        UserError("upload_size",GetMessage(MSG_FILE_UPLOAD_SIZE,
                                  array("NAME"=>$a_file_spec['name'],
                                        "SIZE"=>$a_file_spec['size'],
                                        "MAX"=>MAX_FILE_UPLOAD_SIZE)));
    if ($b_ok)
    {
        if (isset($a_file_spec['saved_as']) && !empty($a_file_spec['saved_as']))
        {
            if (!copy($s_srce,$s_dest) || !@unlink($s_srce))
                $b_ok = false;
        }
        else
        {
            if (!move_uploaded_file($s_srce,$s_dest))
                $b_ok = false;
        }
        if ($b_ok)
        {
                //
                // Flag to say it's been put in the repository.
                //
            $a_file_spec['in_repository'] = true;
                //
                // Its new location
                //
            $a_file_spec['saved_as'] = $s_dest;
                //
                // Now that the file has been saved, "is_uploaded_file"
                // will return false.  So, we create a flag to say it was
                // valid.
                //
            $a_file_spec['moved'] = true;
        }
        else
            $s_error = $php_errormsg;
    }
    if (!$b_ok)
    {
        SendAlert(GetMessage(MSG_SAVE_FILE,array(
                            "FILE"=>$s_srce,
                            "DEST"=>$s_dest,
                            "ERR"=>$s_error)));
        return (false);
    }
        //
        // ignore chmod fails (other than reporting them)
        //
    if (FILE_MODE != 0 && !chmod($s_dest,FILE_MODE))
        SendAlert(GetMessage(MSG_CHMOD,array(
                            "FILE"=>$s_dest,
                            "MODE"=>FILE_MODE,
                            "ERR"=>$s_error)));
    return (true);
}
 
    //
    // Save all uploaded files to the repository directory.
    //
function SaveAllFilesToRepository()
{
    global  $aFileVars;
 
    if (!FILEUPLOADS || $FILE_REPOSITORY === "")
            //
            // nothing to do
            //
        return (true);
 
    foreach ($aFileVars as $m_file_key=>$a_upload)
    {
            //
            // One customer reported:
            //  Possible file upload attack detected: name='' temp name='none'
            // on PHP 4.1.2 on RAQ4.
            // So, we now also test for 'name'.
            //
        if (!isset($a_upload['tmp_name']) || empty($a_upload['tmp_name']) ||
            !isset($a_upload['name']) || empty($a_upload['name']))
            continue;
        if (isset($a_upload['in_repository']) && $a_upload['in_repository'])
                //
                // already saved
                //
            continue;
        if (!IsUploadedFile($a_upload))
        {
            SendAlert(GetMessage(MSG_FILE_UPLOAD_ATTACK,
                            array("NAME"=>$a_upload['name'],
                                    "TEMP"=>$a_upload['tmp_name'],
                                    "FLD"=>$m_file_key)));
            continue;
        }
        if (!SaveFileInRepository($aFileVars[$m_file_key]))
            return (false);
    }
    return (true);
}
 
    //
    // Save an uploaded file for later processing.
    //
function SaveUploadedFile(&$a_file_spec,$s_prefix)
{
    global  $php_errormsg;
 
    $s_dest = GetScratchPadFile($s_prefix);
    if (!move_uploaded_file($a_file_spec['tmp_name'],$s_dest))
    {
        SendAlert(GetMessage(MSG_SAVE_FILE,array(
                            "FILE"=>$a_file_spec['tmp_name'],
                            "DEST"=>$s_dest,
                            "ERR"=>$php_errormsg)));
        return (false);
    }
    $a_file_spec['saved_as'] = $s_dest;
    $a_file_spec['moved'] = true;
    return (true);
}
 
    //
    // Remove old files from the scratchpad directory.
    //
function CleanScratchPad($s_prefix = "")
{
    global  $lNow,$CLEANUP_TIME,$CLEANUP_CHANCE;
    global  $php_errormsg,$SCRATCH_PAD;
 
    if (!isset($SCRATCH_PAD) || empty($SCRATCH_PAD))
            //
            // no scratchpad to cleanup!
            //
        return;
    if ($CLEANUP_TIME <= 0)
            //
            // cleanup disabled
            //
        return;
        //
        // compute chance of cleanup
        //
    if ($CLEANUP_CHANCE < 100)
    {
        $i_rand = mt_rand(1,100);
        if ($i_rand > $CLEANUP_CHANCE)
            return;
    }
    if (($f_dir = @opendir($SCRATCH_PAD)) === false)
    {
        Error("open_scratch_pad",GetMessage(MSG_OPEN_SCRATCH_PAD,array(
                                        "DIR"=>$SCRATCH_PAD,
                                        "ERR"=>$php_errormsg)),false,false);
        return;
    }
    $i_len = strlen($s_prefix);
    while (($s_file = readdir($f_dir)) !== false)
    {
        $s_path = $SCRATCH_PAD."/".$s_file;
        if (is_file($s_path) && ($i_len == 0 || substr($s_file,0,$i_len) == $s_prefix))
        {
            if (($a_stat = @stat($s_path)) !== false)
            {
                if (isset($a_stat['mtime']))
                    $l_time = $a_stat['mtime'];
                else
                    $l_time = $a_stat[9];
                if (($lNow - $l_time) / 60 >= $CLEANUP_TIME)
                    @unlink($s_path);
            }
        }
    }
    closedir($f_dir);
}
 
    //
    // Save all uploaded files for later processing.
    //
function SaveAllUploadedFiles(&$a_file_vars)
{
    global  $php_errormsg,$SCRATCH_PAD;
 
    $s_prefix = "UPLD";
    if (!isset($SCRATCH_PAD) || empty($SCRATCH_PAD))
    {
        Error("need_scratch_pad",GetMessage(MSG_NEED_SCRATCH_PAD),false,false);
        return (false);
    }
 
        //
        // remove old uploaded files that have not been moved out.
        //
    CleanScratchPad($s_prefix);
 
    foreach (array_keys($a_file_vars) as $m_file_key)
    {
        $a_upload = &$a_file_vars[$m_file_key];
            //
            // One customer reported:
            //  Possible file upload attack detected: name='' temp name='none'
            // on PHP 4.1.2 on RAQ4.
            // So, we now also test for 'name'.
            //
        if (!isset($a_upload['tmp_name']) || empty($a_upload['tmp_name']) ||
            !isset($a_upload['name']) || empty($a_upload['name']))
            continue;
            //
            // ensure we don't move the file more than once
            //
        if (!isset($a_upload['saved_as']) || empty($a_upload['saved_as']))
            if (!IsUploadedFile($a_upload))
                SendAlert(GetMessage(MSG_FILE_UPLOAD_ATTACK,
                                array("NAME"=>$a_upload['name'],
                                        "TEMP"=>$a_upload['tmp_name'],
                                        "FLD"=>$m_file_key)));
            elseif (!SaveUploadedFile($a_upload,$s_prefix))
                return (false);
    }
    return (true);
}
 
    //
    // Attach a file to the body of a MIME formatted email.  $a_lines is the
    // current body, and is modified to include the file.
    // $a_file_spec must have the following values (just like an uploaded
    // file specification):
    //      name        the name of the file
    //      type        the mime type
    //      tmp_name    the name of the temporary file
    //      size        the size of the temporary file
    //
    // Alternatively, you supply the following instead of tmp_name and size:
    //      data        the data to attach
    //
function AttachFile(&$a_lines,$s_att_boundary,$a_file_spec,$s_charset)
{
    $a_lines[] = "--$s_att_boundary".HEAD_CRLF;
        //
        // if a replacement name has been specified, use that, otherwise
        // use the original name
        //
    if (isset($a_file_spec['new_name']))
        $s_file_name = $a_file_spec['new_name'];
    else
        $s_file_name = $a_file_spec['name'];
    $s_file_name = str_replace('"','',$s_file_name);
    $s_mime_type = $a_file_spec['type'];
            //
            // The following says that the data is encoded in
            // base64 and is an attachment and that once decoded the
            // character set of the decoded data is $s_charset.
            // (See RFC 1521 Section 5.)
            //
    $a_lines[] = "Content-Type: $s_mime_type; name=\"$s_file_name\"; charset=$s_charset".HEAD_CRLF;
    $a_lines[] = "Content-Transfer-Encoding: base64".HEAD_CRLF;
    $a_lines[] = "Content-Disposition: attachment; filename=\"$s_file_name\"".HEAD_CRLF;
    $a_lines[] = HEAD_CRLF;         // blank line
    if (isset($a_file_spec['tmp_name']) && isset($a_file_spec['size']))
    {
        $s_srce = $a_file_spec['tmp_name'];
            //
            // check if the file has been saved elsewhere
            //
        if (isset($a_file_spec['saved_as']) && !empty($a_file_spec['saved_as']))
            $s_srce = $a_file_spec['saved_as'];
        return (AddFile($a_lines,$s_srce,$a_file_spec['size']));
    }
    if (!isset($a_file_spec['data']))
    {
        SendAlert(GetMessage(MSG_ATTACH_DATA));
        return (false);
    }
    return (AddData($a_lines,$a_file_spec['data']));
}
 
    //
    // Reformat the email to be in MIME format.
    // Process file attachments and and fill out any
    // specified HTML template.
    //
function MakeMimeMail(&$s_body,&$a_headers,$a_raw_fields,$s_template = "",
                    $s_missing = NULL,$b_no_plain = false,
                    $s_filter = "",$a_file_vars = array(),
                    $a_attach_spec = array())
{
    global  $FM_VERS,$aPHPVERSION;
    global  $SPECIAL_VALUES,$FILTER_ATTRIBS,$FILE_REPOSITORY;
 
    $s_charset = GetMailOption("CharSet");
    if (!isset($s_charset))
        $s_charset = "ISO-8859-1";
    $b_att = $b_html = false;
    $b_got_filter = (isset($s_filter) && !empty($s_filter));
    if (isset($s_template) && !empty($s_template))
    {
            //
            // need PHP 4.0.5 for the preg_replace_callback function
            //
        if (!IsPHPAtLeast("4.0.5"))
        {
            SendAlert(GetMessage(MSG_PHP_HTML_TEMPLATES,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
            return (false);
        }
        $b_html = true;
    }
    if (count($a_file_vars) > 0)
    {
        if (!IsPHPAtLeast("4.0.3"))
        {
            SendAlert(GetMessage(MSG_PHP_FILE_UPLOADS,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
            return (false);
        }
        if (!FILEUPLOADS)
            SendAlert(GetMessage(MSG_FILE_UPLOAD));
        elseif ($FILE_REPOSITORY === "")    // if storing on the server, don't attach
            foreach ($a_file_vars as $a_upload)
            {
                    //
                    // One customer reported:
                    //  Possible file upload attack detected: name='' temp name='none'
                    // on PHP 4.1.2 on RAQ4.
                    // So, we now also test for 'name'.
                    //
                if (isset($a_upload['tmp_name']) && !empty($a_upload['tmp_name']) &&
                    isset($a_upload['name']) && !empty($a_upload['name']))
                {
                    $b_att = true;
                    break;
                }
            }
    }
        //
        // check for an internally-generated attachment
        //
    if (isset($a_attach_spec["Data"]))
        $b_att = true;
 
    $s_uniq = md5($s_body);
    $s_body_boundary = "BODY$s_uniq";
    $s_att_boundary = "PART$s_uniq";
    $a_headers['MIME-Version'] = "1.0 (produced by FormMail $FM_VERS from www.tectite.com)";
 
        //
        // if the filter strips formatting, then we'll only have plain text
        // to send, even after the template has been used
        //
    if ($b_got_filter && IsFilterAttribSet($s_filter,"Strips"))
            //
            // no HTML if the filter strips the formatting
            //
        $b_html = false;
    $a_new = array();
    if ($b_att)
    {
        $a_headers['Content-Type'] = "multipart/mixed; boundary=\"$s_att_boundary\"";
 
        MimePreamble($a_new);
            //
            // add the body of the email
            //
        $a_new[] = "--$s_att_boundary".HEAD_CRLF;
        if ($b_html)
        {
            $a_lines = $a_local_headers = array();
            if (!HTMLMail($a_lines,$a_local_headers,$s_body,$s_template,
                            $s_missing,($b_got_filter) ? $s_filter : "",
                            $s_body_boundary,$a_raw_fields,$b_no_plain))
                return (false);
            $a_new = array_merge($a_new,ExpandMailHeadersArray($a_local_headers));
            $a_new[] = HEAD_CRLF;       // blank line after header
            $a_new = array_merge($a_new,$a_lines);
        }
        else
        {
            $a_new[] = "Content-Type: text/plain; charset=$s_charset".HEAD_CRLF;
            $a_new[] = HEAD_CRLF;       // blank line
                //
                // treat the body like one line, even though it isn't
                //
            $a_new[] = $s_body;
        }
            //
            // now add the attachments or save to the $FILE_REPOSITORY
            //
        if (FILEUPLOADS && $FILE_REPOSITORY === "")
            foreach ($a_file_vars as $m_file_key=>$a_upload)
            {
                    //
                    // One customer reported:
                    //  Possible file upload attack detected: name='' temp name='none'
                    // on PHP 4.1.2 on RAQ4.
                    // So, we now also test for 'name'.
                    //
                if (!isset($a_upload['tmp_name']) || empty($a_upload['tmp_name']) ||
                    !isset($a_upload['name']) || empty($a_upload['name']))
                    continue;
                if (!IsUploadedFile($a_upload))
                {
                    SendAlert(GetMessage(MSG_FILE_UPLOAD_ATTACK,
                                    array("NAME"=>$a_upload['name'],
                                          "TEMP"=>$a_upload['tmp_name'],
                                          "FLD"=>$m_file_key)));
                    continue;
                }
                if (MAX_FILE_UPLOAD_SIZE != 0 &&
                    $a_upload['size'] > MAX_FILE_UPLOAD_SIZE*1024)
                    UserError("upload_size",GetMessage(MSG_FILE_UPLOAD_SIZE,
                                              array("NAME"=>$a_upload['name'],
                                                    "SIZE"=>$a_upload['size'],
                                                    "MAX"=>MAX_FILE_UPLOAD_SIZE)));
                if (!AttachFile($a_new,$s_att_boundary,$a_upload,$s_charset))
                    return (false);
            }
        if (isset($a_attach_spec["Data"]))
        {
                //
                // build a specification similar to a file upload
                //
            $a_file_spec["name"] = isset($a_attach_spec["Name"]) ?
                                        $a_attach_spec["Name"] :
                                        "attachment.dat";
            $a_file_spec["type"] = isset($a_attach_spec["MIME"]) ?
                                        $a_attach_spec["MIME"] :
                                        "text/plain";
            $a_file_spec["data"] = $a_attach_spec["Data"];
            if (!AttachFile($a_new,$s_att_boundary,$a_file_spec,
                                isset($a_attach_spec["CharSet"]) ?
                                $a_attach_spec["CharSet"] :
                                $s_charset))
                return (false);
        }
        $a_new[] = "--$s_att_boundary--".HEAD_CRLF;     // the end
        $a_new[] = HEAD_CRLF;           // blank line
    }
    elseif ($b_html)
    {
        if (!HTMLMail($a_new,$a_headers,$s_body,$s_template,
                            $s_missing,($b_got_filter) ? $s_filter : "",
                            $s_body_boundary,$a_raw_fields,$b_no_plain))
            return (false);
    }
    else
    {
        $a_headers['Content-Type'] = "text/plain; charset=$s_charset";
            //
            // treat the body like one line, even though it isn't
            //
        $a_new[] = $s_body;
    }
 
    $s_body = JoinLines(BODY_LF,$a_new);
    return (true);
}
 
    //
    // to make a From line for the email
    //
function MakeFromLine($s_email,$s_name)
{
    $s_line = "";
    if (!empty($s_email))
        $s_line .= $s_email." ";
    if (!empty($s_name))
        $s_line .= "(".$s_name.")";
    return ($s_line);
}
 
    //
    // Return two sets of plain text output: the filtered fields and the
    // non-filtered fields.
    //
function GetFilteredOutput($a_fld_order,$a_clean_fields,$s_filter,$a_filter_list)
{
        //
        // find the non-filtered fields and make unfiltered text from them
        //
    $a_unfiltered_list = array();
    $n_flds = count($a_fld_order);
    for ($ii = 0 ; $ii < $n_flds ; $ii++)
        if (!in_array($a_fld_order[$ii],$a_filter_list))
            $a_unfiltered_list[] = $a_fld_order[$ii];
    $s_unfiltered_results = MakeFieldOutput($a_unfiltered_list,$a_clean_fields);
        //
        // filter the specified fields only
        //
    $s_filtered_results = MakeFieldOutput($a_filter_list,$a_clean_fields);
    $s_filtered_results = Filter($s_filter,$s_filtered_results);
    return (array($s_unfiltered_results,$s_filtered_results));
}
 
    //
    // Make a plain text email body
    //
function MakePlainEmail($a_fld_order,$a_clean_fields,
                        $s_to,$s_cc,$s_bcc,$a_raw_fields,$s_filter,$a_filter_list)
{
    global  $SPECIAL_VALUES,$aPHPVERSION;
 
    $s_unfiltered_results = $s_filtered_results = "";
    $b_got_filter = (isset($s_filter) && !empty($s_filter));
    if ($b_got_filter)
        if (isset($a_filter_list) && count($a_filter_list) > 0)
            $b_limited_filter = true;
        else
            $b_limited_filter = false;
    $b_used_template = false;
    if (IsMailOptionSet("PlainTemplate"))
    {
            //
            // need PHP 4.0.5 for the preg_replace_callback function
            //
        if (!IsPHPAtLeast("4.0.5"))
            SendAlert(GetMessage(MSG_PHP_PLAIN_TEMPLATES,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
        else
        {
            $s_template = GetMailOption("PlainTemplate");
            if (ProcessTemplate($s_template,$a_lines,$a_raw_fields,
                                GetMailOption('TemplateMissing'),
                                'SubstituteValuePlain'))
            {
                $b_used_template = true;
                $s_unfiltered_results = implode(BODY_LF,$a_lines);
                if ($b_got_filter)
                {
                        //
                        // with a limited filter, the template goes unfiltered
                        // and the named fields get filtered
                        //
                    if ($b_limited_filter)
                        list($s_discard,$s_filtered_results) =
                                    GetFilteredOutput($a_fld_order,$a_clean_fields,
                                            $s_filter,$a_filter_list);
                    else
                    {
                        $s_filtered_results = Filter($s_filter,$s_unfiltered_results);
                        $s_unfiltered_results = "";
                    }
                }
            }
        }
    }
    if (!$b_used_template)
    {
        $res_hdr = "";
 
        if (IsMailOptionSet("DupHeader"))
        {
                //
                // write some standard mail headers
                //
            $res_hdr = "To: $s_to".BODY_LF;
            if (!empty($s_cc))
                $res_hdr .= "Cc: $s_cc".BODY_LF;
            if (!empty($SPECIAL_VALUES["email"]))
                $res_hdr .= "From: ".MakeFromLine($SPECIAL_VALUES["email"],
                                        $SPECIAL_VALUES["realname"]).BODY_LF;
            $res_hdr .= BODY_LF;
            if (IsMailOptionSet("StartLine"))
                $res_hdr .= "--START--".BODY_LF;        // signals the beginning of the text to filter
        }
 
            //
            // put the realname and the email address at the top of the results
            // (if not excluded)
            //
        if (!IsMailExcluded("realname"))
        {
            array_unshift($a_fld_order,"realname");
            $a_clean_fields["realname"] = $SPECIAL_VALUES["realname"];
        }
        if (!IsMailExcluded("email"))
        {
            array_unshift($a_fld_order,"email");
            $a_clean_fields["email"] = $SPECIAL_VALUES["email"];
        }
        if ($b_got_filter)
        {
            if ($b_limited_filter)
                list($s_unfiltered_results,$s_filtered_results) =
                            GetFilteredOutput($a_fld_order,$a_clean_fields,
                                    $s_filter,$a_filter_list);
            else
            {
                    //
                    // make text output and filter it (filter all fields)
                    //
                $s_filtered_results = MakeFieldOutput($a_fld_order,$a_clean_fields);
                $s_filtered_results = Filter($s_filter,$s_filtered_results);
            }
        }
        else
        {
//SendAlert("There are ".count($a_fld_order)." fields in the order array");
//SendAlert("Here is the clean fields array:\r\n".var_export($a_clean_fields,true));
            $s_unfiltered_results = MakeFieldOutput($a_fld_order,$a_clean_fields);
        }
        $s_unfiltered_results = $res_hdr.$s_unfiltered_results;
    }
    $s_results = $s_unfiltered_results;
    if ($b_got_filter && !empty($s_filtered_results))
    {
        if (!empty($s_results))
            $s_results .= BODY_LF;
        $s_results .= $s_filtered_results;
    }
    return (array($s_results,$s_unfiltered_results,$s_filtered_results));
}
 
    //
    // Return the list of fields to be filtered, FALSE if no list provided.
    //
function GetFilterList()
{
    global  $SPECIAL_VALUES;
 
        //
        // no filter means no list of fields
        //
    if (!empty($SPECIAL_VALUES["filter"]))
        if (isset($SPECIAL_VALUES["filter_fields"]) && !empty($SPECIAL_VALUES["filter_fields"]))
            return (TrimArray(explode(",",$SPECIAL_VALUES["filter_fields"])));
    return (false);
}
 
    //
    // send the given results to the given email addresses
    //
function SendResults($a_fld_order,$a_clean_fields,$s_to,$s_cc,$s_bcc,$a_raw_fields)
{
    global  $SPECIAL_VALUES,$aFileVars,$FILE_REPOSITORY,$FIXED_SENDER;
 
        //
        // check for a filter and how to use it
        //
    $b_got_filter = (isset($SPECIAL_VALUES["filter"]) && !empty($SPECIAL_VALUES["filter"]));
    $b_filter_attach = false;
    $a_attach_spec = array();
    $s_filter = "";
    $a_filter_list = array();
    if ($b_got_filter)
    {
        $s_filter = $SPECIAL_VALUES["filter"];
        $a_filter_list = GetFilterList();
        if ($a_filter_list === false)
        {
                //
                // not a limited filter, so filter all fields
                //
            $b_limited_filter = false;
            $a_filter_list = array();
        }
        else
            $b_limited_filter = true;
        $s_filter_attach_name = GetFilterOption("Attach");
        if (isset($s_filter_attach_name))
             if (!is_string($s_filter_attach_name) || empty($s_filter_attach_name))
                SendAlert(GetMessage(MSG_ATTACH_NAME));
            else
            {
                $b_filter_attach = true;
                $a_attach_spec = array("Name"=>$s_filter_attach_name);
                if (($s_mime = GetFilterAttrib($s_filter,"MIME")) !== false)
                    $a_attach_spec["MIME"] = $s_mime;
                    //
                    // Regarding the character set...
                    // A filter will not generally change the character set
                    // of the message, however, if it does, then we
                    // provide that information to the MIME encoder.
                    // Remember: this character set specification refers
                    // to the data *after* the effect of the filter
                    // has been reversed (e.g. an encrypted message
                    // in UTF-8 is in UTF-8 when it is decrypted).
                    //
                if (($s_cset = GetFilterAttrib($s_filter,"CharSet")) !== false)
                    $a_attach_spec["CharSet"] = $s_cset;
            }
    }
 
        //
        // check the need for MIME formatted mail
        //
    $b_mime_mail = (IsMailOptionSet("HTMLTemplate") || count($aFileVars) > 0 ||
                    $b_filter_attach);
 
        //
        // create the email header lines - CC, BCC, and From
        //
    $a_headers = array();
    if (!empty($s_cc))
        $a_headers['Cc'] = $s_cc;
        //
        // note that BCC is documented to not work prior to PHP 4.3
        //
    if (!empty($s_bcc))
    {
        global  $aPHPVERSION;
 
        if ($aPHPVERSION[0] < 4 || ($aPHPVERSION[0] == 4 && $aPHPVERSION[1] < 3))
            SendAlert(GetMessage(MSG_PHP_BCC,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
        $a_headers['Bcc'] = $s_bcc;
    }
        //
        // create the From address
        //
        // Some servers won't let you set the email address to the
        // submitter of the form.  Therefore, use FromAddr if it's been
        // specified to set the sender and the "From" address.
        //
    $s_sender = GetMailOption("FromAddr");
    if (!isset($s_sender))
    {
        $s_sender = "";
        if (!empty($SPECIAL_VALUES["email"]))
            $a_headers['From'] = MakeFromLine($SPECIAL_VALUES["email"],
                                            $SPECIAL_VALUES["realname"]);
    }
    elseif ($s_sender !== "")
        $s_sender = $a_headers['From'] = UnMangle($s_sender);
 
        /* 
         * Override sender if $FIXED_SENDER is set.
         */
    if ($FIXED_SENDER !== "")
        $s_sender = $FIXED_SENDER;
 
    if ($s_sender === "")
        if (SET_SENDER_FROM_EMAIL)
            $s_sender = $SPECIAL_VALUES["email"];
 
        //
        // special case: if there is only one non-special string value, then
        // format it as an email (unless an option says not to)
        //
    $a_keys = array_keys($a_raw_fields);
    if (count($a_keys) == 1 && is_string($a_raw_fields[$a_keys[0]]) &&
        !IsMailOptionSet("AlwaysList") && !IsMailOptionSet("DupHeader"))
    {
        if (IsMailExcluded($a_keys[0]))
            SendAlert("Exclusion of single field '".$a_keys[0]."' ignored");
        $s_value = $a_raw_fields[$a_keys[0]];
            //
            // replace carriage return/linefeeds with <br>
            //
        $s_value = str_replace("\r\n",'<br />',$s_value);
            //
            // replace lone linefeeds with <br>
            //
        $s_value = str_replace("\n",'<br />',$s_value);
            //
            // remove lone carriage returns
            //
        $s_value = str_replace("\r","",$s_value);
            //
            // replace all control chars with <br>
            //
        $s_value = preg_replace('/[[:cntrl:]]+/','<br />',$s_value);
            //
            // strip HTML (note that all the <br> above will now be
            // replaced with BODY_LF)
            //
        $s_value = StripHTML($s_value,BODY_LF);
 
        if ($b_mime_mail)
        {
            if ($b_got_filter)
            {
                    //
                    // filter the whole value (ignore filter_fields for this
                    // special case) if a filter has been specified
                    //
                $s_results = Filter($s_filter,$s_value);
                if ($b_filter_attach)
                {
                    $a_attach_spec["Data"] = $s_results;
                        //
                        // KeepInLine keeps the filtered version inline as well
                        // as an attachment
                        //
                    if (!IsFilterOptionSet("KeepInLine"))
                        $s_results = "";
                    $s_filter = ""; // no more filtering
                }
            }
            else
                $s_results = $s_value;
 
                //
                // send this single value off to get formatted in a MIME
                // email
                //
            if (!MakeMimeMail($s_results,$a_headers,$a_raw_fields,
                                GetMailOption('HTMLTemplate'),
                                GetMailOption('TemplateMissing'),
                                IsMailOptionSet("NoPlain"),
                                $s_filter,$aFileVars,$a_attach_spec))
                return (false);
        }
        elseif ($b_got_filter)
                //
                // filter the whole value (ignore filter_fields for this special case)
                // if a filter has been specified
                //
            $s_results = Filter($s_filter,$s_value);
        else
            $s_results = $s_value;
    }
    else
    {
        if ($b_mime_mail)
        {
                //
                // get the plain text version of the email then send it
                // to get MIME formatted
                //
            list($s_results,$s_unfiltered_results,$s_filtered_results) =
                            MakePlainEmail($a_fld_order,$a_clean_fields,
                                $s_to,$s_cc,$s_bcc,$a_raw_fields,$s_filter,
                                $a_filter_list);
            if ($b_filter_attach)
            {
                    //
                    // attached the filtered results
                    //
                $a_attach_spec["Data"] = $s_filtered_results;
                    //
                    // KeepInLine keeps the filtered version inline as well
                    // as an attachment
                    //
                if (!IsFilterOptionSet("KeepInLine"))
                        //
                        // put the unfiltered results in the body of the message
                        //
                    $s_results = $s_unfiltered_results;
                $s_filter = ""; // no more filtering
            }
            if (!MakeMimeMail($s_results,$a_headers,$a_raw_fields,
                                GetMailOption('HTMLTemplate'),
                                GetMailOption('TemplateMissing'),
                                IsMailOptionSet("NoPlain"),
                                $s_filter,$aFileVars,$a_attach_spec))
                return (false);
        }
        else
        {
            list($s_results,$s_unfiltered_results,$s_filtered_results) =
                            MakePlainEmail($a_fld_order,$a_clean_fields,
                                $s_to,$s_cc,$s_bcc,$a_raw_fields,$s_filter,
                                $a_filter_list);
            if (!$b_got_filter && IsMailOptionSet("CharSet"))
                    //
                    // sending plain text email, and the CharSet has been
                    // specified; include a header
                    //
                $a_headers['Content-Type'] = "text/plain; charset=".GetMailOption("CharSet");
        }
    }
 
        //
        // append the environment variables report
        //
    if (isset($SPECIAL_VALUES["env_report"]))
    {
        $s_results .= BODY_LF."==================================".BODY_LF;
        $s_results .= BODY_LF.GetEnvVars(TrimArray(explode(",",$SPECIAL_VALUES["env_report"])),BODY_LF);
    }
        //
        // now save uploaded files to the repository
        //
    if (FILEUPLOADS && $FILE_REPOSITORY !== "")
        if (!SaveAllFilesToRepository())
            return (false);
 
        //
        // send the mail - assumes the email addresses have already been checked
        //
    return (SendCheckedMail($s_to,$SPECIAL_VALUES["subject"],$s_results,
                                    $s_sender,$a_headers));
}
 
    //
    // append an entry to a log file
    //
function WriteLog($log_file)
{
    global  $SPECIAL_VALUES,$php_errormsg;
 
@   $log_fp = fopen($log_file,"a");
    if ($log_fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$log_file,
                                            "TYPE"=>"log",
                                            "ERROR"=>CheckString($php_errormsg))));
        return;
    }
    $date = gmdate("H:i:s d-M-y T");
    $entry = $date.":".$SPECIAL_VALUES["email"].",".
            $SPECIAL_VALUES["realname"].",".$SPECIAL_VALUES["subject"]."\n";
    fwrite($log_fp,$entry);
    fclose($log_fp);
}
 
    //
    // write the data to a comma-separated-values file
    //
function WriteCSVFile($s_csv_file,$a_vars)
{
    global  $SPECIAL_VALUES,$CSVSEP,$CSVINTSEP,$CSVQUOTE,$CSVOPEN,$CSVLINE;
 
        //
        // create an array of column values in the order specified
        // in $SPECIAL_VALUES["csvcolumns"]
        //
    $a_column_list = $SPECIAL_VALUES["csvcolumns"];
    if (!isset($a_column_list) || empty($a_column_list) || !is_string($a_column_list))
    {
        SendAlert(GetMessage(MSG_CSVCOLUMNS,array("VALUE"=>$a_column_list)));
        return;
    }
    if (!isset($s_csv_file) || empty($s_csv_file) || !is_string($s_csv_file))
    {
        SendAlert(GetMessage(MSG_CSVFILE,array("VALUE"=>$s_csv_file)));
        return;
    }
 
@   $fp = fopen($s_csv_file,"a".$CSVOPEN);
    if ($fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$s_csv_file,
                                            "TYPE"=>"CSV",
                                            "ERROR"=>CheckString($php_errormsg))));
        return;
    }
 
        //
        // convert the column list to an array, trim the names too
        //
    $a_column_list = TrimArray(explode(",",$a_column_list));
    $n_columns = count($a_column_list);
 
        //
        // if the file is currently empty, put the column names in the first line
        //
    if (filesize($s_csv_file) == 0)
    {
        for ($ii = 0 ; $ii < $n_columns ; $ii++)
        {
            fwrite($fp,$CSVQUOTE.$a_column_list[$ii].$CSVQUOTE);
            if ($ii < $n_columns-1)
                fwrite($fp,"$CSVSEP");
        }
        fwrite($fp,$CSVLINE);
    }
 
//  $debug = "";
//  $debug .= "gpc -> ".get_magic_quotes_gpc()."\n";
//  $debug .= "runtime -> ".get_magic_quotes_runtime()."\n";
    for ($ii = 0 ; $ii < $n_columns ; $ii++)
    {
        $s_col_name = $a_column_list[$ii];
            //
            // columns can be missing from some form submission and present
            // from others
            //
        if (isset($a_vars[$s_col_name]))
            $m_value = $a_vars[$s_col_name];
        else
            $m_value = "";
 
        if (LIMITED_IMPORT)
                //
                // the target database doesn't understand escapes, so
                // remove various things, including newlines and truncate
                //
            $m_value = CleanValue($m_value,false);
        else
                //
                // the target database does understand escapes, so
                // we have to slash any slashes
                //
            $m_value = str_replace("\\","\\\\",$m_value);
            //
            // convert quotes, depending on the setting of $CSVQUOTE
            //
        switch ($CSVQUOTE)
        {
        case '"':
                    //
                    // convert double quotes in the data to single quotes
                    //
            $m_value = str_replace("\"","'",$m_value);
            break;
        case '\'':
                    //
                    // convert single quotes in the data to double quotes
                    //
            $m_value = str_replace("'","\"",$m_value);
            break;
        default:
                //
                // otherwise, leave the data unchanged
                //
            break;
        }
            //
            // we handle arrays and strings
            //
        if (is_array($m_value))
                //
                // separate the values with the internal field separator
                //
            $m_value = implode("$CSVINTSEP",$m_value);
 
//      $debug .= $a_column_list[$ii]." => ".$m_value."\n";
        fwrite($fp,$CSVQUOTE.$m_value.$CSVQUOTE);
        if ($ii < $n_columns-1)
            fwrite($fp,"$CSVSEP");
    }
    fwrite($fp,$CSVLINE);
    fclose($fp);
//  CreatePage($debug);
//  exit;
}
 
function CheckConfig()
{
    global  $TARGET_EMAIL,$CONFIG_CHECK;
 
    $a_mesgs = array();
    if (in_array("TARGET_EMAIL",$CONFIG_CHECK))
    {
            //
            // $TARGET_EMAIL values should begin with ^ and end with $
            //
        for ($ii = 0 ; $ii < count($TARGET_EMAIL) ; $ii++)
        {
            $s_pattern = $TARGET_EMAIL[$ii];
            if (substr($s_pattern,0,1) != '^')
                $a_mesgs[] = GetMessage(MSG_TARG_EMAIL_PAT_START,
                                        array("PAT"=>$s_pattern));
            if (substr($s_pattern,-1) != '$')
                $a_mesgs[] = GetMessage(MSG_TARG_EMAIL_PAT_END,
                                        array("PAT"=>$s_pattern));
        }
    }
    if (count($a_mesgs) > 0)
        SendAlert(GetMessage(MSG_CONFIG_WARN,
                        array("MESGS"=>implode("\n",$a_mesgs))),false,true);
}
 
    //
    // append an entry to the Auto Responder log file
    //
function WriteARLog($s_to,$s_subj,$s_info)
{
    global  $LOGDIR,$AUTORESPONDLOG,$aServerVars,$php_errormsg;
 
    if (!isset($LOGDIR) || !isset($AUTORESPONDLOG) ||
            empty($LOGDIR) || empty($AUTORESPONDLOG))
        return;
 
    $log_file = $LOGDIR."/".$AUTORESPONDLOG;
@   $log_fp = fopen($log_file,"a");
    if ($log_fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$log_file,
                                            "TYPE"=>"log",
                                            "ERROR"=>CheckString($php_errormsg))));
        return;
    }
    $a_entry = array();
    $a_entry[] = gmdate("H:i:s d-M-y T");       // date/time in GMT
    $a_entry[] = $aServerVars['REMOTE_ADDR'];   // remote IP address
    $a_entry[] = $s_to;                         // target email address
    $a_entry[] = $s_subj;                       // subject line
    $a_entry[] = $s_info;                       // information
 
    $s_log_entry = implode(",",$a_entry)."\n";
    fwrite($log_fp,$s_log_entry);
    fclose($log_fp);
}
 
    //
    // Send an email response to the user.
    //
function AutoRespond($s_to,$s_subj,$a_values)
{
    global  $aPHPVERSION,$SPECIAL_VALUES,$FROM_USER;
 
        //
        // need PHP 4.0.5 for the preg_replace_callback function
        //
    if (!IsPHPAtLeast("4.0.5"))
    {
        SendAlert(GetMessage(MSG_PHP_AUTORESP,
                        array("PHPVERS"=>implode(".",$aPHPVERSION))));
        return (false);
    }
 
    $a_headers = array();
    $s_mail_text = "";
    $s_from_addr = GetAROption("FromAddr");
 
    if (!isset($s_from_addr))
    {
        $s_from_addr = "";
        if (isset($FROM_USER) && !empty($FROM_USER))
        {
            if ($FROM_USER != "NONE")
                $s_from_addr = $FROM_USER;
        }
        else
        {
            global  $SERVER;
 
            $s_from_addr = "FormMail@".$SERVER;
        }
    }
    else
        $s_from_addr = UnMangle($s_from_addr);
 
    if (!empty($s_from_addr))
        $a_headers['From'] = $s_from_addr;
 
    if (IsAROptionSet('PlainTemplate'))
    {
        $s_template = GetAROption("PlainTemplate");
        if (!ProcessTemplate($s_template,$a_lines,$a_values,
                                    GetAROption('TemplateMissing'),
                                    'SubstituteValuePlain'))
            return (false);
        $s_mail_text = implode(BODY_LF,$a_lines);
    }
    if (IsAROptionSet("HTMLTemplate"))
    {
        if (!MakeMimeMail($s_mail_text,$a_headers,$a_values,
                            GetAROption("HTMLTemplate"),
                            GetAROption('TemplateMissing')))
            return (false);
    }
    return (SendCheckedMail($s_to,$s_subj,$s_mail_text,$s_from_addr,$a_headers));
}
 
/*
 * The main logic starts here....
 */
 
    //
    // First, a special case; if formmail.php is called like this:
    //  http://.../formmail.php?testalert=1
    // it sends a test message to the default alert address with some
    // information about your PHP version and the DOCUMENT_ROOT.
    //
if (isset($aGetVars["testalert"]) && $aGetVars["testalert"] == 1)
{
    function ShowServerVar($s_name)
    {
        global  $aServerVars;
 
        return (isset($aServerVars[$s_name]) ? $aServerVars[$s_name] : "-not set-");
    }
    $sAlert = GetMessage(MSG_ALERT,
                array("LANG"=>$sLangID,
                      "PHPVERS"=>implode(".",$aPHPVERSION),
                      "FM_VERS"=>$FM_VERS,
                      "SERVER"=>(IsServerWindows() ? "Windows" : "non-Windows"),
                      "DOCUMENT_ROOT"=>ShowServerVar('DOCUMENT_ROOT'),
                      "SCRIPT_FILENAME"=>ShowServerVar('SCRIPT_FILENAME'),
                      "PATH_TRANSLATED"=>ShowServerVar('PATH_TRANSLATED'),
                      "REAL_DOCUMENT_ROOT"=>CheckString($REAL_DOCUMENT_ROOT),
                     ));
 
    if (DEF_ALERT == "")
        echo "<p>".GetMessage(MSG_NO_DEF_ALERT)."</p>";
    elseif (SendAlert($sAlert,false,true))
        echo "<p>".GetMessage(MSG_TEST_SENT)."</p>";
    else
        echo "<p>".GetMessage(MSG_TEST_FAILED)."</p>";
    exit;
}
 
if (isset($aGetVars["testlang"]) && $aGetVars["testlang"] == 1)
{
    if (!IsPHPAtLeast("4.1.0"))
    {
    ?>
        <p>testlang feature only works with PHP version 4.1.0 or later</p>
    <?php
    }
    else
    {
        function ShowMessages()
        {
            global  $aMessages,$sLangID,$bShowMesgNumbers,$aGetVars,$sHTMLCharSet;
 
                //
                // force message numbers on unless "mnums=no"
                //
            if (isset($aGetVars["mnums"]) && $aGetVars["mnums"] == "no")
                $bShowMesgNumbers = false;
            else
                $bShowMesgNumbers = true;
 
            LoadBuiltinLanguage();
 
 
            $s_def_lang = $sLangID;
            $a_def_mesgs = $aMessages;
 
            LoadLanguageFile();
 
            $s_active_lang = $sLangID;
            $a_active_mesgs = $aMessages;
 
            $a_list = get_defined_constants();
 
            echo "<html>\n";
            echo "<head>\n";
            if (isset($sHTMLCharSet) && $sHTMLCharSet !== "")
                echo "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=$sHTMLCharSet\">\n";
            echo "</head>\n";
            echo "<body>\n";
 
            echo "<table border=\"1\" cellpadding=\"10\" width=\"95%\">\n";
            echo "<tr>\n";
            echo "<th>\n";
            echo "Message Number";
            echo "</th>\n";
            echo "<th>\n";
            echo "$s_def_lang";
            echo "</th>\n";
            echo "<th>\n";
            echo "$s_active_lang";
            echo "</th>\n";
            echo "</tr>\n";
            foreach ($a_list as $s_name=>$i_value)
            {
                if (substr($s_name,0,4) == "MSG_")
                {
                    echo "<tr>\n";
                    echo "<td valign=\"top\">\n";
                    echo "$s_name ($i_value)";
                    echo "</td>\n";
                    echo "<td valign=\"top\">\n";
                    $aMessages = $a_def_mesgs;
                    $s_def_msg = GetMessage((int) $i_value,array(),true,true);
                    echo nl2br(htmlentities($s_def_msg));
                    echo "</td>\n";
                    echo "<td valign=\"top\">\n";
                    $aMessages = $a_active_mesgs;
                    $s_act_msg = GetMessage((int) $i_value,array(),true,true);
                    if ($s_def_msg == $s_act_msg)
                        echo "<i>identical</i>\n";
                    elseif (isset($sHTMLCharSet) && $sHTMLCharSet != "")
                                //
                                // unfortunately, htmlentities get some characters
                                // wrong and converts them even when the
                                // charset is provided
                                //
                        echo nl2br(htmlspecialchars($s_act_msg,ENT_COMPAT,$sHTMLCharSet));
                    else
                        echo nl2br(htmlentities($s_act_msg));
                    echo "</td>\n";
                    echo "</tr>\n";
                }
            }
            echo "</table>\n";
 
            echo "</body>\n";
            echo "</html>\n";
        }
        ShowMessages();
    }
    exit;
}
 
    //
    // Scan the Multi form sequence values and build up the values that
    // were submitted to the given form index.
    //
function GetMultiValues($a_form_list,$i_form_index,$a_order = array(),
                                            $a_clean = array(),
                                            $a_raw_data = array(),
                                            $a_all_data = array(),
                                            $a_file_data = array())
{
    $a_ret_clean = $a_ret_raw = $a_ret_all = $a_ret_files = array();
    for ($ii = 0 ; $ii < $i_form_index ; $ii++)
    {
            //
            // only add a field to the order if it's not already there
            //
        $a_form_order = $a_form_list[$ii]["ORDER"];
        $n_order = count($a_form_order);
        for ($jj = 0 ; $jj < $n_order ; $jj++)
        {
            if (array_search($a_form_order[$jj],$a_order) === false)
                $a_order[] = $a_form_order[$jj];
        }
        $a_ret_clean = array_merge($a_ret_clean,$a_form_list[$ii]["CLEAN"]);
        $a_ret_raw = array_merge($a_ret_raw,$a_form_list[$ii]["RAWDATA"]);
        $a_ret_all = array_merge($a_ret_all,$a_form_list[$ii]["ALLDATA"]);
        $a_ret_files = array_merge($a_ret_files,$a_form_list[$ii]["FILES"]);
    }
        //
        // later values must take precedence to earlier values,
        // so merge in the passed-in data last
        //
    $a_ret_clean = array_merge($a_ret_clean,$a_clean);
    $a_ret_raw = array_merge($a_ret_raw,$a_raw_data);
    $a_ret_all = array_merge($a_ret_all,$a_all_data);
    $a_ret_files = array_merge($a_ret_files,$a_file_data);
    return (array($a_order,$a_ret_clean,$a_ret_raw,$a_ret_all,$a_ret_files));
}
 
$bMultiForm = false;
 
    //
    // Multi-page form sequencing is complicated....
    // Requirements:
    //      1. The first page in a multi-page form sequence must provide:
    //          - multi_start field set to 1
    //          - this_form field (it's own URL)
    //          - next_form field (multi-page form template name)
    //      2. Subsequent pages must provide either:
    //          next_form (the next template name in the sequence)
    //         OR
    //          good_url or good_template or neither; this terminates
    //          the multi-page processing and provides the final URL.
    // Logic:
    //      1. We create session variables to contain information about
    //         the sequence.
    //      2. On the first submission from the starting form, we record
    //         its "this_form" URL and the data submitted.
    //         We also create a URL (to FormMail) that will allow return
    //         to the *next* form in the sequence.
    //      3. On submission from other forms in the sequence, we record
    //         the data that was submitted so we can return to that
    //         form with the user's data re-filled into the form.
    //         We also create a URL (to FormMail) that will allow return
    //         to the *next* form in the sequence.
    //      4. A return URL contains "return=index" where index is the
    //         form sequence index number.  This is a URL to FormMail.
    //         FormMail gets the template name or URL (URL only for the
    //         starting form) and outputs the requested HTML form.  It also
    //         truncates the session data for forms after the returned-to
    //         one.
    //
 
    //
    // Return to a previous form in a sequence.
    //
function MultiFormReturn($i_return_to)
{
    global  $aSessionVars;
    global  $iFormIndex;
 
    if (!isset($aSessionVars["FormList"]) ||
           !isset($aSessionVars["FormIndex"]) ||
            $i_return_to < 0 ||
            $i_return_to > $aSessionVars["FormIndex"])
        Error("cannot_return",GetMessage(MSG_CANNOT_RETURN,
                                array("TO"=>$i_return_to,
                                    "TOPINDEX"=>(
                                        isset($aSessionVars["FormIndex"]) ?
                                        $aSessionVars["FormIndex"] :
                                        "<undefined>"))),
                                false,false);
    assert($i_return_to < count($aSessionVars["FormList"]));
    $a_form_def = $aSessionVars["FormList"][$i_return_to];
    $aSessionVars["FormList"] = array_slice($aSessionVars["FormList"],0,$i_return_to+1);
    $aSessionVars["FormIndex"] = $iFormIndex = $i_return_to;
    if (isset($a_form_def["FORM"]))
    {
        list(,,$a_values,,) = GetMultiValues($aSessionVars["FormList"],$i_return_to);
        $a_lines = array();
        if (ProcessMultiFormTemplate($a_form_def["FORM"],$a_values,$a_lines))
        {
            $n_lines = count($a_lines);
            $s_buf = "";
            for ($ii = 0 ; $ii < $n_lines ; $ii++)
            {
                $s_buf .= $a_lines[$ii]."\n";
                unset($a_lines[$ii]);       // free memory (hopefully)
            }
            unset($a_lines);       // free memory (hopefully)
                //
                // put in the values that the user previously submitted
                // to this form
                //
            echo SetPreviousValues($s_buf,$a_form_def["RAWDATA"]);
        }
        else
            Error("multi_form_failed",GetMessage(MSG_MULTIFORM_FAILED,
                                    array("NAME"=>$s_template)),false,false);
    }
    else
        ProcessReturnToForm($a_form_def["URL"],$a_form_def["RAWDATA"]);
    //
    // no return form this functon
    //
    //echo "Returned to $i_return_to";
}
 
    //
    // Store any data just submitted and specified as "multi_keep".
    //
function MultiKeep()
{
    global  $SPECIAL_VALUES,$aSessionVars,$aRawDataValues;
 
    if (isset($SPECIAL_VALUES["multi_keep"]) &&
        !empty($SPECIAL_VALUES["multi_keep"]))
    {
        $a_list = TrimArray(explode(",",$SPECIAL_VALUES["multi_keep"]));
        if (!isset($aSessionVars["FormKeep"]))
            $aSessionVars["FormKeep"] = array();
            //
            // For each data field specified in "multi_keep" store its
            // value in the FormKeep session variable.
            // If a field is specified and does not exist in the
            // recent submission, its value is discarded.
            //
        foreach ($a_list as $s_fld_name)
            if (!empty($s_fld_name))
                if (isset($aRawDataValues[$s_fld_name]))
                    $aSessionVars["FormKeep"][$s_fld_name] = $aRawDataValues[$s_fld_name];
                else
                    unset($aSessionVars["FormKeep"][$s_fld_name]);
    }
}
 
    //
    // Perform Logic for Multi-Page form sequences
    //
function MultiFormLogic()
{
    global  $bMultiForm,$SPECIAL_VALUES,$aSessionVars,$aServerVars,$aFileVars;
    global  $sFormMailScript,$bGotGoBack,$bGotNextForm,$iFormIndex;
    global  $aFieldOrder,$aCleanedValues,$aRawDataValues,$aAllRawValues;
 
    if ($SPECIAL_VALUES["multi_start"] == 1)
    {
        if (empty($SPECIAL_VALUES["this_form"]))
            ErrorWithIgnore("need_this_form",GetMessage(MSG_NEED_THIS_FORM),false,false);
 
        $bMultiForm = true;
            //
            // Start of multi-page form sequence
            //
        $aSessionVars["FormList"] = array();
        $aSessionVars["FormList"][0] = array("URL"=>$SPECIAL_VALUES["this_form"],
                                            "ORDER"=>$aFieldOrder,
                                            "CLEAN"=>$aCleanedValues,
                                            "RAWDATA"=>$aRawDataValues,
                                            "ALLDATA"=>$aAllRawValues,
                                            "FILES"=>$aFileVars);
        $iFormIndex = $aSessionVars["FormIndex"] = 0;   // zero is the first form, which was
                                                        // just submitted
    }
    elseif (isset($aSessionVars["FormList"]))
        $bMultiForm = true;
 
    if ($bMultiForm)
    {
        if (isset($aServerVars["PHP_SELF"]) &&
            !empty($aServerVars["PHP_SELF"]) &&
            isset($aServerVars["SERVER_NAME"]) &&
            !empty($aServerVars["SERVER_NAME"]))
        {
            if (isset($aServerVars["SERVER_PORT"]) &&
                $aServerVars["SERVER_PORT"] != 80)
            {
                if ($aServerVars["SERVER_PORT"] == 443)     // SSL port
                        //
                        // just use https prefix
                        //
                    $sFormMailScript = "https://".$aServerVars["SERVER_NAME"].
                                                $aServerVars["PHP_SELF"];
                else
                        //
                        // use http with port number
                        //
                    $sFormMailScript = "http://".$aServerVars["SERVER_NAME"].
                                        ":".$aServerVars["SERVER_PORT"].
                                        $aServerVars["PHP_SELF"];
            }
            else
                $sFormMailScript = "http://".$aServerVars["SERVER_NAME"].
                                        $aServerVars["PHP_SELF"];
            $iFormIndex = $aSessionVars["FormIndex"];
        }
        else
            Error("no_php_self",GetMessage(MSG_NO_PHP_SELF),false,false);
    }
 
        //
        // If we're going forward in a multi-page form sequence,
        // compute a URL to return to the form we're about to display.
        //
    if ($bMultiForm && !$bGotGoBack)
    {
            //
            // record the data that was just submitted by the previous form
            //
        $iFormIndex = $aSessionVars["FormIndex"];
        $aSessionVars["FormList"][$iFormIndex]["ORDER"] = $aFieldOrder;
        $aSessionVars["FormList"][$iFormIndex]["CLEAN"] = $aCleanedValues;
        $aSessionVars["FormList"][$iFormIndex]["RAWDATA"] = $aRawDataValues;
        $aSessionVars["FormList"][$iFormIndex]["ALLDATA"] = $aAllRawValues;
        if (count($aFileVars) > 0 && !FILEUPLOADS)
            SendAlert(GetMessage(MSG_FILE_UPLOAD));
        elseif (count($aFileVars) > 0 && !SaveAllUploadedFiles($aFileVars))
            Error("upload_save_failed",GetMessage(MSG_MULTI_UPLOAD),false,false);
        $aSessionVars["FormList"][$iFormIndex]["FILES"] = $aFileVars;
        $iFormIndex++;
        $s_url = GetReturnLink($sFormMailScript,$iFormIndex);
        $aSessionVars["FormList"][$iFormIndex] = array("URL"=>$s_url,
                                    "FORM"=>$SPECIAL_VALUES["next_form"],
                                    "ORDER"=>$aFieldOrder,
                                    "CLEAN"=>$aCleanedValues,
                                    "RAWDATA"=>$aRawDataValues,
                                    "ALLDATA"=>$aAllRawValues,
                                    "FILES"=>$aFileVars);
        $aSessionVars["FormIndex"] = $iFormIndex;
        MultiKeep();
    }
}
 
    //
    // Check for the MIME Attack
    //
function DetectMimeAttack($a_fields,&$s_attack,&$s_info)
{
        //
        // if any of the recipient fields contain "MIME-Version" or
        // "Content-Type" then this is the MIME attack
        // Now also checks the subject field.
        //
    $a_rec_flds = array("recipients","cc","bcc","subject");   // all these fields must be scalar (not arrays)
    foreach ($a_rec_flds as $s_fld)
        if (isset($a_fields[$s_fld]) && is_scalar($a_fields[$s_fld]))
        {
            $s_data = strtolower($a_fields[$s_fld]);
            if (($i_mime = strpos($s_data,"mime-version")) !== false ||
                ($i_cont = strpos($s_data,"content-type")) !== false)
            {
                $s_attack = "MIME";
                $s_info = GetMessage(MSG_ATTACK_MIME_INFO,
                            array("FLD"=>$s_fld,
                                  "CONTENT"=>($i_mime !== false) ?
                                                "mime-version" :
                                                "content-type"),false);
                return (true);
            }
        }
    return (false);
}
 
    //
    // Check for the duplicate data attack
    //
function DetectDupAttack($a_fields,&$s_attack,&$s_info)
{
        //
        // if any of the configured fields contain duplicate data,
        // then this lame attack has been detected
        //
    global  $ATTACK_DETECTION_DUPS;
 
    $a_data_map = array();
    foreach ($ATTACK_DETECTION_DUPS as $s_fld)
        if (isset($a_fields[$s_fld]) &&
            is_scalar($a_fields[$s_fld]) &&    // can only work with string data
            !empty($a_fields[$s_fld]))
        {
            $s_data = (string) $a_fields[$s_fld];
            if (isset($a_data_map[$s_data]))
            {
                    //
                    // duplicate found!
                    //
                $s_attack = "Duplicate Fields";
                $s_info = GetMessage(MSG_ATTACK_DUP_INFO,
                            array("FLD1"=>$a_data_map[$s_data],
                                  "FLD2"=>$s_fld),false);
                return (true);
            }
            $a_data_map[$s_data] = $s_fld;
        }
    return (false);
}
 
    //
    // Check for the email addresses in specials attack
    //
function DetectSpecialsAttack($a_fields,&$s_attack,&$s_info)
{
    global  $ATTACK_DETECTION_SPECIALS_ONLY_EMAIL,
            $ATTACK_DETECTION_SPECIALS_ANY_EMAIL;
 
        //
        // look for email addresses in whole fields
        //
    foreach ($ATTACK_DETECTION_SPECIALS_ONLY_EMAIL as $s_fld)
    {
        if (isset($a_fields[$s_fld]) &&
            is_scalar($a_fields[$s_fld]) &&    // can only work with string data
            !empty($a_fields[$s_fld]))
        {
            $s_data = $a_fields[$s_fld];
            if (preg_match("/^\b[-a-z0-9._%]+@[-.%_a-z0-9]+\.[a-z]{2,9}\b$/i",
                            $s_data) === 1)
            {
                    //
                    // email address found in wrong field
                    //
                $s_attack = "Special Fields Only";
                $s_info = GetMessage(MSG_ATTACK_SPEC_INFO,
                            array("FLD"=>$s_fld),false);
                return (true);
            }
        }
    }
        //
        // look for email addresses in any part of fields
        //
    foreach ($ATTACK_DETECTION_SPECIALS_ANY_EMAIL as $s_fld)
    {
        if (isset($a_fields[$s_fld]) &&
            is_scalar($a_fields[$s_fld]) &&    // can only work with string data
            !empty($a_fields[$s_fld]))
        {
            $s_data = $a_fields[$s_fld];
            if (preg_match("/\b[-a-z0-9._%]+@[-.%_a-z0-9]+\.[a-z]{2,9}\b/i",
                            $s_data) > 0)
            {
                    //
                    // email address found in wrong field
                    //
                $s_attack = "Special Fields Any";
                $s_info = GetMessage(MSG_ATTACK_SPEC_INFO,
                            array("FLD"=>$s_fld),false);
                return (true);
            }
        }
    }
    return (false);
}
 
    //
    // Check for "many URLs in a field" and "many fields with URLs" attacks
    //
function DetectManyURLsAttack($a_fields,&$s_attack,&$s_info)
{
    global      $ATTACK_DETECTION_URL_PATTERNS;
 
    $a_fld_names = array();
        //
        // actual URL link patterns
        //
    $s_srch = '((\bhttps{0,1}:\/\/|<\s*a\s+href=["'."'".']{0,1})[-a-z0-9.]+\b)';
 
        //
        // now add configurable patterns
        //
    if (!empty($ATTACK_DETECTION_URL_PATTERNS) &&
        is_array($ATTACK_DETECTION_URL_PATTERNS))
    {
            //
            // escape / characters and build up a string
            // of alternate patterns
            //
        foreach ($ATTACK_DETECTION_URL_PATTERNS as $s_pat)
        {
            if ($s_pat == "")
                continue;
            $s_srch .= "|".str_replace('/','\/',$s_pat);
        }
    }
 
    foreach ($a_fields as $s_fld=>$s_data)
    {
        if (IsSpecialField($s_fld) || IsSpecialMultiField($s_fld))
                //
                // skip special fields because some are supposed to
                // have URLs in them
                //
            continue;
        if (isset($s_data) &&
            is_scalar($s_data) &&    // can only work with string data
            !empty($s_data))
        {
            $n_match = preg_match_all("/$s_srch/msi",$s_data,$a_matches);
            if (!is_int($n_match))
                $n_match = 0;
            /*
             * debugging code....
             if ($n_match > 0)
                echo "Pattern is '".htmlentities($s_srch)."' with '".
                    htmlentities($s_data)."' field '$s_fld', matched=$n_match<br />";
             */
            if (ATTACK_DETECTION_MANY_URLS > 0)
                if ($n_match >= ATTACK_DETECTION_MANY_URLS)
                {
                    $s_attack = "Many URLS in a field";
                    $s_info = GetMessage(MSG_ATTACK_MANYURL_INFO,
                                array("FLD"=>$s_fld,"NUM"=>($n_match)),false);
                    return (true);
                }
            if ($n_match > 0)
                $a_fld_names[] = $s_fld;
        }
    }
    if (ATTACK_DETECTION_MANY_URL_FIELDS > 0)
        if (count($a_fld_names) >= ATTACK_DETECTION_MANY_URL_FIELDS)
        {
            $s_attack = "Many fields with URLs";
            $s_info = GetMessage(MSG_ATTACK_MANYFIELDS_INFO,
                        array("FLDS"=>implode(",",$a_fld_names),
                                "NUM"=>(count($a_fld_names))),false);
            return (true);
        }
    return (false);
}
 
    //
    // Detect annoying attacks and prevent them from sending spurious
    // alert messages.
    //
function DetectAttacks($a_fields)
{
    global      $ATTACK_DETECTION_DUPS;
 
    $s_info = $s_attack = "";
    $b_attacked = false;
    if (ATTACK_DETECTION_MIME)
        if (DetectMimeAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
    if (!$b_attacked && !empty($ATTACK_DETECTION_DUPS))
        if (DetectDupAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
    if (!$b_attacked && ATTACK_DETECTION_SPECIALS)
        if (DetectSpecialsAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
    if (!$b_attacked && (ATTACK_DETECTION_MANY_URLS ||
                        ATTACK_DETECTION_MANY_URL_FIELDS))
        if (DetectManyURLsAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
 
    if ($b_attacked)
    {
        if (ALERT_ON_ATTACK_DETECTION)
            SendAlert(GetMessage(MSG_ATTACK_DETECTED,
                    array("ATTACK"=>$s_attack,
                          "INFO"=>$s_info,)),
                        false);
        if (ATTACK_DETECTION_URL !== "")
            Redirect(ATTACK_DETECTION_URL);
        else
            CreatePage(GetMessage(MSG_ATTACK_PAGE));
        exit;
    }
}
 
$bAdvTemplates = false;
if (ADVANCED_TEMPLATES &&
        (!empty($TEMPLATEDIR) || !empty($TEMPLATEURL) ||
        !empty($MULTIFORMDIR) || !empty($MULTIFORMURL)))
    $bAdvTemplates = true;
 
if (isset($aGetVars["return"]) && is_numeric($aGetVars["return"]))
{
        //
        // if advanced templates are in use, we will need them for
        // performing a multi-page form return
        //
    if ($bAdvTemplates)
    {
        $FMCTEMPLATE_PROC = true;
        if (!include_once("$MODULEDIR/$FMCOMPUTE"))
            Error("load_fmcompute",GetMessage(MSG_LOAD_FMCOMPUTE,
                            array("FILE"=>"$MODULEDIR/$FMCOMPUTE",
                                    "ERROR"=>$php_errormsg)),false,false);
    }
    MultiFormReturn($aGetVars["return"]);
    exit;
}
 
    //
    // Hook system: after initialization
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookpostinit.inc");
 
    //
    // check configuration values for potential security problems
    //
CheckConfig();
 
    //
    // otherwise, do the real processing of FormMail
    //
$aStrippedFormVars = $aAllRawValues = StripGPCArray($aFormVars);
 
if (ENABLE_ATTACK_DETECTION)
    DetectAttacks($aAllRawValues);
 
    //
    // process the options
    //
ProcessMailOptions($aAllRawValues);
ProcessCRMOptions($aAllRawValues);
ProcessAROptions($aAllRawValues);
ProcessFilterOptions($aAllRawValues);
 
    //
    // create any derived fields
    //
$aAllRawValues = CreateDerived($aAllRawValues);
 
list($aFieldOrder,$aCleanedValues,$aRawDataValues) = ParseInput($aAllRawValues);
 
    //
    // if we're processing multi-forms, then merge in the raw data from previous
    // forms unless this is the first page of the form sequence
    //
if (isset($aSessionVars["FormList"]) && $SPECIAL_VALUES["multi_start"] != 1)
{
    list($aFieldOrder,$aCleanedValues,
            $aRawDataValues,$aAllRawValues,$aFileVars) = GetMultiValues(
                            $aSessionVars["FormList"],
                            $aSessionVars["FormIndex"],
                            $aFieldOrder,$aCleanedValues,
                            $aRawDataValues,$aAllRawValues,
                            $aFileVars);
}
 
if ($SPECIAL_VALUES["file_names"] !== "")
    list($aFieldOrder,$aCleanedValues,$aRawDataValues,$aAllRawValues,$aFileVars) =
            SetFileNames($SPECIAL_VALUES["file_names"],$aFieldOrder,
                    $aCleanedValues,$aRawDataValues,$aAllRawValues,$aFileVars);
 
    //
    // Hook system: after loading and processing data
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookload.inc");
 
if ($FORM_INI_FILE !== "")
{
    ProcessFormIniFile($FORM_INI_FILE);
        //
        // Hook system: after processing INI file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookinifile.inc");
}
 
$bDoneSomething = false;
if (DB_SEE_INPUT)
{
    /***
    echo "<pre>";
    print_r($aFormVars);
    print_r($aServerVars);
    echo "</pre>";
    exit;
    ****/
    CreatePage(implode("\n",$FORMATTED_INPUT));
    ZapSession();
    exit;
}
 
if (!empty($SPECIAL_VALUES["fmcompute"]) || $bAdvTemplates)
{
    $FM_UserErrors = array();
        //
        // Generalized interface between FMCompute and FormMail functions
        //
    function FM_CallFunction($s_func,$a_params,&$m_return,
                                &$s_mesg,&$a_debug,&$a_alerts)
    {
        switch ($s_func)
        {
        case "FMFatalError":
            SendComputeAlerts();
            if (count($a_params) < 3)
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            else
                Error("fmcompute_error",$a_params[0],$a_params[1],$a_params[2]);
            break;
 
        case "FMFatalUserError":
            SendComputeAlerts();
            if (count($a_params) < 1)
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            else
                UserError("fmcompute_usererror",$a_params[0]);
            break;
 
        case "FMUserError":
            if (count($a_params) < 1)
            {
                SendComputeAlerts();
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            }
            else
            {
                global  $FM_UserErrors;
 
                $FM_UserErrors[] = $a_params[0];
            }
            break;
 
        case "FMSaveAllFilesToRepository":
            if (count($a_params) != 0)
            {
                SendComputeAlerts();
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            }
            else
                $m_return = SaveAllFilesToRepository();
            break;
 
        default:
            $s_mesg = GetMessage(MSG_CALL_UNK_FUNC,array("FUNC"=>$s_func));
            return (false);
        }
        return (true);
    }
 
        //
        // register useful FormMail functions with FMCompute module
        //
    function RegisterFormMailFunctions(&$fmc)
    {
            //
            // Allows the user to call "Error" from within a computation
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","void",
                            "FMFatalError",
                            array("string","bool","bool"),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMFatalError",
                                          "ERROR"=>$s_msg)),false,false);
            //
            // Allows the user to call "UserError" from within a computation
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","void",
                            "FMFatalUserError",
                            array("string"),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMFatalUserError",
                                          "ERROR"=>$s_msg)),false,false);
 
            //
            // Allows the user to record an error to be displayed
            // from within a computation.
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","void",
                            "FMUserError",
                            array("string"),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMUserError",
                                          "ERROR"=>$s_msg)),false,false);
 
            //
            // Saves files to the repository.
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","bool",
                            "FMSaveAllFilesToRepository",
                            array(),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMSaveAllFilesToRepository",
                                          "ERROR"=>$s_msg)),false,false);
 
    }
 
        //
        // load the fmcompute module
        //
    if (!empty($SPECIAL_VALUES["fmcompute"]))
    {
        $FMCOMPUTE_CLASS = true;
        $FMCOMPUTE_NODEBUG = true;
    }
    if ($bAdvTemplates)
        $FMCTEMPLATE_PROC = true;
    if (!include_once("$MODULEDIR/$FMCOMPUTE"))
        Error("load_fmcompute",GetMessage(MSG_LOAD_FMCOMPUTE,
                        array("FILE"=>"$MODULEDIR/$FMCOMPUTE",
                                "ERROR"=>$php_errormsg)),false,false);
    if (!empty($SPECIAL_VALUES["fmcompute"]))
    {
        RegisterFormMailFunctions($FMCalc);
 
            //
            // if GeoIP support is specified, load that module now
            //
        if (!empty($GEOIP_LIC))
        {
            $FMMODULE_LOAD = true;      // signal module load
            if (!include_once("$MODULEDIR/$FMGEOIP"))
                Error("load_module",GetMessage(MSG_LOAD_MODULE,
                                array("FILE"=>"$MODULEDIR/$FMGEOIP",
                                        "ERROR"=>$php_errormsg)),false,false);
                //
                // load the license and register the module
                //
            $GeoIP = new FMGeoIP($GEOIP_LIC);
            if (!$GeoIP->RegisterModule($FMCalc))
                Error("reg_module",GetMessage(MSG_REGISTER_MODULE,
                                array("NAME"=>"FMGeoIP",
                                       "ERROR"=>$GeoIP->GetError())),false,false);
        }
    }
}
 
if (isset($SPECIAL_VALUES["multi_go_back"]) && !empty($SPECIAL_VALUES["multi_go_back"]))
{
    if (!isset($aSessionVars["FormList"]) || $aSessionVars["FormIndex"] == 0)
        ErrorWithIgnore("go_back",GetMessage(MSG_GO_BACK),false,false);
    MultiKeep();        // store any "multi_keep" data just submitted
    MultiFormReturn($aSessionVars["FormIndex"]-1);
//    echo "Form index = ".$aSessionVars["FormIndex"];
    exit;
}
 
    //
    // This is the check for spiders; I can't imagine a spider will
    // ever use the POST method.
    //
if ($bIsGetMethod && count($aFormVars) == 0)
{
    CreatePage(GetMessage(MSG_NO_DATA_PAGE));
    ZapSession();
    exit;
}
 
    //
    // Hook system: before performing required and conditions etc.
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookprechecks.inc");
 
    //
    // check for required fields
    //
if (!CheckRequired($SPECIAL_VALUES["required"],$aAllRawValues,$missing,$a_missing_list))
    UserError("missing_fields",GetMessage(MSG_REQD_ERROR),$missing,$a_missing_list);
 
    //
    // check complex conditions
    //
if (!CheckConditions($SPECIAL_VALUES["conditions"],$aAllRawValues,$missing,$a_missing_list))
    UserError("failed_conditions",GetMessage(MSG_COND_ERROR),$missing,$a_missing_list);
 
    //
    // check imgverify
    //
if (isset($SPECIAL_VALUES["imgverify"]) && !empty($SPECIAL_VALUES["imgverify"]))
{
        //
        // VerifyImgString is from Tectite's simple verifyimg.php CAPTCHA
        // turing_string is from Captcha Creator
        //
    if (!isset($aSessionVars["VerifyImgString"]) &&
        !isset($aSessionVars["turing_string"]))
        ErrorWithIgnore("verify_failed",GetMessage(MSG_VERIFY_MISSING),false);
        //
        // the user's entry must match the value in the session; allow
        // spaces in the user's input
        //
    if (isset($aSessionVars["VerifyImgString"]))
    {
        if (str_replace(" ","",$SPECIAL_VALUES["imgverify"]) !==
                    $aSessionVars["VerifyImgString"])
            UserError("img_verify",GetMessage(MSG_VERIFY_MATCH));
    }
    else
    {
        if (strtoupper(str_replace(" ","",$SPECIAL_VALUES["imgverify"])) !==
                    strtoupper($aSessionVars["turing_string"]))
            UserError("img_verify",GetMessage(MSG_VERIFY_MATCH)/*,
                        "imgverify='".$SPECIAL_VALUES["imgverify"]."' ".
                        "turing_string='".$aSessionVars["turing_string"]."'"*/);
    }
}
 
    //
    // Hook system: after performing required and conditions etc.
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookchecks.inc");
 
if (!empty($SPECIAL_VALUES["fmmodules"]))
{
    $aModuleList = TrimArray(explode(",",$SPECIAL_VALUES["fmmodules"]));
    $FMMODULE_LOAD = true;      // signal module load
    foreach ($aModuleList as $sModule)
        if (!include_once("$MODULEDIR/$sModule"))
            Error("load_module",GetMessage(MSG_LOAD_MODULE,
                            array("FILE"=>"$MODULEDIR/$sModule",
                                    "ERROR"=>$php_errormsg)),false,false);
}
 
if (!empty($SPECIAL_VALUES["fmcompute"]))
{
        //
        // Callback function for preg_replace_callback to add line
        // numbers on each match
        //
    function AddLineNumbersCallback($a_matches)
    {
        global  $iAddLineNumbersCounter;
 
        return (sprintf("%d:",++$iAddLineNumbersCounter).$a_matches[0]);
    }
        //
        // Add line numbers to some code
        //
    function AddLineNumbers($s_code)
    {
        global  $iAddLineNumbersCounter;
 
        $iAddLineNumbersCounter = 0;
        return (preg_replace_callback('/^/m','AddLineNumbersCallback',$s_code));
    }
 
        //
        // Load some more code into FMCalc
        //
    function Load($s_code)
    {
        global  $FMCalc;
 
        $a_mesgs = array();
       // echo "Loading '$s_code'";
        if ($FMCalc->Parse($s_code,$a_mesgs) === false)
        {
            $s_msgs = "";
            foreach ($a_mesgs as $a_msg)
            {
                $s_msgs .= "Line ".$a_msg["LINE"];
                $s_msgs .= ", position ".$a_msg["CHAR"].": ";
                $s_msgs .= $a_msg["MSG"]."\n";
            }
            Error("fmcompute_parse",GetMessage(MSG_COMP_PARSE,
                        array("CODE"=>AddLineNumbers($s_code),
                                "ERRORS"=>$s_msgs)),false,false);
        }
    }
 
        //
        // Send any alerts found in FMCalc
        //
    function SendComputeAlerts()
    {
        global  $FMCalc;
 
        $a_alerts = $FMCalc->GetAlerts();
        if (count($a_alerts) > 0)
            SendAlert(GetMessage(MSG_COMP_ALERT,
                        array("ALERTS"=>implode("\n",$a_alerts))));
        $a_debug = $FMCalc->GetDebug();
        if (count($a_debug) > 0)
            SendAlert(GetMessage(MSG_COMP_DEBUG,
                        array("DEBUG"=>implode("\n",$a_debug))));
    }
        //
        // Perform the computations in FMCalc
        //
    function Compute(&$a_field_order,&$a_cleaned_values,&$a_raw_data_values,
                            &$a_values)
    {
        global  $FMCalc,$FM_UserErrors;
 
        $a_mesgs = array();
        $FM_UserErrors = array();
        if (($a_flds = $FMCalc->Execute($a_mesgs)) !== false)
        {
            SendComputeAlerts();
            foreach ($a_flds as $s_name=>$s_value)
            {
                $a_values[$s_name] = $s_value;
                ProcessField($s_name,$s_value,$a_field_order,
                                $a_cleaned_values,$a_raw_data_values);
            }
            if (count($FM_UserErrors) > 0)
                UserError("fmcompute_usererrors",GetMessage(MSG_USER_ERRORS),
                                "",$FM_UserErrors);
        }
        else
        {
            SendComputeAlerts();
            Error("fmcompute_exec",GetMessage(MSG_COMP_EXEC,
                        array("ERRORS"=>implode("\n",$a_mesgs))),false,false);
        }
    }
 
        //
        // Register all fields; a future improvement should use a call-back
        // function so as not to copy all the data into the FMCompute object
        //
    function RegisterData($a_form_data,$a_file_vars)
    {
        global  $FMCalc;
 
        foreach ($a_form_data as $s_name=>$s_value)
            if (isset($s_name) && isset($s_value))
                if (($s_msg = $FMCalc->RegisterExternalData("PHP","string",
                                                $s_name,"c",$s_value)) !== true)
                    Error("fmcompute_regdata",GetMessage(MSG_COMP_REG_DATA,
                                array("NAME"=>$s_name,"ERROR"=>$s_msg)),false,false);
 
        foreach ($a_file_vars as $s_fld_name=>$a_file_spec)
        {
            if (IsUploadedFile($a_file_spec))
                $s_value = $a_file_spec['name'];
            else
                $s_value = "";
            if (($s_msg = $FMCalc->RegisterExternalData("PHP","string",
                                            $s_fld_name,"c",$s_value)) !== true)
                Error("fmcompute_regdata",GetMessage(MSG_COMP_REG_DATA,
                            array("NAME"=>$s_fld_name,"ERROR"=>$s_msg)),false,false);
        }
    }
    RegisterData($aAllRawValues,$aFileVars);
        //
        // parse all fmcompute fields
        //
    if (is_array($SPECIAL_VALUES["fmcompute"]))
    {
        $nCompute = count($SPECIAL_VALUES["fmcompute"]);
        for ($iCompute = 0 ; $iCompute < $nCompute ; $iCompute++)
            Load($SPECIAL_VALUES["fmcompute"][$iCompute]);
    }
    else
        Load($SPECIAL_VALUES["fmcompute"]);
 
        //
        // run computations
        //
    Compute($aFieldOrder,$aCleanedValues,$aRawDataValues,$aAllRawValues);
        //
        // Hook system: after computations
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookcompute.inc");
}
 
$bGotGoBack = $bGotNextForm = $bGotGoodTemplate = $bGotGoodUrl = false;
if (isset($SPECIAL_VALUES["good_url"]) &&
    !empty($SPECIAL_VALUES["good_url"]))
    $bGotGoodUrl = true;
 
if (isset($SPECIAL_VALUES["good_template"]) &&
    !empty($SPECIAL_VALUES["good_template"]))
    $bGotGoodTemplate = true;
 
if (isset($SPECIAL_VALUES["next_form"]) &&
    !empty($SPECIAL_VALUES["next_form"]))
    $bGotNextForm = true;
 
if (isset($SPECIAL_VALUES["multi_go_back"]) &&
    !empty($SPECIAL_VALUES["multi_go_back"]))
    $bGotGoBack = true;
 
    //
    // it's not valid to specify "next_form" as well as "good_url" or
    // "good_template"; this is because it's ambiguous - do we go to the
    // next form or the final 'thank you' page?
    //
if ($bGotNextForm && ($bGotGoodTemplate || $bGotGoodUrl))
    ErrorWithIgnore("next_plus_good",GetMessage(MSG_NEXT_PLUS_GOOD,array("WHICH"=>
                                    ($bGotGoodUrl ? "good_url" :
                                    "good_template"))),false,false);
 
MultiFormLogic();
 
    //
    // Hook system: after multi-page form logic
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookmulti.inc");
 
    //
    // write to the CSV database
    //
if (!empty($CSVDIR) && isset($SPECIAL_VALUES["csvfile"]) &&
                        !empty($SPECIAL_VALUES["csvfile"]))
{
        //
        // Hook system: before writing CSV file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookprecsv.inc");
    WriteCSVFile($CSVDIR."/".basename($SPECIAL_VALUES["csvfile"]),$aAllRawValues);
        //
        // Hook system: after writing CSV file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpostcsv.inc");
    $bDoneSomething = true;
}
 
    //
    // write to the log file
    //
if (!empty($LOGDIR) && isset($SPECIAL_VALUES["logfile"]) && !empty($SPECIAL_VALUES["logfile"]))
{
        //
        // Hook system: before writing log file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookprelog.inc");
    WriteLog($LOGDIR."/".basename($SPECIAL_VALUES["logfile"]));
        //
        // Hook system: after writing log file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpostlog.inc");
    $bDoneSomething = true;
}
 
    //
    // send to the CRM
    //
if (isset($SPECIAL_VALUES["crm_url"]) && isset($SPECIAL_VALUES["crm_spec"]))
{
    $sCRM = GetCRMURL($SPECIAL_VALUES["crm_spec"],$aAllRawValues,$SPECIAL_VALUES["crm_url"]);
    if (!empty($sCRM))
    {
        $aCRMReturnData = array();
            //
            // Hook system: before sending to CRM
            //
        if ($HOOK_DIR !== "")
            @include("$HOOK_DIR/fmhookprecrm.inc");
        if (!SendToCRM($sCRM,$aCRMReturnData))
        {
                //
                // CRM interface failed, check if the form wants an error
                // displayed
                //
            if (IsCRMOptionSet("ErrorOnFail"))
                Error("crm_failed",GetMessage(MSG_CRM_FAILURE,
                                array("URL"=>$sCRM,
                                    "DATA"=>GetObjectAsString($aCRMReturnData))),
                                false,false);
        }
        else
                //
                // append the returned data to the raw data values of the form
                //
            $aRawDataValues = array_merge($aRawDataValues,$aCRMReturnData);
            //
            // Hook system: after sending to CRM
            //
        if ($HOOK_DIR !== "")
            @include("$HOOK_DIR/fmhookpostcrm.inc");
        $bDoneSomething = true;
    }
}
 
    //
    // Check obsolete SendMailFOption
    //
if (IsMailOptionSet("SendMailFOption"))
    SendAlert(GetMessage(MSG_FOPTION_WARN,array("LINE"=>SENDMAIL_F_OPTION_LINE)),
                false,true);
 
    //
    // send email
    //
if (!isset($SPECIAL_VALUES["recipients"]) || empty($SPECIAL_VALUES["recipients"]))
{
        //
        // No recipients - don't email anyone...
        // If nothing has been done above (CSV, logging, or CRM),
        // then report an error.
        //
    if (!$bDoneSomething)
        if (!$bGotGoBack && !$bGotNextForm)
            ErrorWithIgnore("no_recipients",GetMessage(MSG_NO_ACTIONS));
}
else
{
        //
        // Hook system: before sending emails
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpreemail.inc");
    $s_invalid = $s_invalid_cc = $s_invalid_bcc = "";
    if (!CheckEmailAddress($SPECIAL_VALUES["recipients"],$s_valid_recipients,$s_invalid))
        ErrorWithIgnore("no_valid_recipients",GetMessage(MSG_NO_RECIP));
    else
    {
        $s_valid_cc = $s_valid_bcc = "";
 
            //
            // check CC and BCC addresses
            //
        if (isset($SPECIAL_VALUES["cc"]) && !empty($SPECIAL_VALUES["cc"]))
            CheckEmailAddress($SPECIAL_VALUES["cc"],$s_valid_cc,$s_invalid_cc);
        if (isset($SPECIAL_VALUES["bcc"]) && !empty($SPECIAL_VALUES["bcc"]))
            CheckEmailAddress($SPECIAL_VALUES["bcc"],$s_valid_bcc,$s_invalid_bcc);
 
            //
            // send an alert for invalid addresses
            //
        $s_error = "";
        if (!empty($s_invalid))
            $s_error .= "recipients: $s_invalid\r\n";
        if (!empty($s_invalid_cc))
            $s_error .= "cc: $s_invalid_cc\r\n";
        if (!empty($s_invalid_bcc))
            $s_error .= "bcc: $s_invalid_bcc\r\n";
        if (!empty($s_error))
            SendAlert(GetMessage(MSG_INV_EMAIL,array("ERRORS"=>$s_error)));
 
            //
            // send the actual results
            //
        if (!SendResults($aFieldOrder,$aCleanedValues,$s_valid_recipients,$s_valid_cc,
                            $s_valid_bcc,$aRawDataValues))
            Error("mail_failed",GetMessage(MSG_FAILED_SEND));
            //
            // Hook system: after sending emails
            //
        if ($HOOK_DIR !== "")
            @include("$HOOK_DIR/fmhookpostemail.inc");
    }
}
 
    //
    // if the user didn't enter the verification code,
    // just skip the autoresponse
    //
if (isset($SPECIAL_VALUES["arverify"]) && !empty($SPECIAL_VALUES["arverify"]))
    if (IsAROptionSet('HTMLTemplate') || IsAROptionSet('PlainTemplate'))
    {
        if (!isset($SPECIAL_VALUES["email"]) || empty($SPECIAL_VALUES["email"]))
            SendAlert(GetMessage(MSG_ARESP_EMAIL));
        else
        {
                //
                // Hook system: before sending auto response
                //
            if ($HOOK_DIR !== "")
                @include("$HOOK_DIR/fmhookprearesp.inc");
            $sAutoRespTo = $SPECIAL_VALUES["email"];
            if (IsAROptionSet('Subject'))
                $sAutoRespSubj = GetAROption('Subject');
            else
                $sAutoRespSubj = GetMessage(MSG_ARESP_SUBJ,array(),false);
 
                //
                // VerifyImgString is from Tectite's simple verifyimg.php CAPTCHA
                // turing_string is from Captcha Creator
                //
            if (!isset($aSessionVars["VerifyImgString"]) &&
                !isset($aSessionVars["turing_string"]))
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                        GetMessage(MSG_LOG_NO_VERIMG,array(),false));
                ErrorWithIgnore("verify_failed",GetMessage(MSG_ARESP_NO_AUTH),true);
            }
            $bARImgMatch = false;
                //
                // the user's entry must match the value in the session; allow
                // spaces in the user's input
                //
            if (isset($aSessionVars["VerifyImgString"]))
            {
                if (str_replace(" ","",$SPECIAL_VALUES["arverify"]) ===
                            $aSessionVars["VerifyImgString"])
                    $bARImgMatch = true;
            }
            else
            {
                if (strtoupper(str_replace(" ","",$SPECIAL_VALUES["arverify"])) ===
                            strtoupper($aSessionVars["turing_string"]))
                    $bARImgMatch = true;
            }
            if (!$bARImgMatch)
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                            GetMessage(MSG_LOG_NO_MATCH,array(),false));
                UserError("ar_verify",GetMessage(MSG_ARESP_NO_MATCH));
            }
            elseif (!AutoRespond($sAutoRespTo,$sAutoRespSubj,$aRawDataValues))
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                            GetMessage(MSG_LOG_FAILED,array(),false));
                SendAlert(GetMessage(MSG_ARESP_FAILED));
            }
            else
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                            GetMessage(MSG_LOG_OK,array(),false));
                    //
                    // Hook system: after sending auto response
                    //
                if ($HOOK_DIR !== "")
                    @include("$HOOK_DIR/fmhookpostaresp.inc");
            }
        }
    }
 
    //
    // multi-form processing
    //
if ($bGotNextForm)
{
    OutputMultiFormTemplate($SPECIAL_VALUES["next_form"],$aRawDataValues);
//    echo "Form index = ".$aSessionVars["FormIndex"];
}
else
{
        //
        // Hook system: before finishing
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookprefinish.inc");
        //
        // redirect to the good URL page, or create a default page;
        // we're no longer processing a multi-page form sequence
        //
    unset($aSessionVars["FormList"]);
    unset($aSessionVars["FormIndex"]);
    unset($aSessionVars["FormKeep"]);
    if (!$bGotGoodUrl)
    {
        if ($bGotGoodTemplate)
            OutputTemplate($SPECIAL_VALUES["good_template"],$aRawDataValues);
        else
            CreatePage(GetMessage(MSG_THANKS_PAGE));
    }
    else
        Redirect($SPECIAL_VALUES["good_url"]);
        //
        // Hook system: after finishing (before session is cleared)
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpostfinish.inc");
        //
        // everything's good, so we don't need the session any more
        //
    ZapSession();
}
?>
 
  <!-- notice the addition of the class="break" here to give it the extra space. -->
    </p>
 
 
 
  </div>
 
  <p class="clear">&nbsp;</p>
  </div>
 
<!-- This is the end of the template. -->
 
	</body>
</html>

                                              
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:
995:
996:
997:
998:
999:
1000:
1001:
1002:
1003:
1004:
1005:
1006:
1007:
1008:
1009:
1010:
1011:
1012:
1013:
1014:
1015:
1016:
1017:
1018:
1019:
1020:
1021:
1022:
1023:
1024:
1025:
1026:
1027:
1028:
1029:
1030:
1031:
1032:
1033:
1034:
1035:
1036:
1037:
1038:
1039:
1040:
1041:
1042:
1043:
1044:
1045:
1046:
1047:
1048:
1049:
1050:
1051:
1052:
1053:
1054:
1055:
1056:
1057:
1058:
1059:
1060:
1061:
1062:
1063:
1064:
1065:
1066:
1067:
1068:
1069:
1070:
1071:
1072:
1073:
1074:
1075:
1076:
1077:
1078:
1079:
1080:
1081:
1082:
1083:
1084:
1085:
1086:
1087:
1088:
1089:
1090:
1091:
1092:
1093:
1094:
1095:
1096:
1097:
1098:
1099:
1100:
1101:
1102:
1103:
1104:
1105:
1106:
1107:
1108:
1109:
1110:
1111:
1112:
1113:
1114:
1115:
1116:
1117:
1118:
1119:
1120:
1121:
1122:
1123:
1124:
1125:
1126:
1127:
1128:
1129:
1130:
1131:
1132:
1133:
1134:
1135:
1136:
1137:
1138:
1139:
1140:
1141:
1142:
1143:
1144:
1145:
1146:
1147:
1148:
1149:
1150:
1151:
1152:
1153:
1154:
1155:
1156:
1157:
1158:
1159:
1160:
1161:
1162:
1163:
1164:
1165:
1166:
1167:
1168:
1169:
1170:
1171:
1172:
1173:
1174:
1175:
1176:
1177:
1178:
1179:
1180:
1181:
1182:
1183:
1184:
1185:
1186:
1187:
1188:
1189:
1190:
1191:
1192:
1193:
1194:
1195:
1196:
1197:
1198:
1199:
1200:
1201:
1202:
1203:
1204:
1205:
1206:
1207:
1208:
1209:
1210:
1211:
1212:
1213:
1214:
1215:
1216:
1217:
1218:
1219:
1220:
1221:
1222:
1223:
1224:
1225:
1226:
1227:
1228:
1229:
1230:
1231:
1232:
1233:
1234:
1235:
1236:
1237:
1238:
1239:
1240:
1241:
1242:
1243:
1244:
1245:
1246:
1247:
1248:
1249:
1250:
1251:
1252:
1253:
1254:
1255:
1256:
1257:
1258:
1259:
1260:
1261:
1262:
1263:
1264:
1265:
1266:
1267:
1268:
1269:
1270:
1271:
1272:
1273:
1274:
1275:
1276:
1277:
1278:
1279:
1280:
1281:
1282:
1283:
1284:
1285:
1286:
1287:
1288:
1289:
1290:
1291:
1292:
1293:
1294:
1295:
1296:
1297:
1298:
1299:
1300:
1301:
1302:
1303:
1304:
1305:
1306:
1307:
1308:
1309:
1310:
1311:
1312:
1313:
1314:
1315:
1316:
1317:
1318:
1319:
1320:
1321:
1322:
1323:
1324:
1325:
1326:
1327:
1328:
1329:
1330:
1331:
1332:
1333:
1334:
1335:
1336:
1337:
1338:
1339:
1340:
1341:
1342:
1343:
1344:
1345:
1346:
1347:
1348:
1349:
1350:
1351:
1352:
1353:
1354:
1355:
1356:
1357:
1358:
1359:
1360:
1361:
1362:
1363:
1364:
1365:
1366:
1367:
1368:
1369:
1370:
1371:
1372:
1373:
1374:
1375:
1376:
1377:
1378:
1379:
1380:
1381:
1382:
1383:
1384:
1385:
1386:
1387:
1388:
1389:
1390:
1391:
1392:
1393:
1394:
1395:
1396:
1397:
1398:
1399:
1400:
1401:
1402:
1403:
1404:
1405:
1406:
1407:
1408:
1409:
1410:
1411:
1412:
1413:
1414:
1415:
1416:
1417:
1418:
1419:
1420:
1421:
1422:
1423:
1424:
1425:
1426:
1427:
1428:
1429:
1430:
1431:
1432:
1433:
1434:
1435:
1436:
1437:
1438:
1439:
1440:
1441:
1442:
1443:
1444:
1445:
1446:
1447:
1448:
1449:
1450:
1451:
1452:
1453:
1454:
1455:
1456:
1457:
1458:
1459:
1460:
1461:
1462:
1463:
1464:
1465:
1466:
1467:
1468:
1469:
1470:
1471:
1472:
1473:
1474:
1475:
1476:
1477:
1478:
1479:
1480:
1481:
1482:
1483:
1484:
1485:
1486:
1487:
1488:
1489:
1490:
1491:
1492:
1493:
1494:
1495:
1496:
1497:
1498:
1499:
1500:
1501:
1502:
1503:
1504:
1505:
1506:
1507:
1508:
1509:
1510:
1511:
1512:
1513:
1514:
1515:
1516:
1517:
1518:
1519:
1520:
1521:
1522:
1523:
1524:
1525:
1526:
1527:
1528:
1529:
1530:
1531:
1532:
1533:
1534:
1535:
1536:
1537:
1538:
1539:
1540:
1541:
1542:
1543:
1544:
1545:
1546:
1547:
1548:
1549:
1550:
1551:
1552:
1553:
1554:
1555:
1556:
1557:
1558:
1559:
1560:
1561:
1562:
1563:
1564:
1565:
1566:
1567:
1568:
1569:
1570:
1571:
1572:
1573:
1574:
1575:
1576:
1577:
1578:
1579:
1580:
1581:
1582:
1583:
1584:
1585:
1586:
1587:
1588:
1589:
1590:
1591:
1592:
1593:
1594:
1595:
1596:
1597:
1598:
1599:
1600:
1601:
1602:
1603:
1604:
1605:
1606:
1607:
1608:
1609:
1610:
1611:
1612:
1613:
1614:
1615:
1616:
1617:
1618:
1619:
1620:
1621:
1622:
1623:
1624:
1625:
1626:
1627:
1628:
1629:
1630:
1631:
1632:
1633:
1634:
1635:
1636:
1637:
1638:
1639:
1640:
1641:
1642:
1643:
1644:
1645:
1646:
1647:
1648:
1649:
1650:
1651:
1652:
1653:
1654:
1655:
1656:
1657:
1658:
1659:
1660:
1661:
1662:
1663:
1664:
1665:
1666:
1667:
1668:
1669:
1670:
1671:
1672:
1673:
1674:
1675:
1676:
1677:
1678:
1679:
1680:
1681:
1682:
1683:
1684:
1685:
1686:
1687:
1688:
1689:
1690:
1691:
1692:
1693:
1694:
1695:
1696:
1697:
1698:
1699:
1700:
1701:
1702:
1703:
1704:
1705:
1706:
1707:
1708:
1709:
1710:
1711:
1712:
1713:
1714:
1715:
1716:
1717:
1718:
1719:
1720:
1721:
1722:
1723:
1724:
1725:
1726:
1727:
1728:
1729:
1730:
1731:
1732:
1733:
1734:
1735:
1736:
1737:
1738:
1739:
1740:
1741:
1742:
1743:
1744:
1745:
1746:
1747:
1748:
1749:
1750:
1751:
1752:
1753:
1754:
1755:
1756:
1757:
1758:
1759:
1760:
1761:
1762:
1763:
1764:
1765:
1766:
1767:
1768:
1769:
1770:
1771:
1772:
1773:
1774:
1775:
1776:
1777:
1778:
1779:
1780:
1781:
1782:
1783:
1784:
1785:
1786:
1787:
1788:
1789:
1790:
1791:
1792:
1793:
1794:
1795:
1796:
1797:
1798:
1799:
1800:
1801:
1802:
1803:
1804:
1805:
1806:
1807:
1808:
1809:
1810:
1811:
1812:
1813:
1814:
1815:
1816:
1817:
1818:
1819:
1820:
1821:
1822:
1823:
1824:
1825:
1826:
1827:
1828:
1829:
1830:
1831:
1832:
1833:
1834:
1835:
1836:
1837:
1838:
1839:
1840:
1841:
1842:
1843:
1844:
1845:
1846:
1847:
1848:
1849:
1850:
1851:
1852:
1853:
1854:
1855:
1856:
1857:
1858:
1859:
1860:
1861:
1862:
1863:
1864:
1865:
1866:
1867:
1868:
1869:
1870:
1871:
1872:
1873:
1874:
1875:
1876:
1877:
1878:
1879:
1880:
1881:
1882:
1883:
1884:
1885:
1886:
1887:
1888:
1889:
1890:
1891:
1892:
1893:
1894:
1895:
1896:
1897:
1898:
1899:
1900:
1901:
1902:
1903:
1904:
1905:
1906:
1907:
1908:
1909:
1910:
1911:
1912:
1913:
1914:
1915:
1916:
1917:
1918:
1919:
1920:
1921:
1922:
1923:
1924:
1925:
1926:
1927:
1928:
1929:
1930:
1931:
1932:
1933:
1934:
1935:
1936:
1937:
1938:
1939:
1940:
1941:
1942:
1943:
1944:
1945:
1946:
1947:
1948:
1949:
1950:
1951:
1952:
1953:
1954:
1955:
1956:
1957:
1958:
1959:
1960:
1961:
1962:
1963:
1964:
1965:
1966:
1967:
1968:
1969:
1970:
1971:
1972:
1973:
1974:
1975:
1976:
1977:
1978:
1979:
1980:
1981:
1982:
1983:
1984:
1985:
1986:
1987:
1988:
1989:
1990:
1991:
1992:
1993:
1994:
1995:
1996:
1997:
1998:
1999:
2000:
2001:
2002:
2003:
2004:
2005:
2006:
2007:
2008:
2009:
2010:
2011:
2012:
2013:
2014:
2015:
2016:
2017:
2018:
2019:
2020:
2021:
2022:
2023:
2024:
2025:
2026:
2027:
2028:
2029:
2030:
2031:
2032:
2033:
2034:
2035:
2036:
2037:
2038:
2039:
2040:
2041:
2042:
2043:
2044:
2045:
2046:
2047:
2048:
2049:
2050:
2051:
2052:
2053:
2054:
2055:
2056:
2057:
2058:
2059:
2060:
2061:
2062:
2063:
2064:
2065:
2066:
2067:
2068:
2069:
2070:
2071:
2072:
2073:
2074:
2075:
2076:
2077:
2078:
2079:
2080:
2081:
2082:
2083:
2084:
2085:
2086:
2087:
2088:
2089:
2090:
2091:
2092:
2093:
2094:
2095:
2096:
2097:
2098:
2099:
2100:
2101:
2102:
2103:
2104:
2105:
2106:
2107:
2108:
2109:
2110:
2111:
2112:
2113:
2114:
2115:
2116:
2117:
2118:
2119:
2120:
2121:
2122:
2123:
2124:
2125:
2126:
2127:
2128:
2129:
2130:
2131:
2132:
2133:
2134:
2135:
2136:
2137:
2138:
2139:
2140:
2141:
2142:
2143:
2144:
2145:
2146:
2147:
2148:
2149:
2150:
2151:
2152:
2153:
2154:
2155:
2156:
2157:
2158:
2159:
2160:
2161:
2162:
2163:
2164:
2165:
2166:
2167:
2168:
2169:
2170:
2171:
2172:
2173:
2174:
2175:
2176:
2177:
2178:
2179:
2180:
2181:
2182:
2183:
2184:
2185:
2186:
2187:
2188:
2189:
2190:
2191:
2192:
2193:
2194:
2195:
2196:
2197:
2198:
2199:
2200:
2201:
2202:
2203:
2204:
2205:
2206:
2207:
2208:
2209:
2210:
2211:
2212:
2213:
2214:
2215:
2216:
2217:
2218:
2219:
2220:
2221:
2222:
2223:
2224:
2225:
2226:
2227:
2228:
2229:
2230:
2231:
2232:
2233:
2234:
2235:
2236:
2237:
2238:
2239:
2240:
2241:
2242:
2243:
2244:
2245:
2246:
2247:
2248:
2249:
2250:
2251:
2252:
2253:
2254:
2255:
2256:
2257:
2258:
2259:
2260:
2261:
2262:
2263:
2264:
2265:
2266:
2267:
2268:
2269:
2270:
2271:
2272:
2273:
2274:
2275:
2276:
2277:
2278:
2279:
2280:
2281:
2282:
2283:
2284:
2285:
2286:
2287:
2288:
2289:
2290:
2291:
2292:
2293:
2294:
2295:
2296:
2297:
2298:
2299:
2300:
2301:
2302:
2303:
2304:
2305:
2306:
2307:
2308:
2309:
2310:
2311:
2312:
2313:
2314:
2315:
2316:
2317:
2318:
2319:
2320:
2321:
2322:
2323:
2324:
2325:
2326:
2327:
2328:
2329:
2330:
2331:
2332:
2333:
2334:
2335:
2336:
2337:
2338:
2339:
2340:
2341:
2342:
2343:
2344:
2345:
2346:
2347:
2348:
2349:
2350:
2351:
2352:
2353:
2354:
2355:
2356:
2357:
2358:
2359:
2360:
2361:
2362:
2363:
2364:
2365:
2366:
2367:
2368:
2369:
2370:
2371:
2372:
2373:
2374:
2375:
2376:
2377:
2378:
2379:
2380:
2381:
2382:
2383:
2384:
2385:
2386:
2387:
2388:
2389:
2390:
2391:
2392:
2393:
2394:
2395:
2396:
2397:
2398:
2399:
2400:
2401:
2402:
2403:
2404:
2405:
2406:
2407:
2408:
2409:
2410:
2411:
2412:
2413:
2414:
2415:
2416:
2417:
2418:
2419:
2420:
2421:
2422:
2423:
2424:
2425:
2426:
2427:
2428:
2429:
2430:
2431:
2432:
2433:
2434:
2435:
2436:
2437:
2438:
2439:
2440:
2441:
2442:
2443:
2444:
2445:
2446:
2447:
2448:
2449:
2450:
2451:
2452:
2453:
2454:
2455:
2456:
2457:
2458:
2459:
2460:
2461:
2462:
2463:
2464:
2465:
2466:
2467:
2468:
2469:
2470:
2471:
2472:
2473:
2474:
2475:
2476:
2477:
2478:
2479:
2480:
2481:
2482:
2483:
2484:
2485:
2486:
2487:
2488:
2489:
2490:
2491:
2492:
2493:
2494:
2495:
2496:
2497:
2498:
2499:
2500:
2501:
2502:
2503:
2504:
2505:
2506:
2507:
2508:
2509:
2510:
2511:
2512:
2513:
2514:
2515:
2516:
2517:
2518:
2519:
2520:
2521:
2522:
2523:
2524:
2525:
2526:
2527:
2528:
2529:
2530:
2531:
2532:
2533:
2534:
2535:
2536:
2537:
2538:
2539:
2540:
2541:
2542:
2543:
2544:
2545:
2546:
2547:
2548:
2549:
2550:
2551:
2552:
2553:
2554:
2555:
2556:
2557:
2558:
2559:
2560:
2561:
2562:
2563:
2564:
2565:
2566:
2567:
2568:
2569:
2570:
2571:
2572:
2573:
2574:
2575:
2576:
2577:
2578:
2579:
2580:
2581:
2582:
2583:
2584:
2585:
2586:
2587:
2588:
2589:
2590:
2591:
2592:
2593:
2594:
2595:
2596:
2597:
2598:
2599:
2600:
2601:
2602:
2603:
2604:
2605:
2606:
2607:
2608:
2609:
2610:
2611:
2612:
2613:
2614:
2615:
2616:
2617:
2618:
2619:
2620:
2621:
2622:
2623:
2624:
2625:
2626:
2627:
2628:
2629:
2630:
2631:
2632:
2633:
2634:
2635:
2636:
2637:
2638:
2639:
2640:
2641:
2642:
2643:
2644:
2645:
2646:
2647:
2648:
2649:
2650:
2651:
2652:
2653:
2654:
2655:
2656:
2657:
2658:
2659:
2660:
2661:
2662:
2663:
2664:
2665:
2666:
2667:
2668:
2669:
2670:
2671:
2672:
2673:
2674:
2675:
2676:
2677:
2678:
2679:
2680:
2681:
2682:
2683:
2684:
2685:
2686:
2687:
2688:
2689:
2690:
2691:
2692:
2693:
2694:
2695:
2696:
2697:
2698:
2699:
2700:
2701:
2702:
2703:
2704:
2705:
2706:
2707:
2708:
2709:
2710:
2711:
2712:
2713:
2714:
2715:
2716:
2717:
2718:
2719:
2720:
2721:
2722:
2723:
2724:
2725:
2726:
2727:
2728:
2729:
2730:
2731:
2732:
2733:
2734:
2735:
2736:
2737:
2738:
2739:
2740:
2741:
2742:
2743:
2744:
2745:
2746:
2747:
2748:
2749:
2750:
2751:
2752:
2753:
2754:
2755:
2756:
2757:
2758:
2759:
2760:
2761:
2762:
2763:
2764:
2765:
2766:
2767:
2768:
2769:
2770:
2771:
2772:
2773:
2774:
2775:
2776:
2777:
2778:
2779:
2780:
2781:
2782:
2783:
2784:
2785:
2786:
2787:
2788:
2789:
2790:
2791:
2792:
2793:
2794:
2795:
2796:
2797:
2798:
2799:
2800:
2801:
2802:
2803:
2804:
2805:
2806:
2807:
2808:
2809:
2810:
2811:
2812:
2813:
2814:
2815:
2816:
2817:
2818:
2819:
2820:
2821:
2822:
2823:
2824:
2825:
2826:
2827:
2828:
2829:
2830:
2831:
2832:
2833:
2834:
2835:
2836:
2837:
2838:
2839:
2840:
2841:
2842:
2843:
2844:
2845:
2846:
2847:
2848:
2849:
2850:
2851:
2852:
2853:
2854:
2855:
2856:
2857:
2858:
2859:
2860:
2861:
2862:
2863:
2864:
2865:
2866:
2867:
2868:
2869:
2870:
2871:
2872:
2873:
2874:
2875:
2876:
2877:
2878:
2879:
2880:
2881:
2882:
2883:
2884:
2885:
2886:
2887:
2888:
2889:
2890:
2891:
2892:
2893:
2894:
2895:
2896:
2897:
2898:
2899:
2900:
2901:
2902:
2903:
2904:
2905:
2906:
2907:
2908:
2909:
2910:
2911:
2912:
2913:
2914:
2915:
2916:
2917:
2918:
2919:
2920:
2921:
2922:
2923:
2924:
2925:
2926:
2927:
2928:
2929:
2930:
2931:
2932:
2933:
2934:
2935:
2936:
2937:
2938:
2939:
2940:
2941:
2942:
2943:
2944:
2945:
2946:
2947:
2948:
2949:
2950:
2951:
2952:
2953:
2954:
2955:
2956:
2957:
2958:
2959:
2960:
2961:
2962:
2963:
2964:
2965:
2966:
2967:
2968:
2969:
2970:
2971:
2972:
2973:
2974:
2975:
2976:
2977:
2978:
2979:
2980:
2981:
2982:
2983:
2984:
2985:
2986:
2987:
2988:
2989:
2990:
2991:
2992:
2993:
2994:
2995:
2996:
2997:
2998:
2999:
3000:
3001:
3002:
3003:
3004:
3005:
3006:
3007:
3008:
3009:
3010:
3011:
3012:
3013:
3014:
3015:
3016:
3017:
3018:
3019:
3020:
3021:
3022:
3023:
3024:
3025:
3026:
3027:
3028:
3029:
3030:
3031:
3032:
3033:
3034:
3035:
3036:
3037:
3038:
3039:
3040:
3041:
3042:
3043:
3044:
3045:
3046:
3047:
3048:
3049:
3050:
3051:
3052:
3053:
3054:
3055:
3056:
3057:
3058:
3059:
3060:
3061:
3062:
3063:
3064:
3065:
3066:
3067:
3068:
3069:
3070:
3071:
3072:
3073:
3074:
3075:
3076:
3077:
3078:
3079:
3080:
3081:
3082:
3083:
3084:
3085:
3086:
3087:
3088:
3089:
3090:
3091:
3092:
3093:
3094:
3095:
3096:
3097:
3098:
3099:
3100:
3101:
3102:
3103:
3104:
3105:
3106:
3107:
3108:
3109:
3110:
3111:
3112:
3113:
3114:
3115:
3116:
3117:
3118:
3119:
3120:
3121:
3122:
3123:
3124:
3125:
3126:
3127:
3128:
3129:
3130:
3131:
3132:
3133:
3134:
3135:
3136:
3137:
3138:
3139:
3140:
3141:
3142:
3143:
3144:
3145:
3146:
3147:
3148:
3149:
3150:
3151:
3152:
3153:
3154:
3155:
3156:
3157:
3158:
3159:
3160:
3161:
3162:
3163:
3164:
3165:
3166:
3167:
3168:
3169:
3170:
3171:
3172:
3173:
3174:
3175:
3176:
3177:
3178:
3179:
3180:
3181:
3182:
3183:
3184:
3185:
3186:
3187:
3188:
3189:
3190:
3191:
3192:
3193:
3194:
3195:
3196:
3197:
3198:
3199:
3200:
3201:
3202:
3203:
3204:
3205:
3206:
3207:
3208:
3209:
3210:
3211:
3212:
3213:
3214:
3215:
3216:
3217:
3218:
3219:
3220:
3221:
3222:
3223:
3224:
3225:
3226:
3227:
3228:
3229:
3230:
3231:
3232:
3233:
3234:
3235:
3236:
3237:
3238:
3239:
3240:
3241:
3242:
3243:
3244:
3245:
3246:
3247:
3248:
3249:
3250:
3251:
3252:
3253:
3254:
3255:
3256:
3257:
3258:
3259:
3260:
3261:
3262:
3263:
3264:
3265:
3266:
3267:
3268:
3269:
3270:
3271:
3272:
3273:
3274:
3275:
3276:
3277:
3278:
3279:
3280:
3281:
3282:
3283:
3284:
3285:
3286:
3287:
3288:
3289:
3290:
3291:
3292:
3293:
3294:
3295:
3296:
3297:
3298:
3299:
3300:
3301:
3302:
3303:
3304:
3305:
3306:
3307:
3308:
3309:
3310:
3311:
3312:
3313:
3314:
3315:
3316:
3317:
3318:
3319:
3320:
3321:
3322:
3323:
3324:
3325:
3326:
3327:
3328:
3329:
3330:
3331:
3332:
3333:
3334:
3335:
3336:
3337:
3338:
3339:
3340:
3341:
3342:
3343:
3344:
3345:
3346:
3347:
3348:
3349:
3350:
3351:
3352:
3353:
3354:
3355:
3356:
3357:
3358:
3359:
3360:
3361:
3362:
3363:
3364:
3365:
3366:
3367:
3368:
3369:
3370:
3371:
3372:
3373:
3374:
3375:
3376:
3377:
3378:
3379:
3380:
3381:
3382:
3383:
3384:
3385:
3386:
3387:
3388:
3389:
3390:
3391:
3392:
3393:
3394:
3395:
3396:
3397:
3398:
3399:
3400:
3401:
3402:
3403:
3404:
3405:
3406:
3407:
3408:
3409:
3410:
3411:
3412:
3413:
3414:
3415:
3416:
3417:
3418:
3419:
3420:
3421:
3422:
3423:
3424:
3425:
3426:
3427:
3428:
3429:
3430:
3431:
3432:
3433:
3434:
3435:
3436:
3437:
3438:
3439:
3440:
3441:
3442:
3443:
3444:
3445:
3446:
3447:
3448:
3449:
3450:
3451:
3452:
3453:
3454:
3455:
3456:
3457:
3458:
3459:
3460:
3461:
3462:
3463:
3464:
3465:
3466:
3467:
3468:
3469:
3470:
3471:
3472:
3473:
3474:
3475:
3476:
3477:
3478:
3479:
3480:
3481:
3482:
3483:
3484:
3485:
3486:
3487:
3488:
3489:
3490:
3491:
3492:
3493:
3494:
3495:
3496:
3497:
3498:
3499:
3500:
3501:
3502:
3503:
3504:
3505:
3506:
3507:
3508:
3509:
3510:
3511:
3512:
3513:
3514:
3515:
3516:
3517:
3518:
3519:
3520:
3521:
3522:
3523:
3524:
3525:
3526:
3527:
3528:
3529:
3530:
3531:
3532:
3533:
3534:
3535:
3536:
3537:
3538:
3539:
3540:
3541:
3542:
3543:
3544:
3545:
3546:
3547:
3548:
3549:
3550:
3551:
3552:
3553:
3554:
3555:
3556:
3557:
3558:
3559:
3560:
3561:
3562:
3563:
3564:
3565:
3566:
3567:
3568:
3569:
3570:
3571:
3572:
3573:
3574:
3575:
3576:
3577:
3578:
3579:
3580:
3581:
3582:
3583:
3584:
3585:
3586:
3587:
3588:
3589:
3590:
3591:
3592:
3593:
3594:
3595:
3596:
3597:
3598:
3599:
3600:
3601:
3602:
3603:
3604:
3605:
3606:
3607:
3608:
3609:
3610:
3611:
3612:
3613:
3614:
3615:
3616:
3617:
3618:
3619:
3620:
3621:
3622:
3623:
3624:
3625:
3626:
3627:
3628:
3629:
3630:
3631:
3632:
3633:
3634:
3635:
3636:
3637:
3638:
3639:
3640:
3641:
3642:
3643:
3644:
3645:
3646:
3647:
3648:
3649:
3650:
3651:
3652:
3653:
3654:
3655:
3656:
3657:
3658:
3659:
3660:
3661:
3662:
3663:
3664:
3665:
3666:
3667:
3668:
3669:
3670:
3671:
3672:
3673:
3674:
3675:
3676:
3677:
3678:
3679:
3680:
3681:
3682:
3683:
3684:
3685:
3686:
3687:
3688:
3689:
3690:
3691:
3692:
3693:
3694:
3695:
3696:
3697:
3698:
3699:
3700:
3701:
3702:
3703:
3704:
3705:
3706:
3707:
3708:
3709:
3710:
3711:
3712:
3713:
3714:
3715:
3716:
3717:
3718:
3719:
3720:
3721:
3722:
3723:
3724:
3725:
3726:
3727:
3728:
3729:
3730:
3731:
3732:
3733:
3734:
3735:
3736:
3737:
3738:
3739:
3740:
3741:
3742:
3743:
3744:
3745:
3746:
3747:
3748:
3749:
3750:
3751:
3752:
3753:
3754:
3755:
3756:
3757:
3758:
3759:
3760:
3761:
3762:
3763:
3764:
3765:
3766:
3767:
3768:
3769:
3770:
3771:
3772:
3773:
3774:
3775:
3776:
3777:
3778:
3779:
3780:
3781:
3782:
3783:
3784:
3785:
3786:
3787:
3788:
3789:
3790:
3791:
3792:
3793:
3794:
3795:
3796:
3797:
3798:
3799:
3800:
3801:
3802:
3803:
3804:
3805:
3806:
3807:
3808:
3809:
3810:
3811:
3812:
3813:
3814:
3815:
3816:
3817:
3818:
3819:
3820:
3821:
3822:
3823:
3824:
3825:
3826:
3827:
3828:
3829:
3830:
3831:
3832:
3833:
3834:
3835:
3836:
3837:
3838:
3839:
3840:
3841:
3842:
3843:
3844:
3845:
3846:
3847:
3848:
3849:
3850:
3851:
3852:
3853:
3854:
3855:
3856:
3857:
3858:
3859:
3860:
3861:
3862:
3863:
3864:
3865:
3866:
3867:
3868:
3869:
3870:
3871:
3872:
3873:
3874:
3875:
3876:
3877:
3878:
3879:
3880:
3881:
3882:
3883:
3884:
3885:
3886:
3887:
3888:
3889:
3890:
3891:
3892:
3893:
3894:
3895:
3896:
3897:
3898:
3899:
3900:
3901:
3902:
3903:
3904:
3905:
3906:
3907:
3908:
3909:
3910:
3911:
3912:
3913:
3914:
3915:
3916:
3917:
3918:
3919:
3920:
3921:
3922:
3923:
3924:
3925:
3926:
3927:
3928:
3929:
3930:
3931:
3932:
3933:
3934:
3935:
3936:
3937:
3938:
3939:
3940:
3941:
3942:
3943:
3944:
3945:
3946:
3947:
3948:
3949:
3950:
3951:
3952:
3953:
3954:
3955:
3956:
3957:
3958:
3959:
3960:
3961:
3962:
3963:
3964:
3965:
3966:
3967:
3968:
3969:
3970:
3971:
3972:
3973:
3974:
3975:
3976:
3977:
3978:
3979:
3980:
3981:
3982:
3983:
3984:
3985:
3986:
3987:
3988:
3989:
3990:
3991:
3992:
3993:
3994:
3995:
3996:
3997:
3998:
3999:
4000:
4001:
4002:
4003:
4004:
4005:
4006:
4007:
4008:
4009:
4010:
4011:
4012:
4013:
4014:
4015:
4016:
4017:
4018:
4019:
4020:
4021:
4022:
4023:
4024:
4025:
4026:
4027:
4028:
4029:
4030:
4031:
4032:
4033:
4034:
4035:
4036:
4037:
4038:
4039:
4040:
4041:
4042:
4043:
4044:
4045:
4046:
4047:
4048:
4049:
4050:
4051:
4052:
4053:
4054:
4055:
4056:
4057:
4058:
4059:
4060:
4061:
4062:
4063:
4064:
4065:
4066:
4067:
4068:
4069:
4070:
4071:
4072:
4073:
4074:
4075:
4076:
4077:
4078:
4079:
4080:
4081:
4082:
4083:
4084:
4085:
4086:
4087:
4088:
4089:
4090:
4091:
4092:
4093:
4094:
4095:
4096:
4097:
4098:
4099:
4100:
4101:
4102:
4103:
4104:
4105:
4106:
4107:
4108:
4109:
4110:
4111:
4112:
4113:
4114:
4115:
4116:
4117:
4118:
4119:
4120:
4121:
4122:
4123:
4124:
4125:
4126:
4127:
4128:
4129:
4130:
4131:
4132:
4133:
4134:
4135:
4136:
4137:
4138:
4139:
4140:
4141:
4142:
4143:
4144:
4145:
4146:
4147:
4148:
4149:
4150:
4151:
4152:
4153:
4154:
4155:
4156:
4157:
4158:
4159:
4160:
4161:
4162:
4163:
4164:
4165:
4166:
4167:
4168:
4169:
4170:
4171:
4172:
4173:
4174:
4175:
4176:
4177:
4178:
4179:
4180:
4181:
4182:
4183:
4184:
4185:
4186:
4187:
4188:
4189:
4190:
4191:
4192:
4193:
4194:
4195:
4196:
4197:
4198:
4199:
4200:
4201:
4202:
4203:
4204:
4205:
4206:
4207:
4208:
4209:
4210:
4211:
4212:
4213:
4214:
4215:
4216:
4217:
4218:
4219:
4220:
4221:
4222:
4223:
4224:
4225:
4226:
4227:
4228:
4229:
4230:
4231:
4232:
4233:
4234:
4235:
4236:
4237:
4238:
4239:
4240:
4241:
4242:
4243:
4244:
4245:
4246:
4247:
4248:
4249:
4250:
4251:
4252:
4253:
4254:
4255:
4256:
4257:
4258:
4259:
4260:
4261:
4262:
4263:
4264:
4265:
4266:
4267:
4268:
4269:
4270:
4271:
4272:
4273:
4274:
4275:
4276:
4277:
4278:
4279:
4280:
4281:
4282:
4283:
4284:
4285:
4286:
4287:
4288:
4289:
4290:
4291:
4292:
4293:
4294:
4295:
4296:
4297:
4298:
4299:
4300:
4301:
4302:
4303:
4304:
4305:
4306:
4307:
4308:
4309:
4310:
4311:
4312:
4313:
4314:
4315:
4316:
4317:
4318:
4319:
4320:
4321:
4322:
4323:
4324:
4325:
4326:
4327:
4328:
4329:
4330:
4331:
4332:
4333:
4334:
4335:
4336:
4337:
4338:
4339:
4340:
4341:
4342:
4343:
4344:
4345:
4346:
4347:
4348:
4349:
4350:
4351:
4352:
4353:
4354:
4355:
4356:
4357:
4358:
4359:
4360:
4361:
4362:
4363:
4364:
4365:
4366:
4367:
4368:
4369:
4370:
4371:
4372:
4373:
4374:
4375:
4376:
4377:
4378:
4379:
4380:
4381:
4382:
4383:
4384:
4385:
4386:
4387:
4388:
4389:
4390:
4391:
4392:
4393:
4394:
4395:
4396:
4397:
4398:
4399:
4400:
4401:
4402:
4403:
4404:
4405:
4406:
4407:
4408:
4409:
4410:
4411:
4412:
4413:
4414:
4415:
4416:
4417:
4418:
4419:
4420:
4421:
4422:
4423:
4424:
4425:
4426:
4427:
4428:
4429:
4430:
4431:
4432:
4433:
4434:
4435:
4436:
4437:
4438:
4439:
4440:
4441:
4442:
4443:
4444:
4445:
4446:
4447:
4448:
4449:
4450:
4451:
4452:
4453:
4454:
4455:
4456:
4457:
4458:
4459:
4460:
4461:
4462:
4463:
4464:
4465:
4466:
4467:
4468:
4469:
4470:
4471:
4472:
4473:
4474:
4475:
4476:
4477:
4478:
4479:
4480:
4481:
4482:
4483:
4484:
4485:
4486:
4487:
4488:
4489:
4490:
4491:
4492:
4493:
4494:
4495:
4496:
4497:
4498:
4499:
4500:
4501:
4502:
4503:
4504:
4505:
4506:
4507:
4508:
4509:
4510:
4511:
4512:
4513:
4514:
4515:
4516:
4517:
4518:
4519:
4520:
4521:
4522:
4523:
4524:
4525:
4526:
4527:
4528:
4529:
4530:
4531:
4532:
4533:
4534:
4535:
4536:
4537:
4538:
4539:
4540:
4541:
4542:
4543:
4544:
4545:
4546:
4547:
4548:
4549:
4550:
4551:
4552:
4553:
4554:
4555:
4556:
4557:
4558:
4559:
4560:
4561:
4562:
4563:
4564:
4565:
4566:
4567:
4568:
4569:
4570:
4571:
4572:
4573:
4574:
4575:
4576:
4577:
4578:
4579:
4580:
4581:
4582:
4583:
4584:
4585:
4586:
4587:
4588:
4589:
4590:
4591:
4592:
4593:
4594:
4595:
4596:
4597:
4598:
4599:
4600:
4601:
4602:
4603:
4604:
4605:
4606:
4607:
4608:
4609:
4610:
4611:
4612:
4613:
4614:
4615:
4616:
4617:
4618:
4619:
4620:
4621:
4622:
4623:
4624:
4625:
4626:
4627:
4628:
4629:
4630:
4631:
4632:
4633:
4634:
4635:
4636:
4637:
4638:
4639:
4640:
4641:
4642:
4643:
4644:
4645:
4646:
4647:
4648:
4649:
4650:
4651:
4652:
4653:
4654:
4655:
4656:
4657:
4658:
4659:
4660:
4661:
4662:
4663:
4664:
4665:
4666:
4667:
4668:
4669:
4670:
4671:
4672:
4673:
4674:
4675:
4676:
4677:
4678:
4679:
4680:
4681:
4682:
4683:
4684:
4685:
4686:
4687:
4688:
4689:
4690:
4691:
4692:
4693:
4694:
4695:
4696:
4697:
4698:
4699:
4700:
4701:
4702:
4703:
4704:
4705:
4706:
4707:
4708:
4709:
4710:
4711:
4712:
4713:
4714:
4715:
4716:
4717:
4718:
4719:
4720:
4721:
4722:
4723:
4724:
4725:
4726:
4727:
4728:
4729:
4730:
4731:
4732:
4733:
4734:
4735:
4736:
4737:
4738:
4739:
4740:
4741:
4742:
4743:
4744:
4745:
4746:
4747:
4748:
4749:
4750:
4751:
4752:
4753:
4754:
4755:
4756:
4757:
4758:
4759:
4760:
4761:
4762:
4763:
4764:
4765:
4766:
4767:
4768:
4769:
4770:
4771:
4772:
4773:
4774:
4775:
4776:
4777:
4778:
4779:
4780:
4781:
4782:
4783:
4784:
4785:
4786:
4787:
4788:
4789:
4790:
4791:
4792:
4793:
4794:
4795:
4796:
4797:
4798:
4799:
4800:
4801:
4802:
4803:
4804:
4805:
4806:
4807:
4808:
4809:
4810:
4811:
4812:
4813:
4814:
4815:
4816:
4817:
4818:
4819:
4820:
4821:
4822:
4823:
4824:
4825:
4826:
4827:
4828:
4829:
4830:
4831:
4832:
4833:
4834:
4835:
4836:
4837:
4838:
4839:
4840:
4841:
4842:
4843:
4844:
4845:
4846:
4847:
4848:
4849:
4850:
4851:
4852:
4853:
4854:
4855:
4856:
4857:
4858:
4859:
4860:
4861:
4862:
4863:
4864:
4865:
4866:
4867:
4868:
4869:
4870:
4871:
4872:
4873:
4874:
4875:
4876:
4877:
4878:
4879:
4880:
4881:
4882:
4883:
4884:
4885:
4886:
4887:
4888:
4889:
4890:
4891:
4892:
4893:
4894:
4895:
4896:
4897:
4898:
4899:
4900:
4901:
4902:
4903:
4904:
4905:
4906:
4907:
4908:
4909:
4910:
4911:
4912:
4913:
4914:
4915:
4916:
4917:
4918:
4919:
4920:
4921:
4922:
4923:
4924:
4925:
4926:
4927:
4928:
4929:
4930:
4931:
4932:
4933:
4934:
4935:
4936:
4937:
4938:
4939:
4940:
4941:
4942:
4943:
4944:
4945:
4946:
4947:
4948:
4949:
4950:
4951:
4952:
4953:
4954:
4955:
4956:
4957:
4958:
4959:
4960:
4961:
4962:
4963:
4964:
4965:
4966:
4967:
4968:
4969:
4970:
4971:
4972:
4973:
4974:
4975:
4976:
4977:
4978:
4979:
4980:
4981:
4982:
4983:
4984:
4985:
4986:
4987:
4988:
4989:
4990:
4991:
4992:
4993:
4994:
4995:
4996:
4997:
4998:
4999:
5000:
5001:
5002:
5003:
5004:
5005:
5006:
5007:
5008:
5009:
5010:
5011:
5012:
5013:
5014:
5015:
5016:
5017:
5018:
5019:
5020:
5021:
5022:
5023:
5024:
5025:
5026:
5027:
5028:
5029:
5030:
5031:
5032:
5033:
5034:
5035:
5036:
5037:
5038:
5039:
5040:
5041:
5042:
5043:
5044:
5045:
5046:
5047:
5048:
5049:
5050:
5051:
5052:
5053:
5054:
5055:
5056:
5057:
5058:
5059:
5060:
5061:
5062:
5063:
5064:
5065:
5066:
5067:
5068:
5069:
5070:
5071:
5072:
5073:
5074:
5075:
5076:
5077:
5078:
5079:
5080:
5081:
5082:
5083:
5084:
5085:
5086:
5087:
5088:
5089:
5090:
5091:
5092:
5093:
5094:
5095:
5096:
5097:
5098:
5099:
5100:
5101:
5102:
5103:
5104:
5105:
5106:
5107:
5108:
5109:
5110:
5111:
5112:
5113:
5114:
5115:
5116:
5117:
5118:
5119:
5120:
5121:
5122:
5123:
5124:
5125:
5126:
5127:
5128:
5129:
5130:
5131:
5132:
5133:
5134:
5135:
5136:
5137:
5138:
5139:
5140:
5141:
5142:
5143:
5144:
5145:
5146:
5147:
5148:
5149:
5150:
5151:
5152:
5153:
5154:
5155:
5156:
5157:
5158:
5159:
5160:
5161:
5162:
5163:
5164:
5165:
5166:
5167:
5168:
5169:
5170:
5171:
5172:
5173:
5174:
5175:
5176:
5177:
5178:
5179:
5180:
5181:
5182:
5183:
5184:
5185:
5186:
5187:
5188:
5189:
5190:
5191:
5192:
5193:
5194:
5195:
5196:
5197:
5198:
5199:
5200:
5201:
5202:
5203:
5204:
5205:
5206:
5207:
5208:
5209:
5210:
5211:
5212:
5213:
5214:
5215:
5216:
5217:
5218:
5219:
5220:
5221:
5222:
5223:
5224:
5225:
5226:
5227:
5228:
5229:
5230:
5231:
5232:
5233:
5234:
5235:
5236:
5237:
5238:
5239:
5240:
5241:
5242:
5243:
5244:
5245:
5246:
5247:
5248:
5249:
5250:
5251:
5252:
5253:
5254:
5255:
5256:
5257:
5258:
5259:
5260:
5261:
5262:
5263:
5264:
5265:
5266:
5267:
5268:
5269:
5270:
5271:
5272:
5273:
5274:
5275:
5276:
5277:
5278:
5279:
5280:
5281:
5282:
5283:
5284:
5285:
5286:
5287:
5288:
5289:
5290:
5291:
5292:
5293:
5294:
5295:
5296:
5297:
5298:
5299:
5300:
5301:
5302:
5303:
5304:
5305:
5306:
5307:
5308:
5309:
5310:
5311:
5312:
5313:
5314:
5315:
5316:
5317:
5318:
5319:
5320:
5321:
5322:
5323:
5324:
5325:
5326:
5327:
5328:
5329:
5330:
5331:
5332:
5333:
5334:
5335:
5336:
5337:
5338:
5339:
5340:
5341:
5342:
5343:
5344:
5345:
5346:
5347:
5348:
5349:
5350:
5351:
5352:
5353:
5354:
5355:
5356:
5357:
5358:
5359:
5360:
5361:
5362:
5363:
5364:
5365:
5366:
5367:
5368:
5369:
5370:
5371:
5372:
5373:
5374:
5375:
5376:
5377:
5378:
5379:
5380:
5381:
5382:
5383:
5384:
5385:
5386:
5387:
5388:
5389:
5390:
5391:
5392:
5393:
5394:
5395:
5396:
5397:
5398:
5399:
5400:
5401:
5402:
5403:
5404:
5405:
5406:
5407:
5408:
5409:
5410:
5411:
5412:
5413:
5414:
5415:
5416:
5417:
5418:
5419:
5420:
5421:
5422:
5423:
5424:
5425:
5426:
5427:
5428:
5429:
5430:
5431:
5432:
5433:
5434:
5435:
5436:
5437:
5438:
5439:
5440:
5441:
5442:
5443:
5444:
5445:
5446:
5447:
5448:
5449:
5450:
5451:
5452:
5453:
5454:
5455:
5456:
5457:
5458:
5459:
5460:
5461:
5462:
5463:
5464:
5465:
5466:
5467:
5468:
5469:
5470:
5471:
5472:
5473:
5474:
5475:
5476:
5477:
5478:
5479:
5480:
5481:
5482:
5483:
5484:
5485:
5486:
5487:
5488:
5489:
5490:
5491:
5492:
5493:
5494:
5495:
5496:
5497:
5498:
5499:
5500:
5501:
5502:
5503:
5504:
5505:
5506:
5507:
5508:
5509:
5510:
5511:
5512:
5513:
5514:
5515:
5516:
5517:
5518:
5519:
5520:
5521:
5522:
5523:
5524:
5525:
5526:
5527:
5528:
5529:
5530:
5531:
5532:
5533:
5534:
5535:
5536:
5537:
5538:
5539:
5540:
5541:
5542:
5543:
5544:
5545:
5546:
5547:
5548:
5549:
5550:
5551:
5552:
5553:
5554:
5555:
5556:
5557:
5558:
5559:
5560:
5561:
5562:
5563:
5564:
5565:
5566:
5567:
5568:
5569:
5570:
5571:
5572:
5573:
5574:
5575:
5576:
5577:
5578:
5579:
5580:
5581:
5582:
5583:
5584:
5585:
5586:
5587:
5588:
5589:
5590:
5591:
5592:
5593:
5594:
5595:
5596:
5597:
5598:
5599:
5600:
5601:
5602:
5603:
5604:
5605:
5606:
5607:
5608:
5609:
5610:
5611:
5612:
5613:
5614:
5615:
5616:
5617:
5618:
5619:
5620:
5621:
5622:
5623:
5624:
5625:
5626:
5627:
5628:
5629:
5630:
5631:
5632:
5633:
5634:
5635:
5636:
5637:
5638:
5639:
5640:
5641:
5642:
5643:
5644:
5645:
5646:
5647:
5648:
5649:
5650:
5651:
5652:
5653:
5654:
5655:
5656:
5657:
5658:
5659:
5660:
5661:
5662:
5663:
5664:
5665:
5666:
5667:
5668:
5669:
5670:
5671:
5672:
5673:
5674:
5675:
5676:
5677:
5678:
5679:
5680:
5681:
5682:
5683:
5684:
5685:
5686:
5687:
5688:
5689:
5690:
5691:
5692:
5693:
5694:
5695:
5696:
5697:
5698:
5699:
5700:
5701:
5702:
5703:
5704:
5705:
5706:
5707:
5708:
5709:
5710:
5711:
5712:
5713:
5714:
5715:
5716:
5717:
5718:
5719:
5720:
5721:
5722:
5723:
5724:
5725:
5726:
5727:
5728:
5729:
5730:
5731:
5732:
5733:
5734:
5735:
5736:
5737:
5738:
5739:
5740:
5741:
5742:
5743:
5744:
5745:
5746:
5747:
5748:
5749:
5750:
5751:
5752:
5753:
5754:
5755:
5756:
5757:
5758:
5759:
5760:
5761:
5762:
5763:
5764:
5765:
5766:
5767:
5768:
5769:
5770:
5771:
5772:
5773:
5774:
5775:
5776:
5777:
5778:
5779:
5780:
5781:
5782:
5783:
5784:
5785:
5786:
5787:
5788:
5789:
5790:
5791:
5792:
5793:
5794:
5795:
5796:
5797:
5798:
5799:
5800:
5801:
5802:
5803:
5804:
5805:
5806:
5807:
5808:
5809:
5810:
5811:
5812:
5813:
5814:
5815:
5816:
5817:
5818:
5819:
5820:
5821:
5822:
5823:
5824:
5825:
5826:
5827:
5828:
5829:
5830:
5831:
5832:
5833:
5834:
5835:
5836:
5837:
5838:
5839:
5840:
5841:
5842:
5843:
5844:
5845:
5846:
5847:
5848:
5849:
5850:
5851:
5852:
5853:
5854:
5855:
5856:
5857:
5858:
5859:
5860:
5861:
5862:
5863:
5864:
5865:
5866:
5867:
5868:
5869:
5870:
5871:
5872:
5873:
5874:
5875:
5876:
5877:
5878:
5879:
5880:
5881:
5882:
5883:
5884:
5885:
5886:
5887:
5888:
5889:
5890:
5891:
5892:
5893:
5894:
5895:
5896:
5897:
5898:
5899:
5900:
5901:
5902:
5903:
5904:
5905:
5906:
5907:
5908:
5909:
5910:
5911:
5912:
5913:
5914:
5915:
5916:
5917:
5918:
5919:
5920:
5921:
5922:
5923:
5924:
5925:
5926:
5927:
5928:
5929:
5930:
5931:
5932:
5933:
5934:
5935:
5936:
5937:
5938:
5939:
5940:
5941:
5942:
5943:
5944:
5945:
5946:
5947:
5948:
5949:
5950:
5951:
5952:
5953:
5954:
5955:
5956:
5957:
5958:
5959:
5960:
5961:
5962:
5963:
5964:
5965:
5966:
5967:
5968:
5969:
5970:
5971:
5972:
5973:
5974:
5975:
5976:
5977:
5978:
5979:
5980:
5981:
5982:
5983:
5984:
5985:
5986:
5987:
5988:
5989:
5990:
5991:
5992:
5993:
5994:
5995:
5996:
5997:
5998:
5999:
6000:
6001:
6002:
6003:
6004:
6005:
6006:
6007:
6008:
6009:
6010:
6011:
6012:
6013:
6014:
6015:
6016:
6017:
6018:
6019:
6020:
6021:
6022:
6023:
6024:
6025:
6026:
6027:
6028:
6029:
6030:
6031:
6032:
6033:
6034:
6035:
6036:
6037:
6038:
6039:
6040:
6041:
6042:
6043:
6044:
6045:
6046:
6047:
6048:
6049:
6050:
6051:
6052:
6053:
6054:
6055:
6056:
6057:
6058:
6059:
6060:
6061:
6062:
6063:
6064:
6065:
6066:
6067:
6068:
6069:
6070:
6071:
6072:
6073:
6074:
6075:
6076:
6077:
6078:
6079:
6080:
6081:
6082:
6083:
6084:
6085:
6086:
6087:
6088:
6089:
6090:
6091:
6092:
6093:
6094:
6095:
6096:
6097:
6098:
6099:
6100:
6101:
6102:
6103:
6104:
6105:
6106:
6107:
6108:
6109:
6110:
6111:
6112:
6113:
6114:
6115:
6116:
6117:
6118:
6119:
6120:
6121:
6122:
6123:
6124:
6125:
6126:
6127:
6128:
6129:
6130:
6131:
6132:
6133:
6134:
6135:
6136:
6137:
6138:
6139:
6140:
6141:
6142:
6143:
6144:
6145:
6146:
6147:
6148:
6149:
6150:
6151:
6152:
6153:
6154:
6155:
6156:
6157:
6158:
6159:
6160:
6161:
6162:
6163:
6164:
6165:
6166:
6167:
6168:
6169:
6170:
6171:
6172:
6173:
6174:
6175:
6176:
6177:
6178:
6179:
6180:
6181:
6182:
6183:
6184:
6185:
6186:
6187:
6188:
6189:
6190:
6191:
6192:
6193:
6194:
6195:
6196:
6197:
6198:
6199:
6200:
6201:
6202:
6203:
6204:
6205:
6206:
6207:
6208:
6209:
6210:
6211:
6212:
6213:
6214:
6215:
6216:
6217:
6218:
6219:
6220:
6221:
6222:
6223:
6224:
6225:
6226:
6227:
6228:
6229:
6230:
6231:
6232:
6233:
6234:
6235:
6236:
6237:
6238:
6239:
6240:
6241:
6242:
6243:
6244:
6245:
6246:
6247:
6248:
6249:
6250:
6251:
6252:
6253:
6254:
6255:
6256:
6257:
6258:
6259:
6260:
6261:
6262:
6263:
6264:
6265:
6266:
6267:
6268:
6269:
6270:
6271:
6272:
6273:
6274:
6275:
6276:
6277:
6278:
6279:
6280:
6281:
6282:
6283:
6284:
6285:
6286:
6287:
6288:
6289:
6290:
6291:
6292:
6293:
6294:
6295:
6296:
6297:
6298:
6299:
6300:
6301:
6302:
6303:
6304:
6305:
6306:
6307:
6308:
6309:
6310:
6311:
6312:
6313:
6314:
6315:
6316:
6317:
6318:
6319:
6320:
6321:
6322:
6323:
6324:
6325:
6326:
6327:
6328:
6329:
6330:
6331:
6332:
6333:
6334:
6335:
6336:
6337:
6338:
6339:
6340:
6341:
6342:
6343:
6344:
6345:
6346:
6347:
6348:
6349:
6350:
6351:
6352:
6353:
6354:
6355:
6356:
6357:
6358:
6359:
6360:
6361:
6362:
6363:
6364:
6365:
6366:
6367:
6368:
6369:
6370:
6371:
6372:
6373:
6374:
6375:
6376:
6377:
6378:
6379:
6380:
6381:
6382:
6383:
6384:
6385:
6386:
6387:
6388:
6389:
6390:
6391:
6392:
6393:
6394:
6395:
6396:
6397:
6398:
6399:
6400:
6401:
6402:
6403:
6404:
6405:
6406:
6407:
6408:
6409:
6410:
6411:
6412:
6413:
6414:
6415:
6416:
6417:
6418:
6419:
6420:
6421:
6422:
6423:
6424:
6425:
6426:
6427:
6428:
6429:
6430:
6431:
6432:
6433:
6434:
6435:
6436:
6437:
6438:
6439:
6440:
6441:
6442:
6443:
6444:
6445:
6446:
6447:
6448:
6449:
6450:
6451:
6452:
6453:
6454:
6455:
6456:
6457:
6458:
6459:
6460:
6461:
6462:
6463:
6464:
6465:
6466:
6467:
6468:
6469:
6470:
6471:
6472:
6473:
6474:
6475:
6476:
6477:
6478:
6479:
6480:
6481:
6482:
6483:
6484:
6485:
6486:
6487:
6488:
6489:
6490:
6491:
6492:
6493:
6494:
6495:
6496:
6497:
6498:
6499:
6500:
6501:
6502:
6503:
6504:
6505:
6506:
6507:
6508:
6509:
6510:
6511:
6512:
6513:
6514:
6515:
6516:
6517:
6518:
6519:
6520:
6521:
6522:
6523:
6524:
6525:
6526:
6527:
6528:
6529:
6530:
6531:
6532:
6533:
6534:
6535:
6536:
6537:
6538:
6539:
6540:
6541:
6542:
6543:
6544:
6545:
6546:
6547:
6548:
6549:
6550:
6551:
6552:
6553:
6554:
6555:
6556:
6557:
6558:
6559:
6560:
6561:
6562:
6563:
6564:
6565:
6566:
6567:
6568:
6569:
6570:
6571:
6572:
6573:
6574:
6575:
6576:
6577:
6578:
6579:
6580:
6581:
6582:
6583:
6584:
6585:
6586:
6587:
6588:
6589:
6590:
6591:
6592:
6593:
6594:
6595:
6596:
6597:
6598:
6599:
6600:
6601:
6602:
6603:
6604:
6605:
6606:
6607:
6608:
6609:
6610:
6611:
6612:
6613:
6614:
6615:
6616:
6617:
6618:
6619:
6620:
6621:
6622:
6623:
6624:
6625:
6626:
6627:
6628:
6629:
6630:
6631:
6632:
6633:
6634:
6635:
6636:
6637:
6638:
6639:
6640:
6641:
6642:
6643:
6644:
6645:
6646:
6647:
6648:
6649:
6650:
6651:
6652:
6653:
6654:
6655:
6656:
6657:
6658:
6659:
6660:
6661:
6662:
6663:
6664:
6665:
6666:
6667:
6668:
6669:
6670:
6671:
6672:
6673:
6674:
6675:
6676:
6677:
6678:
6679:
6680:
6681:
6682:
6683:
6684:
6685:
6686:
6687:
6688:
6689:
6690:
6691:
6692:
6693:
6694:
6695:
6696:
6697:
6698:
6699:
6700:
6701:
6702:
6703:
6704:
6705:
6706:
6707:
6708:
6709:
6710:
6711:
6712:
6713:
6714:
6715:
6716:
6717:
6718:
6719:
6720:
6721:
6722:
6723:
6724:
6725:
6726:
6727:
6728:
6729:
6730:
6731:
6732:
6733:
6734:
6735:
6736:
6737:
6738:
6739:
6740:
6741:
6742:
6743:
6744:
6745:
6746:
6747:
6748:
6749:
6750:
6751:
6752:
6753:
6754:
6755:
6756:
6757:
6758:
6759:
6760:
6761:
6762:
6763:
6764:
6765:
6766:
6767:
6768:
6769:
6770:
6771:
6772:
6773:
6774:
6775:
6776:
6777:
6778:
6779:
6780:
6781:
6782:
6783:
6784:
6785:
6786:
6787:
6788:
6789:
6790:
6791:
6792:
6793:
6794:
6795:
6796:
6797:
6798:
6799:
6800:
6801:
6802:
6803:
6804:
6805:
6806:
6807:
6808:
6809:
6810:
6811:
6812:
6813:
6814:
6815:
6816:
6817:
6818:
6819:
6820:
6821:
6822:
6823:
6824:
6825:
6826:
6827:
6828:
6829:
6830:
6831:
6832:
6833:
6834:
6835:
6836:
6837:
6838:
6839:
6840:
6841:
6842:
6843:
6844:
6845:
6846:
6847:
6848:
6849:
6850:
6851:
6852:
6853:
6854:
6855:
6856:
6857:
6858:
6859:
6860:
6861:
6862:
6863:
6864:
6865:
6866:
6867:
6868:
6869:
6870:
6871:
6872:
6873:
6874:
6875:
6876:
6877:
6878:
6879:
6880:
6881:
6882:
6883:
6884:
6885:
6886:
6887:
6888:
6889:
6890:
6891:
6892:
6893:
6894:
6895:
6896:
6897:
6898:
6899:
6900:
6901:
6902:
6903:
6904:
6905:
6906:
6907:
6908:
6909:
6910:
6911:
6912:
6913:
6914:
6915:
6916:
6917:
6918:
6919:
6920:
6921:
6922:
6923:
6924:
6925:
6926:
6927:
6928:
6929:
6930:
6931:
6932:
6933:
6934:
6935:
6936:
6937:
6938:
6939:
6940:
6941:
6942:
6943:
6944:
6945:
6946:
6947:
6948:
6949:
6950:
6951:
6952:
6953:
6954:
6955:
6956:
6957:
6958:
6959:
6960:
6961:
6962:
6963:
6964:
6965:
6966:
6967:
6968:
6969:
6970:
6971:
6972:
6973:
6974:
6975:
6976:
6977:
6978:
6979:
6980:
6981:
6982:
6983:
6984:
6985:
6986:
6987:
6988:
6989:
6990:
6991:
6992:
6993:
6994:
6995:
6996:
6997:
6998:
6999:
7000:
7001:
7002:
7003:
7004:
7005:
7006:
7007:
7008:
7009:
7010:
7011:
7012:
7013:
7014:
7015:
7016:
7017:
7018:
7019:
7020:
7021:
7022:
7023:
7024:
7025:
7026:
7027:
7028:
7029:
7030:
7031:
7032:
7033:
7034:
7035:
7036:
7037:
7038:
7039:
7040:
7041:
7042:
7043:
7044:
7045:
7046:
7047:
7048:
7049:
7050:
7051:
7052:
7053:
7054:
7055:
7056:
7057:
7058:
7059:
7060:
7061:
7062:
7063:
7064:
7065:
7066:
7067:
7068:
7069:
7070:
7071:
7072:
7073:
7074:
7075:
7076:
7077:
7078:
7079:
7080:
7081:
7082:
7083:
7084:
7085:
7086:
7087:
7088:
7089:
7090:
7091:
7092:
7093:
7094:
7095:
7096:
7097:
7098:
7099:
7100:
7101:
7102:
7103:
7104:
7105:
7106:
7107:
7108:
7109:
7110:
7111:
7112:
7113:
7114:
7115:
7116:
7117:
7118:
7119:
7120:
7121:
7122:
7123:
7124:
7125:
7126:
7127:
7128:
7129:
7130:
7131:
7132:
7133:
7134:
7135:
7136:
7137:
7138:
7139:
7140:
7141:
7142:
7143:
7144:
7145:
7146:
7147:
7148:
7149:
7150:
7151:
7152:
7153:
7154:
7155:
7156:
7157:
7158:
7159:
7160:
7161:
7162:
7163:
7164:
7165:
7166:
7167:
7168:
7169:
7170:
7171:
7172:
7173:
7174:
7175:
7176:
7177:
7178:
7179:
7180:
7181:
7182:
7183:
7184:
7185:
7186:
7187:
7188:
7189:
7190:
7191:
7192:
7193:
7194:
7195:
7196:
7197:
7198:
7199:
7200:
7201:
7202:
7203:
7204:
7205:
7206:
7207:
7208:
7209:
7210:
7211:
7212:
7213:
7214:
7215:
7216:
7217:
7218:
7219:
7220:
7221:
7222:
7223:
7224:
7225:
7226:
7227:
7228:
7229:
7230:
7231:
7232:
7233:
7234:
7235:
7236:
7237:
7238:
7239:
7240:
7241:
7242:
7243:
7244:
7245:
7246:
7247:
7248:
7249:
7250:
7251:
7252:
7253:
7254:
7255:
7256:
7257:
7258:
7259:
7260:
7261:
7262:
7263:
7264:
7265:
7266:
7267:
7268:
7269:
7270:
7271:
7272:
7273:
7274:
7275:
7276:
7277:
7278:
7279:
7280:
7281:
7282:
7283:
7284:
7285:
7286:
7287:
7288:
7289:
7290:
7291:
7292:
7293:
7294:
7295:
7296:
7297:
7298:
7299:
7300:
7301:
7302:
7303:
7304:
7305:
7306:
7307:
7308:
7309:
7310:
7311:
7312:
7313:
7314:
7315:
7316:
7317:
7318:
7319:
7320:
7321:
7322:
7323:
7324:
7325:
7326:
7327:
7328:
7329:
7330:
7331:
7332:
7333:
7334:
7335:
7336:
7337:
7338:
7339:
7340:
7341:
7342:
7343:
7344:
7345:
7346:
7347:
7348:
7349:
7350:
7351:
7352:
7353:
7354:
7355:
7356:
7357:
7358:
7359:
7360:
7361:
7362:
7363:
7364:
7365:
7366:
7367:
7368:
7369:
7370:
7371:
7372:
7373:
7374:
7375:
7376:
7377:
7378:
7379:
7380:
7381:
7382:
7383:
7384:
7385:
7386:
7387:
7388:
7389:
7390:
7391:
7392:
7393:
7394:
7395:
7396:
7397:
7398:
7399:
7400:
7401:
7402:
7403:
7404:
7405:
7406:
7407:
7408:
7409:
7410:
7411:
7412:
7413:
7414:
7415:
7416:
7417:
7418:
7419:
7420:
7421:
7422:
7423:
7424:
7425:
7426:
7427:
7428:
7429:
7430:
7431:
7432:
7433:
7434:
7435:
7436:
7437:
7438:
7439:
7440:
7441:
7442:
7443:
7444:
7445:
7446:
7447:
7448:
7449:
7450:
7451:
7452:
7453:
7454:
7455:
7456:
7457:
7458:
7459:
7460:
7461:
7462:
7463:
7464:
7465:
7466:
7467:
7468:
7469:
7470:
7471:
7472:
7473:
7474:
7475:
7476:
7477:
7478:
7479:
7480:
7481:
7482:
7483:
7484:
7485:
7486:
7487:
7488:
7489:
7490:
7491:
7492:
7493:
7494:
7495:
7496:
7497:
7498:
7499:
7500:
7501:
7502:
7503:
7504:
7505:
7506:
7507:
7508:
7509:
7510:
7511:
7512:
7513:
7514:
7515:
7516:
7517:
7518:
7519:
7520:
7521:
7522:
7523:
7524:
7525:
7526:
7527:
7528:
7529:
7530:
7531:
7532:
7533:
7534:
7535:
7536:
7537:
7538:
7539:
7540:
7541:
7542:
7543:
7544:
7545:
7546:
7547:
7548:
7549:
7550:
7551:
7552:
7553:
7554:
7555:
7556:
7557:
7558:
7559:
7560:
7561:
7562:
7563:
7564:
7565:
7566:
7567:
7568:
7569:
7570:
7571:
7572:
7573:
7574:
7575:
7576:
7577:
7578:
7579:
7580:
7581:
7582:
7583:
7584:
7585:
7586:
7587:
7588:
7589:
7590:
7591:
7592:
7593:
7594:
7595:
7596:
7597:
7598:
7599:
7600:
7601:
7602:
7603:
7604:
7605:
7606:
7607:
7608:
7609:
7610:
7611:
7612:
7613:
7614:
7615:
7616:
7617:
7618:
7619:
7620:
7621:
7622:
7623:
7624:
7625:
7626:
7627:
7628:
7629:
7630:
7631:
7632:
7633:
7634:
7635:
7636:
7637:
7638:
7639:
7640:
7641:
7642:
7643:
7644:
7645:
7646:
7647:
7648:
7649:
7650:
7651:
7652:
7653:
7654:
7655:
7656:
7657:
7658:
7659:
7660:
7661:
7662:
7663:
7664:
7665:
7666:
7667:
7668:
7669:
7670:
7671:
7672:
7673:
7674:
7675:
7676:
7677:
7678:
7679:
7680:
7681:
7682:
7683:
7684:
7685:
7686:
7687:
7688:
7689:
7690:
7691:
7692:
7693:
7694:
7695:
7696:
7697:
7698:
7699:
7700:
7701:
7702:
7703:
7704:
7705:
7706:
7707:
7708:
7709:
7710:
7711:
7712:
7713:
7714:
7715:
7716:
7717:
7718:
7719:
7720:
7721:
7722:
7723:
7724:
7725:
7726:
7727:
7728:
7729:
7730:
7731:
7732:
7733:
7734:
7735:
7736:
7737:
7738:
7739:
7740:
7741:
7742:
7743:
7744:
7745:
7746:
7747:
7748:
7749:
7750:
7751:
7752:
7753:
7754:
7755:
7756:
7757:
7758:
7759:
7760:
7761:
7762:
7763:
7764:
7765:
7766:
7767:
7768:
7769:
7770:
7771:
7772:
7773:
7774:
7775:
7776:
7777:
7778:
7779:
7780:
7781:
7782:
7783:
7784:
7785:
7786:
7787:
7788:
7789:
7790:
7791:
7792:
7793:
7794:
7795:
7796:
7797:
7798:
7799:
7800:
7801:
7802:
7803:
7804:
7805:
7806:
7807:
7808:
7809:
7810:
7811:
7812:
7813:
7814:
7815:
7816:
7817:
7818:
7819:
7820:
7821:
7822:
7823:
7824:
7825:
7826:
7827:
7828:
7829:
7830:
7831:
7832:
7833:
7834:
7835:
7836:
7837:
7838:
7839:
7840:
7841:
7842:
7843:
7844:
7845:
7846:
7847:
7848:
7849:
7850:
7851:
7852:
7853:
7854:
7855:
7856:
7857:
7858:
7859:
7860:
7861:
7862:
7863:
7864:
7865:
7866:
7867:
7868:
7869:
7870:
7871:
7872:
7873:
7874:
7875:
7876:
7877:
7878:
7879:
7880:
7881:
7882:
7883:
7884:
7885:
7886:
7887:
7888:
7889:
7890:
7891:
7892:
7893:
7894:
7895:
7896:
7897:
7898:
7899:
7900:
7901:
7902:
7903:
7904:
7905:
7906:
7907:
7908:
7909:
7910:
7911:
7912:
7913:
7914:
7915:
7916:
7917:
7918:
7919:
7920:
7921:
7922:
7923:
7924:
7925:
7926:
7927:
7928:
7929:
7930:
7931:
7932:
7933:
7934:
7935:
7936:
7937:
7938:
7939:
7940:
7941:
7942:
7943:
7944:
7945:
7946:
7947:
7948:
7949:
7950:
7951:
7952:
7953:
7954:
7955:
7956:
7957:
7958:
7959:
7960:
7961:
7962:
7963:
7964:
7965:
7966:
7967:
7968:
7969:
7970:
7971:
7972:
7973:
7974:
7975:
7976:
7977:
7978:
7979:
7980:
7981:
7982:
7983:
7984:
7985:
7986:
7987:
7988:
7989:
7990:
7991:
7992:
7993:
7994:
7995:
7996:
7997:
7998:
7999:
8000:
8001:
8002:
8003:
8004:
8005:
8006:
8007:
8008:
8009:
8010:
8011:
8012:
8013:
8014:
8015:
8016:
8017:
8018:
8019:
8020:
8021:
8022:
8023:
8024:
8025:
8026:
8027:
8028:
8029:
8030:
8031:
8032:
8033:
8034:
8035:
8036:
8037:
8038:
8039:
8040:
8041:
8042:
8043:
8044:
8045:
8046:
8047:
8048:
8049:
8050:
8051:
8052:
8053:
8054:
8055:
8056:
8057:
8058:
8059:
8060:
8061:
8062:
8063:
8064:
8065:
8066:
8067:
8068:
8069:
8070:
8071:
8072:
8073:
8074:
8075:
8076:
8077:
8078:
8079:
8080:
8081:
8082:
8083:
8084:
8085:
8086:
8087:
8088:
8089:
8090:
8091:
8092:
8093:
8094:
8095:
8096:
8097:
8098:
8099:
8100:
8101:
8102:
8103:
8104:
8105:
8106:
8107:
8108:
8109:
8110:
8111:
8112:
8113:
8114:
8115:
8116:
8117:
8118:
8119:
8120:
8121:
8122:
8123:
8124:
8125:
8126:
8127:
8128:
8129:
8130:
8131:
8132:
8133:
8134:
8135:
8136:
8137:
8138:
8139:
8140:
8141:
8142:
8143:
8144:
8145:
8146:
8147:
8148:
8149:
8150:
8151:
8152:
8153:
8154:
8155:
8156:
8157:
8158:
8159:
8160:
8161:
8162:
8163:
8164:
8165:
8166:
8167:
8168:
8169:
8170:
8171:
8172:
8173:
8174:
8175:
8176:
8177:
8178:
8179:
8180:
8181:
8182:
8183:
8184:
8185:
8186:
8187:
8188:
8189:
8190:
8191:
8192:
8193:
8194:
8195:
8196:
8197:
8198:
8199:
8200:
8201:
8202:
8203:
8204:
8205:
8206:
8207:
8208:
8209:
8210:
8211:
8212:
8213:
8214:
8215:
8216:
8217:
8218:
8219:
8220:
8221:
8222:
8223:
8224:
8225:
8226:
8227:
8228:
8229:
8230:
8231:
8232:
8233:
8234:
8235:
8236:
8237:
8238:
8239:
8240:
8241:
8242:
8243:
8244:
8245:
8246:
8247:
8248:
8249:
8250:
8251:
8252:
8253:
8254:
8255:
8256:
8257:
8258:
8259:
8260:
8261:
8262:
8263:
8264:
8265:
8266:
8267:
8268:
8269:
8270:
8271:
8272:
8273:
8274:
8275:
8276:
8277:
8278:
8279:
8280:
8281:
8282:
8283:
8284:
8285:
8286:
8287:
8288:
8289:
8290:
8291:
8292:
8293:
8294:
8295:
8296:
8297:
8298:
8299:
8300:
8301:
8302:
8303:
8304:
8305:
8306:
8307:
8308:
8309:
8310:
8311:
8312:
8313:
8314:
8315:
8316:
8317:
8318:
8319:
8320:
8321:
8322:
8323:
8324:
8325:
8326:
8327:
8328:
8329:
8330:
8331:
8332:
8333:
8334:
8335:
8336:
8337:
8338:
8339:
8340:
8341:
8342:
8343:
8344:
8345:
8346:
8347:
8348:
8349:
8350:
8351:
8352:
8353:
8354:
8355:
8356:
8357:
8358:
8359:
8360:
8361:
8362:
8363:
8364:
8365:
8366:
8367:
8368:
8369:
8370:
8371:
8372:
8373:
8374:
8375:
8376:
8377:
8378:
8379:
8380:
8381:
8382:
8383:
8384:
8385:
8386:
8387:
8388:
8389:
8390:
8391:
8392:
8393:
8394:
8395:
8396:
8397:
8398:
8399:
8400:
8401:
8402:
8403:
8404:
8405:
8406:
8407:
8408:
8409:
8410:
8411:
8412:
8413:
8414:
8415:
8416:
8417:
8418:
8419:
8420:
8421:
8422:
8423:
8424:
8425:
8426:
8427:
8428:
8429:
8430:
8431:
8432:
8433:
8434:
8435:
8436:
8437:
8438:
8439:
8440:
8441:
8442:
8443:
8444:
8445:
8446:
8447:
8448:
8449:
8450:
8451:
8452:
8453:
8454:
8455:
8456:
8457:
8458:
8459:
8460:
8461:
8462:
8463:
8464:
8465:
8466:
8467:
8468:
8469:
8470:
8471:
8472:
8473:
8474:
8475:
8476:
8477:
8478:
8479:
8480:
8481:
8482:
8483:
8484:
8485:
8486:
8487:
8488:
8489:
8490:
8491:
8492:
8493:
8494:
8495:
8496:
8497:
8498:
8499:
8500:
8501:
8502:
8503:
8504:
8505:
8506:
8507:
8508:
8509:
8510:
8511:
8512:
8513:
8514:
8515:
8516:
8517:
8518:
8519:
8520:
8521:
8522:
8523:
8524:
8525:
8526:
8527:
8528:
8529:
8530:
8531:
8532:
8533:
8534:
8535:
8536:
8537:
8538:
8539:
8540:
8541:
8542:
8543:
8544:
8545:
8546:
8547:
8548:
8549:
8550:
8551:
8552:
8553:
8554:
8555:
8556:
8557:
8558:
8559:
8560:
8561:
8562:
8563:
8564:
8565:
8566:
8567:
8568:
8569:
8570:
8571:
8572:
8573:
8574:
8575:
8576:
8577:
8578:
8579:
8580:
8581:
8582:
8583:
8584:
8585:
8586:
8587:
8588:
8589:
8590:
8591:
8592:
8593:
8594:
8595:
8596:
8597:
8598:
8599:
8600:
8601:
8602:
8603:
8604:
8605:
8606:
8607:
8608:
8609:
8610:
8611:
8612:
8613:
8614:
8615:
8616:
8617:
8618:
8619:
8620:
8621:
8622:
8623:
8624:
8625:
8626:
8627:
8628:
8629:
8630:
8631:
8632:
8633:
8634:
8635:
8636:
8637:
8638:
8639:
8640:
8641:
8642:
8643:
8644:
8645:
8646:
8647:
8648:
8649:
8650:
8651:
8652:
8653:
8654:
8655:
8656:
8657:
8658:
8659:
8660:
8661:
8662:
8663:
8664:
8665:
8666:
8667:
8668:
8669:
8670:
8671:
8672:
8673:
8674:
8675:
8676:
8677:
8678:
8679:
8680:
8681:
8682:
8683:
8684:
8685:
8686:
8687:
8688:
8689:
8690:
8691:
8692:
8693:
8694:
8695:
8696:
8697:
8698:
8699:
8700:
8701:
8702:
8703:
8704:
8705:
8706:
8707:
8708:
8709:
8710:
8711:
8712:
8713:
8714:
8715:
8716:
8717:
8718:
8719:
8720:
8721:
8722:
8723:
8724:
8725:
8726:
8727:
8728:
8729:
8730:
8731:
8732:
8733:
8734:
8735:
8736:
8737:
8738:
8739:
8740:
8741:
8742:
8743:
8744:
8745:
8746:
8747:
8748:
8749:
8750:
8751:
8752:
8753:
8754:
8755:
8756:
8757:
8758:
8759:
8760:
8761:
8762:
8763:
8764:
8765:
8766:
8767:
8768:
8769:
8770:
8771:
8772:
8773:
8774:
8775:
8776:
8777:
8778:
8779:
8780:
8781:
8782:
8783:
8784:
8785:
8786:
8787:
8788:
8789:
8790:
8791:
8792:
8793:
8794:
8795:
8796:
8797:
8798:
8799:
8800:
8801:
8802:
8803:
8804:
8805:
8806:
8807:
8808:
8809:
8810:
8811:
8812:
8813:
8814:
8815:
8816:
8817:
8818:
8819:
8820:
8821:
8822:
8823:
8824:
8825:
8826:
8827:
8828:
8829:
8830:
8831:
8832:
8833:
8834:
8835:
8836:
8837:
8838:
8839:
8840:
8841:
8842:
8843:
8844:
8845:
8846:
8847:
8848:
8849:
8850:
8851:
8852:
8853:
8854:
8855:
8856:
8857:
8858:
8859:
8860:
8861:
8862:
8863:
8864:
8865:
8866:
8867:
8868:
8869:
8870:
8871:
8872:
8873:
8874:
8875:
8876:
8877:
8878:
8879:
8880:
8881:
8882:
8883:
8884:
8885:
8886:
8887:
8888:
8889:
8890:
8891:
8892:
8893:
8894:
8895:
8896:
8897:
8898:
8899:
8900:
8901:
8902:
8903:
8904:
8905:
8906:
8907:
8908:
8909:
8910:
8911:
8912:
8913:
8914:
8915:
8916:
8917:
8918:
8919:
8920:
8921:
8922:
8923:
8924:
8925:
8926:
8927:
8928:
8929:
8930:
8931:
8932:
8933:
8934:
8935:
8936:
8937:
8938:
8939:
8940:
8941:
8942:
8943:
8944:
8945:
8946:
8947:
8948:
8949:
8950:
8951:
8952:
8953:
8954:
8955:
8956:
8957:
8958:
8959:
8960:
8961:
8962:
8963:
8964:
8965:
8966:
8967:
8968:
8969:
8970:
8971:
8972:
8973:
8974:
8975:
8976:
8977:
8978:
8979:
8980:
8981:
8982:
8983:
8984:
8985:
8986:
8987:
8988:
8989:
8990:
8991:
8992:
8993:
8994:
8995:
8996:
8997:
8998:
8999:
9000:
9001:
9002:
9003:
9004:
9005:
9006:
9007:
9008:
9009:
9010:
9011:
9012:
9013:
9014:
9015:
9016:
9017:
9018:
9019:
9020:
9021:
9022:
9023:
9024:
9025:
9026:
9027:
9028:
9029:
9030:
9031:
9032:
9033:
9034:
9035:
9036:
9037:
9038:
9039:
9040:
9041:
9042:
9043:
9044:
9045:
9046:
9047:
9048:
9049:
9050:
9051:
9052:
9053:
9054:
9055:
9056:
9057:
9058:
9059:
9060:
9061:
9062:
9063:
9064:
9065:
9066:
9067:
9068:
9069:
9070:
9071:
9072:
9073:
9074:
9075:
9076:
9077:
9078:
9079:
9080:
9081:
9082:
9083:
9084:
9085:
9086:
9087:
9088:
9089:
9090:
9091:
9092:
9093:
9094:
9095:
9096:
9097:
9098:
9099:
9100:
9101:
9102:
9103:
9104:
9105:
9106:
9107:
9108:
9109:
9110:
9111:
9112:
9113:
9114:
9115:
9116:
9117:
9118:
9119:
9120:
9121:
9122:
9123:
9124:
9125:
9126:
9127:
9128:
9129:
9130:
9131:
9132:
9133:
9134:
9135:
9136:
9137:
9138:
9139:
9140:
9141:
9142:
9143:
9144:
9145:
9146:
9147:
9148:
9149:
9150:
9151:
9152:
9153:
9154:
9155:
9156:
9157:
9158:
9159:
9160:
9161:
9162:
9163:
9164:
9165:
9166:
9167:
9168:
9169:
9170:
9171:
9172:
9173:
9174:
9175:
9176:
9177:
9178:
9179:
9180:
9181:
9182:
9183:
9184:
9185:
9186:
9187:
9188:
9189:
9190:
9191:
9192:
9193:
9194:
9195:
9196:
9197:
9198:
9199:
9200:
9201:
9202:
9203:
9204:
9205:
9206:
9207:
9208:
9209:
9210:
9211:
9212:
9213:
9214:
9215:
9216:
9217:
9218:
9219:
9220:
9221:
9222:
9223:
9224:
9225:
9226:
9227:
9228:
9229:
9230:
9231:
9232:
9233:
9234:
9235:
9236:
9237:
9238:
9239:
9240:
9241:
9242:
9243:
9244:
9245:
9246:
9247:
9248:
9249:
9250:
9251:
9252:
9253:
9254:
9255:
9256:
9257:
9258:
9259:
9260:
9261:
9262:
9263:
9264:
9265:
9266:
9267:
9268:
9269:
9270:
9271:
9272:
9273:
9274:
9275:
9276:
9277:
9278:
9279:
9280:
9281:
9282:
9283:
9284:
9285:
9286:
9287:
9288:
9289:
9290:
9291:
9292:
9293:
9294:
9295:
9296:
9297:
9298:
9299:
9300:
9301:
9302:
9303:
9304:
9305:
9306:
9307:
9308:
9309:
9310:
9311:
9312:
9313:
9314:
9315:
9316:
9317:
9318:
9319:
9320:
9321:
9322:
9323:
9324:
9325:
9326:
9327:
9328:
9329:
9330:
9331:
9332:
9333:
9334:
9335:
9336:
9337:
9338:
9339:
9340:
9341:
9342:
9343:
9344:
9345:
9346:
9347:
9348:
9349:
9350:
9351:
9352:
9353:
9354:
9355:
9356:
9357:
9358:
9359:
9360:
9361:
9362:
9363:
9364:
9365:
9366:
9367:
9368:
9369:
9370:
9371:
9372:
9373:
9374:
9375:
9376:
9377:
9378:
9379:
9380:
9381:
9382:
9383:
9384:
9385:
9386:
9387:
9388:
9389:
9390:
9391:
9392:
9393:
9394:
9395:
9396:
9397:
9398:
9399:
9400:
9401:
9402:
9403:
9404:
9405:
9406:
9407:
9408:
9409:
9410:
9411:
9412:
9413:
9414:
9415:
9416:
9417:
9418:
9419:
9420:
9421:
9422:
9423:
9424:
9425:
9426:
9427:
9428:
9429:
9430:
9431:
9432:
9433:
9434:
9435:
9436:
9437:
9438:
9439:
9440:
9441:
9442:
9443:
9444:
9445:
9446:
9447:
9448:
9449:
9450:
9451:
9452:
9453:
9454:
9455:
9456:
9457:
9458:
9459:
9460:
9461:
9462:
9463:
9464:
9465:
9466:
9467:
9468:
9469:
9470:
9471:
9472:
9473:
9474:
9475:
9476:
9477:
9478:
9479:
9480:
9481:
9482:
9483:
9484:
9485:
9486:
9487:
9488:
9489:
9490:
9491:
9492:
9493:
9494:
9495:
9496:
9497:
9498:
9499:
9500:
9501:
9502:
9503:
9504:
9505:
9506:
9507:
9508:
9509:
9510:
9511:
9512:
9513:
9514:
9515:
9516:
9517:
9518:
9519:
9520:
9521:
9522:
9523:
9524:
9525:
9526:
9527:
9528:
9529:
9530:
9531:
9532:
9533:
9534:
9535:
9536:
9537:
9538:
9539:
9540:
9541:
9542:
9543:
9544:
9545:
9546:
9547:
9548:
9549:
9550:
9551:
9552:
9553:
9554:
9555:
9556:
9557:
9558:
9559:
9560:
9561:
9562:
9563:
9564:
9565:
9566:
9567:
9568:
9569:
9570:
9571:
9572:
9573:
9574:
9575:
9576:
9577:
9578:
9579:
9580:
9581:
9582:
9583:
9584:
9585:
9586:
9587:
9588:
9589:
9590:
9591:
9592:
9593:
9594:
9595:
9596:
9597:
9598:
9599:
9600:
9601:
9602:
9603:
9604:
9605:
9606:
9607:
9608:
9609:
9610:
9611:
9612:
9613:
9614:
9615:
9616:
9617:
9618:
9619:
9620:
9621:
9622:
9623:
9624:
9625:
9626:
9627:
9628:
9629:
9630:
9631:
9632:
9633:
9634:
9635:
9636:
9637:
9638:
9639:
9640:
9641:
9642:
9643:
9644:
9645:
9646:
9647:
9648:
9649:
9650:
9651:
9652:
9653:
9654:
9655:
9656:
9657:
9658:
9659:
9660:
9661:
9662:
9663:
9664:
9665:
9666:
9667:
9668:
9669:
9670:
9671:
9672:
9673:
9674:
9675:
9676:
9677:
9678:
9679:
9680:
9681:
9682:
9683:
9684:
9685:
9686:
9687:
9688:
9689:
9690:
9691:
9692:
9693:
9694:
9695:
9696:
9697:
9698:
9699:
9700:
9701:
9702:
9703:
9704:
9705:
9706:
9707:
9708:
9709:
9710:
9711:
9712:
9713:
9714:
9715:
9716:
9717:
9718:
9719:
9720:
9721:
9722:
9723:
9724:
9725:
9726:
9727:
9728:
9729:
9730:
9731:
9732:
9733:
9734:
9735:
9736:
9737:
9738:
9739:
9740:
9741:
9742:
9743:
9744:
9745:
9746:
9747:
9748:
9749:
9750:
9751:
9752:
9753:
9754:
9755:
9756:
9757:
9758:
9759:
9760:
9761:
9762:
9763:
9764:
9765:
9766:
9767:
9768:
9769:
9770:
9771:
9772:
9773:
9774:
9775:
9776:
9777:
9778:
9779:
9780:
9781:
9782:
9783:
9784:
9785:
9786:
9787:
9788:
9789:
9790:
9791:
9792:
9793:
9794:
9795:
9796:
9797:
9798:
9799:
9800:
9801:
9802:
9803:
9804:
9805:
9806:
9807:
9808:
9809:
9810:
9811:
9812:
9813:
9814:
9815:
9816:
9817:
9818:
9819:
9820:
9821:
9822:
9823:
9824:
9825:
9826:
9827:
9828:
9829:
9830:
9831:
9832:
9833:
9834:
9835:
9836:
9837:
9838:
9839:
9840:
9841:
9842:
9843:
9844:
9845:
9846:
9847:
9848:
9849:
9850:
9851:
9852:
9853:
9854:
9855:
9856:
9857:
9858:
9859:
9860:
9861:
9862:
9863:
9864:
9865:
9866:
9867:
9868:
9869:
9870:
9871:
9872:
9873:
9874:
9875:
9876:
9877:
9878:
9879:
9880:
9881:
9882:
9883:
9884:
9885:
9886:
9887:
9888:
9889:
9890:
9891:
9892:
9893:
9894:
9895:
9896:
9897:
9898:
9899:
9900:
9901:
9902:
9903:
9904:
9905:
9906:
9907:
9908:
9909:
9910:
9911:
9912:
9913:
9914:
9915:
9916:
9917:
9918:
9919:
9920:
9921:
9922:
9923:
9924:
9925:
9926:
9927:
9928:
9929:
9930:
9931:
9932:
9933:
9934:
9935:
9936:
9937:
9938:
9939:
9940:
9941:
9942:
9943:
9944:
9945:
9946:
9947:
9948:
9949:
9950:
9951:
9952:
9953:
9954:
9955:
9956:
9957:
9958:
9959:
9960:
9961:
9962:
9963:
9964:
9965:
9966:
9967:
9968:
9969:
9970:
9971:
9972:
9973:
9974:
9975:
9976:
9977:
9978:
9979:
9980:
9981:
9982:
9983:
9984:
9985:
9986:
9987:
9988:
9989:
9990:
9991:
9992:
9993:
9994:
9995:
9996:
9997:
9998:
9999:
10000:
10001:
10002:
10003:
10004:
10005:
10006:
10007:
10008:
10009:
10010:
10011:
10012:
10013:
10014:
10015:
10016:
10017:
10018:
10019:
10020:
10021:
10022:
10023:
10024:
10025:
10026:
10027:
10028:
10029:
10030:
10031:
10032:
10033:
10034:
10035:
10036:
10037:
10038:
10039:
10040:
10041:
10042:
10043:
10044:
10045:
10046:
10047:
10048:
10049:
10050:
10051:
10052:
10053:
10054:
10055:
10056:
10057:
10058:
10059:
10060:
10061:
10062:
10063:
10064:
10065:
10066:
10067:
10068:
10069:
10070:
10071:
10072:
10073:
10074:
10075:
10076:
10077:
10078:
10079:
10080:
10081:
10082:
10083:
10084:
10085:
10086:
10087:
10088:
10089:
10090:
10091:
10092:
10093:
10094:
10095:
10096:
10097:
10098:
10099:
10100:
10101:
10102:
10103:
10104:
10105:
10106:
10107:
10108:
10109:
10110:
10111:
10112:
10113:
10114:
10115:
10116:
10117:
10118:
10119:
10120:
10121:
10122:
10123:
10124:
10125:
10126:
10127:
10128:
10129:
10130:
10131:
10132:
10133:
10134:
10135:
10136:
10137:
10138:
10139:
10140:
10141:
10142:
10143:
10144:
10145:
10146:
10147:
10148:
10149:
10150:
10151:
10152:
10153:
10154:
10155:
10156:
10157:
10158:
10159:
10160:
10161:
10162:
10163:
10164:
10165:
10166:
10167:
10168:
10169:
10170:
10171:
10172:
10173:
10174:
10175:
10176:
10177:
10178:
10179:
10180:
10181:
10182:
10183:
10184:
10185:
10186:
10187:
10188:
10189:
10190:
10191:
10192:
10193:
10194:
10195:
10196:
10197:
10198:
10199:
10200:
10201:
10202:
10203:
10204:
10205:
10206:
10207:
10208:
10209:
10210:
10211:
10212:
10213:
10214:
10215:
10216:
10217:
10218:
10219:
10220:
10221:
10222:
10223:
10224:
10225:
10226:
10227:
10228:
10229:
10230:
10231:
10232:
10233:
10234:
10235:
10236:
10237:
10238:
10239:
10240:
10241:
10242:
10243:
10244:
10245:
10246:
10247:
10248:
10249:
10250:
10251:
10252:
10253:
10254:
10255:
10256:
10257:
10258:
10259:
10260:
10261:
10262:
10263:
10264:
10265:
10266:
10267:
10268:
10269:
10270:
10271:
10272:
10273:
10274:
10275:
10276:
10277:
10278:
10279:
10280:
10281:
10282:
10283:
10284:
10285:
10286:
10287:
10288:
10289:
10290:
10291:
10292:
10293:
10294:
10295:
10296:
10297:
10298:
10299:
10300:
10301:
10302:
10303:
10304:
10305:
10306:
10307:
10308:
10309:
10310:
10311:
10312:
10313:
10314:
10315:
10316:
10317:
10318:
10319:
10320:
10321:
10322:
10323:
10324:
10325:
10326:
10327:
10328:
10329:
10330:
10331:
10332:
10333:
10334:
10335:
10336:
10337:
10338:
10339:
10340:
10341:
10342:
10343:
10344:
10345:
10346:
10347:
10348:
10349:
10350:
10351:
10352:
10353:
10354:
10355:
10356:
10357:
10358:
10359:
10360:
10361:
10362:
10363:
10364:
10365:
10366:
10367:
10368:
10369:
10370:
10371:
10372:
10373:
10374:
10375:
10376:
10377:
10378:
10379:
10380:
10381:
10382:
10383:
10384:
10385:
10386:
10387:
10388:
10389:
10390:
10391:
10392:
10393:
10394:
10395:
10396:
10397:
10398:
10399:
10400:
10401:
10402:
10403:
10404:
10405:
10406:
10407:
10408:
10409:
10410:
10411:
10412:

Select allOpen in new window

 

by: mplungjanPosted on 2009-08-11 at 07:47:28ID: 25069686

Oops.

You are correct. I looked in my mailer and saw this:

<?php
require_once('recaptchalib.php');
 
// Get a key from http://recaptcha.net/api/getkey
// my site
$publickey = "PUBKEY";
$privatekey = "PRIV_KEY";
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
 
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
  if ($resp->is_valid) {
 
// HERE IS MY ORIGINAL FOMMAIL CODE 
//----------------
// ending with this redirect
 
    if ($landing_page != ""){
      header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
    } else {
      header("Location: http://".$_SERVER["HTTP_HOST"]."/");
    }
  }
  else {
    # set the error code so that we can display it
    $error = $resp->error;
    $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=".$error;
    header("Location: ".$loc);
  }
}
else {
    $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=nocaptcha";
    header("Location: ".$loc);
}
 
?>
                                              
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:

Select allOpen in new window

 

by: sobeservices2Posted on 2009-08-11 at 08:23:04ID: 25070108

What should I do?

 

by: mplungjanPosted on 2009-08-11 at 09:48:23ID: 25070971

If you wish to use the hugely complex script, you (or someone else) needs to figure out how to wrap that script in the recaptcha.

 

by: sobeservices2Posted on 2009-08-11 at 09:53:23ID: 25071016

I could use something simple ... I am not bond by my current formmail.. What would you recommend? I have no problem changing something. I just need it so that when the form gets filled out it is sent to me in an email.

 

by: mplungjanPosted on 2009-08-11 at 11:35:28ID: 25071935

I can send you what I have tomorrow.

 

by: sobeservices2Posted on 2009-08-11 at 12:03:50ID: 25072229

OK Cool ..

Thanks. At this point i'am just a little confused what to do next ...

 

by: mplungjanPosted on 2009-08-12 at 00:20:50ID: 25076330

Ah - sorry for not googling tectite captcha or textite recaptcha

You want to follow instructions here:

http://www.tectite.com/fmhowto/captchacreator.php

 

by: sobeservices2Posted on 2009-08-12 at 06:50:43ID: 25078676

Thanks I saw that. Its a captcha thing but not the recaptcha.net one. Its some other kind. I like to stick to recaptcha one. If it means changing and using a different form mail script besides the tectite one that I will change. But to change to which one I don't know

 

by: mplungjanPosted on 2009-08-12 at 07:06:43ID: 25078828

Ok...

I will have to have a deeper look at the tectite one you posted then

However I guess it was generated so if I modify it and you generate it again, the modifications will be lost.

unless your ISP has a formmail you want to use, perhaps we can consider this one:

http://nms-cgi.sourceforge.net/scripts.shtml

 

by: sobeservices2Posted on 2009-08-12 at 07:09:36ID: 25078868

yep I saw that not to sure about the configure but I will look at that closely.

Will be waiting for your reply

oh by the way I have my own dedicated server. ISP isn't an issue LOL

 

by: mplungjanPosted on 2009-08-12 at 23:37:10ID: 25085820

Ok, try this in combination with the javascript I gave you
I cannot test it for obvious reasons.

I have inserted the following in the snippet - change the bold stuff to your pages
.
.
.
$publickey = "PUBKEY";
$privatekey = "PRIV_KEY";
.
.
.
.
   # set the error code so that we can display it
   $error = $resp->error;
   $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=".$error;
   header("Location: ".$loc);
 }
}
else {
   $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=nocaptcha";
   header("Location: ".$loc);
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="en-us">
	<head>
		<title>Contact The Broward County Police Benevolent Association</title>
		<link href="styles.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-2389628-7");
pageTracker._initData();
pageTracker._trackPageview();
</script>
<!-- This following bit of code catches IE up to the rest of the browsers in terms of handling transparent graphics. -->
<!--[If IE]>
	<style>        #nav { 
        	  margin: 0 0 0 7px; 
              }
		h1 {
			margin: 0 110px 50px 0;
		}
	</style>
<![EndIf]-->
<style type="text/css">
<!--
.style11 {font-size: 10px}
.style5 {font-size: 12px; font-family: Arial, Helvetica, sans-serif;}
.style6 {font-family: Arial, Helvetica, sans-serif}
.style7 {font-size: 12px}
.style8 {font-weight: bold}
-->
</style>
</head>
	<body>
    
 
<!-- Starting here is where I'm building the template. -->
 
<!-- This div tag has the whole page in it, and with CSS we center this div. -->
 
		<div id="page">
 
<!-- NOTE: You might need to change the path of the images (and/or rename the images) when you put this on your servers -->
 
			<img src="images/bcpba-image-top.png" alt="The Broward County Police Benevolent Association" width="780" height="289" />
 
<!-- This is the start of the nav bar -->
 
			<div id="nav">
 
				<img src="images/bcpba-nav-curve.png" alt="navbar swoosh" width="160" height="35" />
 
<!-- This is the start of the nav bar links section -->
 
			  <div id="navlinks">                	<p>
              
                        <a href="index.html"><img src="images/home-button.png" alt="Home" width="160" height="25" /></a>
                	    <a href="about.html"><img src="images/bcpba-nav-01.png" alt="About the PBA" width="160" height="25" /></a>
                	    <a href="membership.html"><img src="images/bcpba-nav-02.png" alt="Membership" width="160" height="26" /></a>
                	    <a href="executive_board_staff.html"><img src="images/bcpba-nav-03.png" alt="Executive Board and Staff" width="160" height="26" /></a>
                	    <a href="board_of_directors.html"><img src="images/bcpba-nav-04.png" alt="Board of Directors" width="160" height="24" /></a>
                	    <a href="legal_representation.html"><img src="images/bcpba-nav-05.png" alt="Legal Representation" width="160" height="26" /></a>
                	    <a href="hope_fund.html"><img src="images/bcpba-nav-06.png" alt="The Hope Fund" width="160" height="25" /></a>
                        <a href="hope_fund.html"><img src="images/scholarship_program_button.png" alt="Scholarship Program" width="160" height="25" /></a>				  
                	    <a href="legislative.html"><img src="images/bcpba-nav-07.png" alt="Legislative" width="160" height="23" /></a>
                	    <a href="pba_hall.html"><img src="images/bcpba-nav-08.png" alt="PBA Hall" width="160" height="25" /></a>
                	    <a href="contracts.html"><img src="images/contracts_button.png" alt="Contracts" width="160" height="25" /></a>
                	    <a href="news.html"><img src="images/bcpba-nav-10.png" alt="News Alerts" width="160" height="25" /></a>
                	    <a href="pba_plate.html"><img src="images/bcpba-nav-11.png" alt="PBA License Plate" width="160" height="25" /></a>				 
                	    <a href="merchandise.html"><img src="images/bcpba-nav-12.png" alt="Merchandise" width="160" height="25" /></a>
                	    <a href="members_only_home.php"><img src="images/bcpba-nav-13.png" alt="Members Only Page" width="160" height="25" /></a>
                	    <a href="newsletter.html"><img src="images/bcpba-nav-14.png" alt="Newsletter" width="160" height="25" /></a>
                	    <a href="/blog2/blog2/"><img src="images/bcpba-nav-15.png" alt="President's Blog" width="160" height="25" /></a>
                	    <a href="contact.html"><img src="images/bcpba-nav-16.png" alt="Contact Us Page" width="160" height="26" /></a>                    
                	    <a href="police_memorial.html"><img src="images/bcpba-nav-17.png" alt="Police Memorial" width="160" height="24" /></a>				
                	    <a href="affiliation.html"><img src="images/affiliations_button.png" alt="Affiliation" width="160" height="25" /></a>                	    
                        <a href="links.html"><img src="images/links_button.png" alt="Links" width="160" height="25" /></a>
                        <a href="events.html"><img src="images/events_button.png" alt"Events" width="160" hight="25"/></a><a href="">
                        <br />
                        <br />
                        <img src="images/syndicated-feed-icon.gif" alt="" width="16" height="16" /></a><a href="pba_feed.xml">PBA RSS FEED</a>
                        <br />
               	</p>
                    <p><!-- Start of Site Search Pro code --><style type="text/css">.sp2_field {border:1px solid #999999; background-color:#ffffff; font-family:Arial; font-style:normal; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_btn {font-family:Arial; font-style:normal; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_i_select {background-color:#ffffff; font-family:Arial; font-style:normal; color:#000000; font-size:12px; font-weight:normal; 
}a.sp2_advanced:link,a.sp2_advanced:active,a.sp2_advanced:visited {font-family:Arial; font-style:normal; text-decoration:none; color:#7777cc; font-size:11px; font-weight:normal; 
}a.sp2_advanced:hover {font-family:Arial; font-style:normal; text-decoration:underline; color:#7777cc; font-size:11px; font-weight:normal; 
}.sp2_info {font-family:Arial; font-style:normal; text-decoration:none; color:#000000; font-size:13px; font-weight:bold; 
}a.sp2_title:link,a.sp2_title:active,a.sp2_title:visited {font-family:Arial; font-style:normal; text-decoration:none; color:#7777cc; font-size:13px; font-weight:bold; 
}a.sp2_title:hover {font-family:Arial; font-style:normal; text-decoration:underline; color:#7777cc; font-size:13px; font-weight:bold; 
}.sp2_result {font-family:Arial; font-style:normal; text-decoration:none; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_select {font-family:Arial; font-style:normal; text-decoration:none; color:#990000; font-size:12px; font-weight:bold; 
}.sp2_address {font-family:Arial; font-style:normal; text-decoration:none; color:#008000; font-size:12px; font-weight:normal; 
}.sp2_page {font-family:Arial; font-style:normal; text-decoration:none; color:#000000; font-size:12px; font-weight:normal; 
}a.sp2_page:link,a.sp2_page:active,a.sp2_page:visited {font-family:Arial; font-style:normal; text-decoration:underline; color:#000000; font-size:12px; font-weight:normal; 
}a.sp2_page:hover {font-family:Arial; font-style:normal; text-decoration:underline; color:#000000; font-size:12px; font-weight:normal; 
}.sp2_nowpage {font-family:Arial; font-style:normal; text-decoration:none; color:#a90a08; font-size:12px; font-weight:bold; 
}</style>
<form action="http://bcpba.org/searchpro/index.php" method="get" enctype="application/x-www-form-urlencoded" name="qs" id="qs">
<br />
&nbsp;&nbsp;&nbsp;Search Site<br />
&nbsp;&nbsp;&nbsp;<input class="sp2_field" name="q" type="text" id="q" value="" maxlength="255" size="15"> 
    <br />
&nbsp;&nbsp;&nbsp;<input class="sp2_btn" name="search" type="submit" id="search" value="Search">
        <br />
&nbsp;&nbsp;&nbsp;<a class="sp2_advanced" href="http://bcpba.org/searchpro/advanced_search.php?g=0">Advanced search</a>
</form>
<!-- End of Site Search Pro code -->  </p>
			  </div>
 
		  </div>
 
            <p>
  <!-- This is the end of the navigation bar area -->
            </p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
          <p>
              
              
<!-- This is the start of the body side of things -->
<?php
// --------------------------- INSERTION OF RECAPTCHA PART 1
 
require_once('recaptchalib.php');
 
// Get a key from http://recaptcha.net/api/getkey
// my site
$publickey = "PUBKEY";
$privatekey = "PRIV_KEY";
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
// --------------------------- END OF INSERTION OF RECAPTCHA PART 1
 
 
 
$FM_VERS = "8.05";      // script version
 
/* ex:set ts=4 sw=4 et:
 * FormMail PHP script from Tectite.com.  This script requires PHP 4 or later.
 * Copyright (c) 2001-2008 Root Software and Open Concepts Pty Ltd
 * (ABN 93 003 733 499), Melbourne, Australia.
 * This script is free for all use as described in the "Copying and Use" and
 * "Warranty and Disclaimer" sections below.
 *
 * Visit us at http://www.tectite.com/ for updates and more information.
 *
 *** If you use Tectite FormMail, please support its development and other
 *** freeware products by putting the following link on your website:
 ***  Visit www.tectite.com for free <a href="http://www.tectite.com/">html form processor</a>.
 *
 * Author: Russell Robinson, 2nd October 2001
 * Last Modified: RR 14:07 Wed 15 August 2007
 * QVCS Version: $Revision: 1.4 $
 *
 * Read This First
 * ~~~~~~~~~~~~~~~
 *  This script is very well documented and quite large!  It looks daunting,
 *  but really isn't.
 *  If you have experience with PHP or other scripting languages,
 *  here's what you *need* to read:
 *      - Configuration (TARGET_EMAIL & DEF_ALERT)
 *      - Creating Forms
 *  That's it!  (Alternatively, just read the Quick Start and/or
 *  Quicker Start section below).
 *  Full configuration documentation is here:
 *      http://www.tectite.com/fmdoc/index.php
 *
 * Purpose:
 * ~~~~~~~~
 *  To accept information from an HTML form via HTTP and mail it to recipients.
 *
 * What does this PHP script do?
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  On your web site, you may have one or more HTML forms that accept
 *  information from people visiting your website.  Your aim is for your
 *  website to email that information to you and/or add it to a database.
 *  FormMail performs those functions.
 *
 * Quick Start
 * ~~~~~~~~~~~
 *  1. Edit this file and set TARGET_EMAIL for your requirements (near
 *      line 235 in this file - replace "yourhost\.com" with your mail server's
 *      name).  We also strongly recommend you set DEF_ALERT (the next
 *      configuration below TARGET_EMAIL).
 *  2. Install this file as formmail.php (or other name ending in .php)
 *     on your web server.
 *  3. Create an HTML form and:
 *      - specify a hidden field called "recipients" with the email address
 *        of the person to receive the form's results.
 *      - in the your form tag set the action attribute to
 *        the formmail.php you uploaded to your web server
 *
 *  Once you have FormMail working, you may be interested in some advanced
 *  usage and features.  We have HOW-TO guides at www.tectite.com which
 *  describe many of the advanced processing you can do with FormMail.
 *      http://www.tectite.com/fmhowto/guides.php
 *
 * Quicker Start
 * ~~~~~~~~~~~~~
 *  Use the FormMail Configuration Wizard here:
 *      http://www.tectite.com/wizards/fmconf.php
 *  By answering a few questions you'll get a configured FormMail and
 *  a sample HTML form ready to upload and use on your server.
 *
 * Features
 * ~~~~~~~~
 *  For a list of features go to: http://www.tectite.com/formmailpage.php
 *
 * Security
 * ~~~~~~~~
 *  Security is the primary concern in accepting data from your website
 *  visitors.
 *  Tectite FormMail has several security features designed into it.  Note,
 *  however, it requires configuration for your particular web site.
 *
 * Configuration
 * ~~~~~~~~~~~~~
 *  To configure this script, go to the section titled "CONFIGURATION"
 *  (after reading the legal stuff below).
 *
 *  There is only one mandatory setting: TARGET_EMAIL
 *  and one strongly recommended setting: DEF_ALERT
 *
 *  Full configuration information is available here:
 *      http://www.tectite.com/fmdoc/index.php
 *
 * Creating Forms
 * ~~~~~~~~~~~~~~
 *  Go to this URL to learn how to write HTML forms for use with
 *  Tectite FormMail: http://www.tectite.com/fmdoc/creating_forms.php
 *
 * Copying and Use
 * ~~~~~~~~~~~~~~~
 *  Tectite FormMail is provided free of charge and may be freely distributed
 *  and used provided that you:
 *      1. keep this header, including copyright and comments,
 *         in place and unmodified; and,
 *      2. do not charge a fee for distributing it, without an agreement
 *         in writing with Root Software allowing you to do so; and,
 *      3. if you modify FormMail before distributing it, you clearly
 *         identify:
 *              a) who you are
 *              b) how to contact you
 *              c) what changes you have made
 *              d) why you have made those changes.
 *
 * Warranty and Disclaimer
 * ~~~~~~~~~~~~~~~~~~~~~~~
 *  Tectite FormMail is provided free-of-charge and with ABSOLUTELY NO WARRANTY.
 *  It has not been verified for use in critical applications, including,
 *  but not limited to, medicine, defense, aircraft, space exploration,
 *  or any other potentially dangerous activity.
 *
 *  By using Tectite FormMail you agree to indemnify Root Software and
 *  Open Concepts Pty Ltd, their agents, employees, directors and
 *  associated companies and businesses from any liability whatsoever.
 *
 * We still care
 * ~~~~~~~~~~~~~
 *  If you find a bug or fault in FormMail, please report it to us.
 *  We will respond to your report and make endeavours to rectify any
 *  faults you've detected as soon as possible.
 *
 *  To contact us please register on our forums at:
 *      http://www.tectite.com/vbforums/
 *  or view our contact information:
 *      http://www.tectite.com/contacts.php
 *
 * Version History
 * ~~~~~~~~~~~~~~~
 *  Near the top of this file, you'll find its version. The version
 *  line looks like this:
 *       $FM_VERS = "N.MM";     /* script version ...
 *
 *  The version history used to be located within this file.  However,
 *  starting with Version 8.00 we've moved it...
 *
 *  You can read the complete version history of FormMail on our
 *  main website here:
 *   http://www.tectite.com/fmdoc/version_history.php
 */
 
    //
    // Capture the current date and time, for various purposes.
    //
$lNow = time();
 
set_magic_quotes_runtime(0);        // disable this silly setting (usually not enabled)
ini_set('track_errors',1);          // enable $php_errormsg
 
$aAlertInfo = array();
$aPHPVERSION = array();
 
$sLangID = "";                      // the language ID
$aMessages = array();               // all FormMail messages in the appropriate
                                    // language
 
$bUseOldVars = IsOldVersion($aPHPVERSION);
 
    //
    // seed the random number generate if not version 4.2.0 or later
    //
if (!IsPHPAtLeast("4.2.0"))
    mt_srand(time());
 
    //
    // we set references to the appropriate arrays to handle PHP version differences
    // Session vars are selected after we start the session.
    //
if ($bUseOldVars)
{
    $aServerVars = &$HTTP_SERVER_VARS;
    $aGetVars = &$HTTP_GET_VARS;
    $aFormVars = &$HTTP_POST_VARS;
    $aFileVars = &$HTTP_POST_FILES;
    $aEnvVars = &$HTTP_ENV_VARS;
}
else
{
    $aServerVars = &$_SERVER;
    $aGetVars = &$_GET;
    $aFormVars = &$_POST;
    $aFileVars = &$_FILES;
    $aEnvVars = &$_ENV;
}
$bIsGetMethod = false;
 
 
// --------------------------- INSERTION OF RECAPTCHA PART 2
 
# was there a reCAPTCHA response?
if ($_POST["recaptcha_response_field"]) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
  if ($resp->is_valid) {
 
 
// --------------------------- END OF INSERTION OF RECAPTCHA PART 2
 
    //
    // If the form submission was using the GET method, switch to the
    // GET vars instead of the POST vars
    //
if (isset($aServerVars["REQUEST_METHOD"]) && $aServerVars["REQUEST_METHOD"] === "GET")
{
    $bIsGetMethod = true;
    if ($bUseOldVars)
        $aFormVars = &$HTTP_GET_VARS;
    else
        $aFormVars = &$_GET;
}
 
if (!isset($REAL_DOCUMENT_ROOT))
    SetRealDocumentRoot();
 
if (isset($aServerVars['SERVER_PORT']))
    $SCHEME = ($aServerVars['SERVER_PORT'] == 80) ? "http://" : "https://";
else
    $SCHEME = "";
if (isset($aServerVars['SERVER_NAME']))
    $SERVER = $aServerVars['SERVER_NAME'];
else
    $SERVER = "";
 
/*****************************************************************************/
/* CONFIGURATION (do not alter this line in any way!!!)                      */
/*****************************************************************************
 * This is the *only* place where you need to modify things to use formmail.php
 * on your particular system.  This section finishes at "END OF CONFIGURATION".
 * Help for all settings can be found on our website:
 *  http://www.tectite.com/fmdoc/index.php
 *
 * Also, above each setting is a direct URL to the help information for the
 * setting.
 *****************************************************************************/
 
            /* Help: http://www.tectite.com/fmdoc/email_name.php */
define("EMAIL_NAME","^[-a-z0-9.]+");    // the '^' is an important security feature!
 
            /* Help: http://www.tectite.com/fmdoc/target_email.php */
$TARGET_EMAIL = array("^$info@bcpba\.org",
                );
 
            /* Help: http://www.tectite.com/fmdoc/def_alert.php */
define("DEF_ALERT","");
 
            /* Help: http://www.tectite.com/fmdoc/set_real_document_root.php */
$SET_REAL_DOCUMENT_ROOT = "";       // overrides the value set by SetRealDocumentRoot function
 
    //
    // override $REAL_DOCUMENT_ROOT from the $SET_REAL_DOCUMENT_ROOT value (if any)
    // Do not alter the following code (next 3 lines)!
    //
if (isset($SET_REAL_DOCUMENT_ROOT) && $SET_REAL_DOCUMENT_ROOT !== "")
    $REAL_DOCUMENT_ROOT = $SET_REAL_DOCUMENT_ROOT;
 
            /* Help: http://www.tectite.com/fmdoc/config_check.php */
$CONFIG_CHECK = array("TARGET_EMAIL");
 
            /* Help: http://www.tectite.com/fmdoc/at_mangle.php */
define("AT_MANGLE","W5XLZS3B");
 
            /* Help: http://www.tectite.com/fmdoc/target_urls.php */
$TARGET_URLS = array();         // default; no URLs allowed
 
            /* Help: http://www.tectite.com/fmdoc/head_crlf.php */
define("HEAD_CRLF","\r\n");
 
            /* Help: http://www.tectite.com/fmdoc/body_lf.php */
define("BODY_LF","\r\n");       // the new default: use this for CR+LF
//define("BODY_LF","\n");       // the old default: just LF
 
            /* Help: http://www.tectite.com/fmdoc/from_user.php */
$FROM_USER = "";                            // the default - setting not used
 
            /* Help: http://www.tectite.com/fmdoc/sendmail_f_option.php */
define("SENDMAIL_F_OPTION",false);
define("SENDMAIL_F_OPTION_LINE",__LINE__-1);    // don't modify this line!
 
            /* Help: http://www.tectite.com/fmdoc/fixed_sender.php */
$FIXED_SENDER = "";
 
            /* Help: http://www.tectite.com/fmdoc/set_sender_from_email.php */
define("SET_SENDER_FROM_EMAIL",false);
 
            /* Help: http://www.tectite.com/fmdoc/ini_set_from.php */
define("INI_SET_FROM",false);
 
            /* Help: http://www.tectite.com/fmdoc/logdir.php */
$LOGDIR = "";                           // directory for log files; empty string to
                                        // disallow log files
            /* Help: http://www.tectite.com/fmdoc/autorespondlog.php */
$AUTORESPONDLOG = "";           // file name in $LOGDIR for the auto responder
                                // log; empty string for no auto responder log
 
            /* Help: http://www.tectite.com/fmdoc/csv_file_settings.php */
$CSVDIR = "";                       // directory for csv files; empty string to
                                    // disallow csv files
$CSVSEP = ",";      // comma separator between fields (columns)
$CSVINTSEP = ";";   // semicolon is the separator for fields (columns)
                    // with multiple values (checkboxes, etc.)
$CSVQUOTE = '"';    // all fields in the CSV are quoted with this character;
                    // default is double quote.  You can change it to
                    // single quote or leave it empty for no quotes.
//$CSVQUOTE = "'";  // use this if you want single quotes
$CSVOPEN = "";      // set to "b" to force line terminations to be
                    // kept as $CSVLINE setting below, regardless of
                    // operating system.  Keep as empty string and
                    // leave $CSVLINE unchanged, to get text file
                    // terminations for your server's operating system.
                    // (Line feed on UNIX, carriage-return line feed on Windows).
$CSVLINE = "\n";    // line termination for CSV files.  The default is
                    // a single line feed, which may be modified for your
                    // server's operating system.  If you want to change
                    // this value, you *must* set $CSVOPEN = "b".
 
            /* Help: http://www.tectite.com/fmdoc/templatedir.php */
$TEMPLATEDIR = "";                  // directory for template files; empty string
                                    // if you don't have any templates
 
            /* Help: http://www.tectite.com/fmdoc/templateurl.php */
$TEMPLATEURL = "";                  // default; no template URL
 
            /* Help: http://www.tectite.com/fmdoc/multiformdir.php */
$MULTIFORMDIR = "";         // directory for multi-form template files; empty string
                            // if you're not using multi-forms
 
            /* Help: http://www.tectite.com/fmdoc/multiformurl.php */
$MULTIFORMURL = "";                 // default; no multi-forms templates URL
 
            /* Help: http://www.tectite.com/fmdoc/authentication_settings.php */
$AUTHENTICATE = "";
//$AUTHENTICATE = "Basic cnVzc2VsbHI6dGVzdA==";        // example
$AUTH_USER = "";
$AUTH_PW = "";
 
            /* Help: http://www.tectite.com/fmdoc/form_ini_file.php */
$FORM_INI_FILE = "";
 
            /* Help: http://www.tectite.com/fmdoc/moduledir.php */
$MODULEDIR = ".";
 
            /* Help: http://www.tectite.com/fmdoc/fmcompute.php */
$FMCOMPUTE = "fmcompute.php";
 
            /* Help: http://www.tectite.com/fmdoc/fmgeoip.php */
$FMGEOIP = "fmgeoip.php";
 
            /* Help: http://www.tectite.com/fmdoc/advanced_templates.php */
define("ADVANCED_TEMPLATES",false);     // set to true for advanced templates
 
            /* Help: http://www.tectite.com/fmdoc/limited_import.php */
define("LIMITED_IMPORT",true);      // set to true if your database cannot
                                    // handle escaped quotes or newlines within
                                    // imported data.  Microsoft Access is one
                                    // example.
 
            /* Help: http://www.tectite.com/fmdoc/valid_env.php */
$VALID_ENV = array('HTTP_REFERER','REMOTE_HOST','REMOTE_ADDR','REMOTE_USER',
				'HTTP_USER_AGENT');
 
            /* Help: http://www.tectite.com/fmdoc/fileuploads.php */
define("FILEUPLOADS",false);        // set to true to allow file attachments
 
            /* Help: http://www.tectite.com/fmdoc/max_file_upload_size.php */
define("MAX_FILE_UPLOAD_SIZE",0);       // default of 0 means that other software
                                        // controls the maximum file upload size
                                        // (FormMail doesn't test the file size)
 
            /* Help: http://www.tectite.com/fmdoc/file_repository.php */
$FILE_REPOSITORY = "";
 
            /* Help: http://www.tectite.com/fmdoc/file_mode.php */
define("FILE_MODE",0664);     // always precede with 0 to specify octal!
 
            /* Help: http://www.tectite.com/fmdoc/file_overwrite.php */
define("FILE_OVERWRITE",true);
 
            /* Help: http://www.tectite.com/fmdoc/next_num_file.php */
$NEXT_NUM_FILE = "";
 
            /* Help: http://www.tectite.com/fmdoc/put_data_in_url.php */
define("PUT_DATA_IN_URL",true); // set to true to place data in the URL
                                    // for bad_url redirects
 
            /* Help: http://www.tectite.com/fmdoc/db_see_input.php */
define("DB_SEE_INPUT",false);       // set to true to just see the input values
 
            /* Help: http://www.tectite.com/fmdoc/db_see_ini.php */
define("DB_SEE_INI",false);     // set to true to just see the ini file
 
            /* Help: http://www.tectite.com/fmdoc/maxstring.php */
define("MAXSTRING",1024);           // maximum string length for a value
 
            /* Help: http://www.tectite.com/fmdoc/bshowmesgnumbers.php */
$bShowMesgNumbers = false;
 
            /* Help: http://www.tectite.com/fmdoc/filters.php */
            /* Note for Tectite personnel: the upgrade Wizard will merge new values
             * but be careful of $var usage and quoting in new entries.
             */
$FILTERS = array("encode"=>"$REAL_DOCUMENT_ROOT/cgi-bin/fmencoder -kpubkey.txt",
                "null"=>"null",
 'csv'=>'csv');
 
            /* Help: http://www.tectite.com/fmdoc/socket_filters.php */
$SOCKET_FILTERS = array(
				 "httpencode"=>array("site"=>"YourSiteHere",
				 	"port"=>80,
					"path"=>"/cgi-bin/fmencoder",
					"params"=>array(array("name"=>"key",
							"file"=>"$REAL_DOCUMENT_ROOT/cgi-bin/pubkey.txt"))),
				 "sslencode"=>array("site"=>"ssl://YourSecureSiteHere",
				 	"port"=>443,
					"path"=>"/cgi-bin/fmencoder",
					"params"=>array(array("name"=>"key",
							"file"=>"$REAL_DOCUMENT_ROOT/cgi-bin/pubkey.txt"))),
				);
 
            /* Help: http://www.tectite.com/fmdoc/filter_attribs.php */
$FILTER_ATTRIBS = array("encode"=>"Strips,MIME=application/vnd.fmencoded,Encrypts",
                        "httpencode"=>"Strips,MIME=application/vnd.fmencoded,Encrypts",
                        "sslencode"=>"Strips,MIME=application/vnd.fmencoded,Encrypts",
                        "csv"=>"Strips,MIME=text/csv",);
 
            /* Help: http://www.tectite.com/fmdoc/check_for_new_version.php */
define("CHECK_FOR_NEW_VERSION",true);
define("CHECK_DAYS",30);
 
            /* Help: http://www.tectite.com/fmdoc/scratch_pad.php */
$SCRATCH_PAD = "";
 
            /* Help: http://www.tectite.com/fmdoc/cleanup_time.php */
$CLEANUP_TIME = 60;     // cleanup time in minutes
 
            /* Help: http://www.tectite.com/fmdoc/cleanup_chance.php */
$CLEANUP_CHANCE = 20;     // percentage probability that cleanup will be performed
 
            /* Help: http://www.tectite.com/fmdoc/pear_settings.php */
$PEAR_SMTP_HOST = "";
$PEAR_SMTP_PORT = 25;
$PEAR_SMTP_USER = "";
$PEAR_SMTP_PWD = "";
 
            /* Help: http://www.tectite.com/fmdoc/alert_on_user_error.php */
define("ALERT_ON_USER_ERROR",false);
 
            /* Help: http://www.tectite.com/fmdoc/enable_attack_detection.php */
define("ENABLE_ATTACK_DETECTION",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_url.php */
define("ATTACK_DETECTION_URL","");
 
            /* Help: http://www.tectite.com/fmdoc/alert_on_attack_detection.php */
define("ALERT_ON_ATTACK_DETECTION",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_mime.php */
define("ATTACK_DETECTION_MIME",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_dups.php */
$ATTACK_DETECTION_DUPS = array("realname","address1","address2","country","zip",
                                "phone","postcode","state","email");
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_specials.php */
define("ATTACK_DETECTION_SPECIALS",false);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_specials.php */
$ATTACK_DETECTION_SPECIALS_ONLY_EMAIL = array("derive_fields","required",
                    "mail_options","good_url","bad_url","good_template",
                    "bad_template");
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_specials.php */
$ATTACK_DETECTION_SPECIALS_ANY_EMAIL = array("subject");
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_many_urls.php */
define("ATTACK_DETECTION_MANY_URLS",0);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_many_url_fields.php */
define("ATTACK_DETECTION_MANY_URL_FIELDS",0);
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_url_patterns.php */
$ATTACK_DETECTION_URL_PATTERNS = array(
            '(^|[^-a-z_.0-9]+)(?<!@)([-a-z0-9]+\.)+(com|org|net|biz|info|name|pro|tel|asia|cat)\b',
            '(^|[^-a-z_.0-9]+)(?<!@)([-a-z0-9]+\.)+(com{0,1}|org|net)\.[a-z][a-z]\b');
 
            /* Help: http://www.tectite.com/fmdoc/attack_detection_ignore_errors.php */
define("ATTACK_DETECTION_IGNORE_ERRORS",false);
 
            /* Help: http://www.tectite.com/fmdoc/geoip_lic.php */
$GEOIP_LIC = "";        // default - no GeoIP
 
            /* Help: http://www.tectite.com/fmdoc/zero_is_empty.php */
define("ZERO_IS_EMPTY",false);
 
            /* Help: http://www.tectite.com/fmdoc/session_name.php */
$SESSION_NAME = "";
 
            /* Help: http://www.tectite.com/fmdoc/hook_dir.php */
$HOOK_DIR = "";
 
/* UPGRADE CONTROL
**
** FILTERS:lt:8.04:merge:The FILTERS configuration has
** been modified to include some new standard filters.:
**
** FILTER_ATTRIBS:lt:8.04:no_keep:The FILTER_ATTRIBS configuration has
** been modified to include new information about the standard filters.:
**
** ATTACK_DETECTION_URL_PATTERNS:eq:8.02:no_keep:The ATTACK_DETECTION_URL_PATTERNS
** configuration has been modified to fix a bug.:
**
** FILTER_ATTRIBS:lt:4.00:no_keep:The FILTER_ATTRIBS configuration has
** been modified to include new information about the standard filters.:
**
** SET_REAL_DOCUMENT_ROOT:gt:4.07:copy_from=REAL_DOCUMENT_ROOT:The
** REAL_DOCUMENT_ROOT configuration has been renamed to SET_REAL_DOCUMENT_ROOT.:
**
** EMAIL_NAME:lt:6.01:no_keep:The EMAIL_NAME configuration has
** been modified to match hyphens ('-') in email addresses.:
**
** ZERO_IS_EMPTY:le:6.01:set_to=true:ZERO_IS_EMPTY has been
** set to a value that duplicates previous behaviour.:
**
** END OF CONTROL
*/
 
/*****************************************************************************/
/* END OF CONFIGURATION (do not alter this line in any way!!!)               */
/*****************************************************************************/
    //
    // the following constants define all FormMail messages
    //
define('MSG_SCRIPT_VERSION',0);     // This script requires at least PHP version...
define('MSG_END_VERS_CHK',1);       // If you're happy...
define('MSG_VERS_CHK',2);           // A later version of FormMail is available...
define('MSG_CHK_FILE_ERROR',3);     // Unable to create check file...
define('MSG_UNK_VALUE_SPEC',4);     // derive_fields: unknown value specification...
define('MSG_INV_VALUE_SPEC',5);     // derive_fields: invalid value specification...
define('MSG_DERIVED_INVALID',6);    // Some derive_fields specifications...
define('MSG_INT_FORM_ERROR',7);     // Internal form error...
define('MSG_OPTIONS_INVALID',8);    // Some mail_options settings...
define('MSG_PLSWAIT_REDIR',9);      // Please wait while you are redirected...
define('MSG_IFNOT_REDIR',10);       // If you are not redirected...
define('MSG_PEAR_OBJ',11);          // Failed to create PEAR Mail object...
define('MSG_PEAR_ERROR',12);        // PEAR Mail error...
define('MSG_NO_FOPT_ADDR',13);      // You have specified "SendMailFOption"...
define('MSG_MORE_INFO',14);         // More information...
define('MSG_INFO_STOPPED',15);      // Extra alert information suppressed...
define('MSG_FM_ALERT',16);          // FormMail alert
define('MSG_FM_ERROR',17);          // FormMail script error
define('MSG_FM_ERROR_LINE',18);     // The following error occurred...
define('MSG_USERDATA_STOPPED',19);  // User data suppressed...
define('MSG_FILTERED',20);          // This alert has been filtered...
define('MSG_TEMPLATES',21);         // You must set either TEMPLATEDIR or TEMPLATEURL...
define('MSG_OPEN_TEMPLATE',22);     // Failed to open template...
define('MSG_ERROR_PROC',23);        // An error occurred while processing...
define('MSG_ALERT_DONE',24);        // Our staff have been alerted...
define('MSG_PLS_CONTACT',25);       // Please contact us directly...
define('MSG_APOLOGY',26);           // We apologize for any inconvenience...
define('MSG_ABOUT_FORMMAIL',27);    // Your form submission was processed by...
define('MSG_PREG_FAILED',28);       // preg_match_all failed in FindCRMFields...
define('MSG_URL_INVALID',29);       // CRM URL "$URL" is not valid...
define('MSG_URL_OPEN',30);          // Failed to open Customer Relationship...
define('MSG_CRM_FAILED',31);        // Failure report from CRM...
define('MSG_CRM_FORM_ERROR',32);    // Your form submission was not...
define('MSG_OR',33);                // "$ITEM1" or "$ITEM2"
define('MSG_NOT_BOTH',34);          // not both "$ITEM1" and "$ITEM2"
define('MSG_XOR',35);               // "$ITEM1" or "$ITEM2" (but not both)
define('MSG_IS_SAME_AS',36);        // "$ITEM1" is the same as "$ITEM2"
define('MSG_IS_NOT_SAME_AS',37);    // "$ITEM1" is not the same as "$ITEM2"
define('MSG_REQD_OPER',38);         // Operator "$OPER" is not valid for "required"
define('MSG_PAT_FAILED',39);        // Pattern operator "$OPER" failed: pattern...
define('MSG_COND_OPER',40);         // Operator "$OPER" is not valid...
define('MSG_INV_COND',41);          // Invalid "conditions" field...
define('MSG_COND_CHARS',42);        // The conditions field "$FLD" is not valid...
define('MSG_COND_INVALID',43);      // The conditions field "$FLD" is not valid...
define('MSG_COND_TEST_LONG',44);    // Field "$FLD" has too many components...
define('MSG_COND_IF_SHORT',45);     // Field "$FLD" has too few components for...
define('MSG_COND_IF_LONG',46);      // Field "$FLD" has too many components for...
define('MSG_COND_UNK',47);          // Field "$FLD" has an unknown command word...
define('MSG_MISSING',48);           // Missing "$ITEM"...
define('MSG_NEED_ARRAY',49);        // "$ITEM" must be an array...
define('MSG_SUBM_FAILED',50);       // Your form submission has failed...
define('MSG_FILTER_WRONG',51);      // Filter "$FILTER" is not properly...
define('MSG_FILTER_CONNECT',52);    // Could not connect to site "$SITE"...
define('MSG_FILTER_PARAM',53);      // Filter "$FILTER" has invalid parameter...
define('MSG_FILTER_OPEN_FILE',54);  // Filter "$FILTER" cannot open file...
define('MSG_FILTER_FILE_ERROR',55); // Filter "$FILTER": read error on file...
define('MSG_FILTER_READ_ERROR',56); // Filter '$filter' failed: read error...
define('MSG_FILTER_NOT_OK',57);     // Filter 'FILTER' failed...
define('MSG_FILTER_UNK',58);        // Unknown filter...
define('MSG_FILTER_CHDIR',59);      // Cannot chdir...
define('MSG_FILTER_NOTFOUND',60);   // Cannot execute...
define('MSG_FILTER_ERROR',61);      // Filter "$FILTER" failed...
define('MSG_FLD_NOTFOUND',62);      // "$FIELD" is not a field submitted...
define('MSG_TEMPLATE_ERRORS',63);   // Template "$NAME" caused the...
define('MSG_TEMPLATE_FAILED',64);   // Failed to process template "$NAME"...
define('MSG_MIME_PREAMBLE',65);     // (Your mail reader should not show this...
define('MSG_MIME_HTML',66);         // This message has been generated by FormMail...
define('MSG_FILE_OPEN_ERROR',67);   // Failed to open file "$NAME"...
define('MSG_ATTACH_DATA',68);       // Internal error: AttachFile requires...
define('MSG_PHP_HTML_TEMPLATES',69);    // HTMLTemplate option is only ...
define('MSG_PHP_FILE_UPLOADS',70);  // For security reasons, file upload...
define('MSG_FILE_UPLOAD',71);       // File upload attempt ignored...
define('MSG_FILE_UPLOAD_ATTACK',72);// Possible file upload attack...
define('MSG_PHP_PLAIN_TEMPLATES',73);// PlainTemplate option is only...
define('MSG_ATTACH_NAME',74);       // filter_options: Attach must contain a name...
define('MSG_PHP_BCC',75);           // Warning: BCC is probably not supported...
define('MSG_CSVCOLUMNS',76);        // The "csvcolumns" setting is not...
define('MSG_CSVFILE',77);           // The "csvfile" setting is not...
define('MSG_TARG_EMAIL_PAT_START',78);  // Warning: Your TARGET_EMAIL pattern...
define('MSG_TARG_EMAIL_PAT_END',79);    // Warning: Your TARGET_EMAIL pattern...
define('MSG_CONFIG_WARN',80);       // The following potential problems...
define('MSG_PHP_AUTORESP',81);      // Autorespond is only supported...
define('MSG_ALERT',82);             // This is a test alert message...
define('MSG_NO_DEF_ALERT',83);      // No DEF_ALERT value has been set....
define('MSG_TEST_SENT',84);         // Test message sent.  Check your email.....
define('MSG_TEST_FAILED',85);       // FAILED to send alert message...
define('MSG_NO_DATA_PAGE',86);      // This URL is a Form submission program...
define('MSG_REQD_ERROR',87);        // The form required some values that you...
define('MSG_COND_ERROR',88);        // Some of the values you provided...
define('MSG_CRM_FAILURE',89);       // The form submission did not succeed...
define('MSG_FOPTION_WARN',90);      // Warning: You've used SendMailFOption in...
define('MSG_NO_ACTIONS',91);        // The form has an internal error...
define('MSG_NO_RECIP',92);          // The form has an internal error...
define('MSG_INV_EMAIL',93);         // Invalid email addresses...
define('MSG_FAILED_SEND',94);       // Failed to send email...
define('MSG_ARESP_EMAIL',96);       // No "email" field was found. Autorespond...
define('MSG_ARESP_SUBJ',97);        // Your form submission...
define('MSG_LOG_NO_VERIMG',98);     // No VerifyImgString in session...
define('MSG_ARESP_NO_AUTH',99);     // Failed to obtain authorization...
define('MSG_LOG_NO_MATCH',100);     // User did not match image...
define('MSG_ARESP_NO_MATCH',101);   // Your entry did not match...
define('MSG_LOG_FAILED',102);       // Failed
define('MSG_ARESP_FAILED',103);     // Autoresponder failed
define('MSG_LOG_OK',104);           // OK
define('MSG_THANKS_PAGE',105);      // Thanks!  We've received your....
define('MSG_LOAD_MODULE',106);      // Cannot load module....
define('MSG_LOAD_FMCOMPUTE',107);   // Cannot load FMCompute....
define('MSG_REGISTER_MODULE',108);  // Cannot register module....
define('MSG_COMP_PARSE',109);       // These parse errors occurred....
define('MSG_COMP_REG_DATA',110);    // Failed to register data field....
define('MSG_COMP_ALERT',111);       // The following alert messages....
define('MSG_COMP_DEBUG',112);       // The following debug messages...
define('MSG_COMP_EXEC',113);        // The following errors occurred....
define('MSG_REG_FMCOMPUTE',114);    // Cannot register function...
define('MSG_USER_ERRORS',115);      // A number of errors occurred...
define('MSG_CALL_PARAM_COUNT',116); // Invalid parameter count...
define('MSG_CALL_UNK_FUNC',117);    // Unknown function...
define('MSG_SAVE_FILE',118);        // Failed to save file....
define('MSG_CHMOD',119);            // Failed to chmod file....
define('MSG_VERIFY_MISSING',120);   // Image verification string missing...
define('MSG_VERIFY_MATCH',121);     // Your entry did not match...
define('MSG_FILE_NAMES_INVALID',122);// Some file_names specifications...
define('MSG_FILE_NAMES_NOT_FILE',123);// Your file_names specification...
define('MSG_TEMPL_ALERT',124);       // The following alert messages....
define('MSG_TEMPL_DEBUG',125);       // The following debug messages...
define('MSG_TEMPL_PROC',126);        // The following errors occurred....
define('MSG_SAVE_FILE_EXISTS',127);  // Cannot save file....
define('MSG_EMPTY_ADDRESSES',128);   // $COUNT empty addresses
 
define('MSG_AND',133);              // "$ITEM1" and "$ITEM2"
define('MSG_NEXT_PLUS_GOOD',134);   // The form specifies both next_form and....
define('MSG_MULTIFORM',135);        // You must set either MULTIFORMDIR or MULTIFORMURL...
define('MSG_MULTIFORM_FAILED',136); // Failed to process multi-page form template "$NAME"...
define('MSG_NEED_THIS_FORM',137);   // Multi-page forms require "this_form" field...
define('MSG_NO_PHP_SELF',138);      // PHP on the server is not providing "PHP_SELF"
define('MSG_RETURN_URL_INVALID',139); // Return "$URL" is not valid...
define('MSG_GO_BACK',140);          // Cannot 'go back' if not a multi-page form...
define('MSG_OPEN_URL',141);         // Cannot open URL...
define('MSG_CANNOT_RETURN',142);    // Cannot return to page....
define('MSG_ATTACK_DETECTED',143);  // Server attack detected....
define('MSG_ATTACK_PAGE',144);      // Your form submission....
define('MSG_ATTACK_MIME_INFO',145); // The field "$FLD" contained...
define('MSG_ATTACK_DUP_INFO',146);  // The fields "$FLD1" and...
define('MSG_ATTACK_SPEC_INFO',147); // Special field "$FLD"...
define('MSG_NEED_SCRATCH_PAD',148); // You need to set SCRATCH_PAD...
define('MSG_MULTI_UPLOAD',149);     // File upload processing failed during multi-page form processing.
define('MSG_OPEN_SCRATCH_PAD',150); // Cannot open directory...
define('MSG_NO_NEXT_NUM_FILE',151); // You cannot use the %nextnum% feature...
define('MSG_NEXT_NUM_FILE',152);    // Cannot process next number...
define('MSG_ATTACK_MANYURL_INFO',153); // Field "$FLD"...
define('MSG_ATTACK_MANYFIELDS_INFO',154); // $NUM fields have URLs....
 
define('MSG_URL_PARSE',160);        // URL parse failed
define('MSG_URL_SCHEME',161);       // Unsupported URL scheme...
define('MSG_SOCKET',162);           // Socket error ...
define('MSG_GETURL_OPEN',163);      // Open URL failed: ...
 
    //
    // The following are PHP's file upload error messages
    //
define('MSG_FILE_UPLOAD_ERR_UNK',180);  // Unknown error code.
define('MSG_FILE_UPLOAD_ERR1',181);     // The uploaded file exceeds the upload_max_filesize directive in php.ini.
define('MSG_FILE_UPLOAD_ERR2',182);     // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.
define('MSG_FILE_UPLOAD_ERR3',183);     // The uploaded file was only partially uploaded.
define('MSG_FILE_UPLOAD_ERR4',184);     // No file was uploaded.
define('MSG_FILE_UPLOAD_ERR6',186);     // Missing a temporary folder.
define('MSG_FILE_UPLOAD_ERR7',187);     // Failed to write file to disk.
define('MSG_FILE_UPLOAD_ERR8',188);     // File upload stopped by extension.
define('MSG_FILE_UPLOAD_SIZE',189);     // Uploaded file "$NAME" is too big...
                                        // (not a PHP error code - internal maximum file size error)
 
    //
    // following are for derive_fields functions
    //
define('MSG_DER_FUNC_ERROR',200);       // derive_fields: invalid function....
define('MSG_DER_FUNC_SIZE_FMT',201);    // function 'size' requires....
define('MSG_DER_FUNC_IF_FMT',202);      // function 'if' requires....
define('MSG_DER_FUNC_NEXTNUM_FMT',203); // function 'nextnum' requires....
define('MSG_DER_FUNC_EXT_FMT',204);     // function 'ext' requires....
define('MSG_DER_FUNC1_FMT',205);        // function 'FUNC' requires....
 
// <A NAME="MessageNumbers"> Jump to: <A HREF="#BuiltinMessages">
 
    //
    // Return true if using the built-in language
    //
function IsBuiltInLanguage()
{
    global  $sLangID;
 
    return (strpos($sLangID,"builtin") !== false);
}
 
$sSavePath = "";
$bPathSaved = false;
    //
    // Set include path to include the given directory.
    //
function AddIncludePath($s_dir = ".")
{
    global  $sSavePath,$bPathSaved;
 
    $s_path = ini_get('include_path');
    $i_path_len = strlen($s_path);
    $s_sep = IsServerWindows() ? ";" : ":";     // get path separator
        //
        // look for it in the include_path
        //
    $b_found = false;
    $i_pos = 0;
    $i_len = strlen($s_dir);
    while (!$b_found && ($i_pos = strpos($s_path,$s_dir,$i_pos)) !== false)
    {
        if ($i_pos == 0)
        {
            if ($i_len == $i_path_len)
                $b_found = true;        // the path only has $s_dir
            elseif ($s_path{$i_len} == $s_sep)
                $b_found = true;
        }
        elseif ($s_path{$i_pos-1} == $s_sep &&
                    ($i_pos + $i_len == $i_path_len ||
                    $s_path{$i_pos + $i_len} == $s_sep))
                $b_found = true;
        if (!$b_found)
            $i_pos++;
    }
    if (!$b_found)
    {
            //
            // allow multiple calls, but only store the original path once
            //
        if (!$bPathSaved)
            $sSavePath = $s_path;
        if (empty($s_path))
            $s_path = $s_dir;
        else
                //
                // prepend the directory
                //
            $s_path = $s_dir.$s_sep.$s_path;
        ini_set('include_path',$s_path);
        $bPathSaved = true;
    }
}
 
    //
    // Reset the include path after a call to AddIncludePath.
    //
function ResetIncludePath()
{
    global  $sSavePath,$bPathSaved;
 
    if ($bPathSaved)
    {
        ini_set('include_path',$sSavePath);
        $bPathSaved = false;
    }
}
 
    //
    // Load a language file
    //
function LoadLanguageFile()
{
    global  $aMessages,$sLangID,$sHTMLCharSet;
 
    AddIncludePath();
    @include("language.inc");
    ResetIncludePath();
}
 
    //
    // Load the messages array from the default language, and then
    // override with an optional language file.
    // Note: all messages get the MNUM parameter sent which they can use.
    // If they don't use it, the message number is appended.
    //
function LoadBuiltinLanguage()
{
    global  $aMessages,$sLangID;
 
    $sLangID = "English (builtin)";
        // MSG_SCRIPT_VERSION is shown if the PHP version is too old to run
        // FormMail
        // Parameters:
        //  $PHPREQ     is the minimum required PHP version
        //  $PHPVERS    is  the version the server currently has installed.
    $aMessages[MSG_SCRIPT_VERSION] = 'This script requires at least PHP version '.
                                     '$PHPREQ.  You have PHP version $PHPVERS.';
 
        // MSG_END_VERS_CHK is sent at the end of an Alert message when
        // FormMail detects that there's a newer version available
        // Parameters: none
    $aMessages[MSG_END_VERS_CHK] =  '***************************************************\n'.
                                    'If you are happy with your current version and want\n'.
                                    'to stop these reminders, edit formmail.php and\n'.
                                    'set CHECK_FOR_NEW_VERSION to false.\n'.
                                    '***************************************************\n';
 
        // MSG_VERS_CHK is sent in an Alert message when
        // FormMail detects that there's a newer version available
        // Parameters:
        //  $TECTITE    the website to go to
        //  $FM_VERS    the current FormMail version
        //  $NEWVERS    the new FormMail version that's available
    $aMessages[MSG_VERS_CHK] =  'A later version of FormMail is available from $TECTITE.\n'.
                                'You are currently using version $FM_VERS.\n'.
                                'The new version available is $NEWVERS.\n';
 
        // MSG_CHK_FILE_ERROR is sent in an Alert message when
        // FormMail cannot create a file to record the time of version check.
        // Parameters:
        //  $FILE   the file name that could not be created
        //  $ERROR  the actual error message
    $aMessages[MSG_CHK_FILE_ERROR] = 'Unable to create check file "$FILE": $ERROR';
 
        // MSG_UNK_VALUE_SPEC is sent in an Alert message when
        // a form uses an unknown value specification in derive_fields.
        // Parameters:
        //  $SPEC   the unknown value specification
        //  $MSG    additional message
    $aMessages[MSG_UNK_VALUE_SPEC] = 'derive_fields: unknown value specification '.
                                     '"$SPEC"$MSG';
 
        // MSG_INV_VALUE_SPEC is sent in an Alert message when
        // a form uses a value specification in derive_fields that's
        // formatted incorrectly (missing terminating '%')
        // Parameters:
        //  $SPEC   the invalid value specification
    $aMessages[MSG_INV_VALUE_SPEC] = 'derive_fields: invalid value specification '.
                                     '"$SPEC" (possibly missing a "%")';
 
        // MSG_DERIVED_INVALID is sent in an Alert message when
        // a form's derive_fields setting has errors
        // Parameters: none
        // A list of errors is appended on separate lines
    $aMessages[MSG_DERIVED_INVALID] = 'Some derive_fields specifications are invalid $MNUM:\n';
 
        // MSG_INT_FORM_ERROR is sent in an Alert message and displayed
        // to the form user
        // Parameters: none
    $aMessages[MSG_INT_FORM_ERROR] = 'Internal form error';
 
        // MSG_OPTIONS_INVALID is sent in an Alert message when
        // a form's options settings are invalid.  This applies to
        // mail_options, filter_options, crm_options, and autorespond
        // Parameters:
        //  $OPT    the name of the options field
        // A list of errors is appended on separate lines
    $aMessages[MSG_OPTIONS_INVALID] = 'Some $OPT settings are undefined $MNUM:\n';
 
        // MSG_PLSWAIT_REDIR is shown to the user for a redirect
        // with JavaScript
        // Parameters: none
    $aMessages[MSG_PLSWAIT_REDIR] = 'Please wait while you are redirected...';
 
        // MSG_IFNOT_REDIR is shown to the user for a redirect
        // with JavaScript
        // Parameters:
        //  $URL    the URL to redirect to
    $aMessages[MSG_IFNOT_REDIR] = 'If you are not automatically redirected, '.
                                  'please <a href="$URL">click here</a>.';
 
        // MSG_PEAR_OBJ is shown to the user if the PEAR Mail object
        // cannot be created
        // Parameters: none
    $aMessages[MSG_PEAR_OBJ] = 'Failed to create PEAR Mail object';
 
        // MSG_PEAR_ERROR is sent in an Alert message if the PEAR Mail processing
        // reports an error
        // Parameters:
        //  $MSG    the error message from PEAR
    $aMessages[MSG_PEAR_ERROR] = 'PEAR Mail error: $MSG';
 
        // MSG_NO_FOPT_ADDR is sent in an Alert message SendMailFOption is
        // specified in the form and no email address has been provided
        // Parameters: none
    $aMessages[MSG_NO_FOPT_ADDR] = 'You have specified "SendMailFOption" in your '.
                                   'form, but there is no email address to use';
 
        // MSG_MORE_INFO is sent in an Alert message on a line by itself, just
        // before extra information about the FormMail processing that may have
        // led to the alert message
        // Parameters: none
    $aMessages[MSG_MORE_INFO] = 'More information:';
 
        // MSG_INFO_STOPPED is sent in an Alert message to say that extra
        // alert information has been suppressed because of potential security
        // problems with showing it.
        // Parameters: none
    $aMessages[MSG_INFO_STOPPED] = '(Extra alert information suppressed for '.
                                   'security purposes. $MNUM)';
 
        // MSG_FM_ALERT is sent as the subject line of an Alert message
        // Parameters: none
    $aMessages[MSG_FM_ALERT] = 'FormMail alert';
 
        // MSG_FM_ERROR is sent as the subject line of an Alert message
        // Parameters: none
    $aMessages[MSG_FM_ERROR] = 'FormMail script error';
 
        // MSG_FM_ERROR_LINE is sent in an Alert message on a
        // separate line to introduce the actual error message
        // Parameters: none
    $aMessages[MSG_FM_ERROR_LINE] = 'The following error occurred in FormMail $MNUM:';
 
        // MSG_USERDATA_STOPPED is sent in an Alert message to say that the
        // user's data has been suppressed because of potential security
        // problems with showing it.
        // Parameters: none
    $aMessages[MSG_USERDATA_STOPPED] = '(User data suppressed for security '.
                                       'purposes. $MNUM)';
 
        // MSG_FILTERED is sent in an Alert message to show what filter
        // has been used on the message
        // Parameters:
        //  $FILTER     the name of the filter
    $aMessages[MSG_FILTERED] = 'This alert has been filtered through "$FILTER" '.
                               'for security purposes.';
 
        // MSG_TEMPLATES is sent in an Alert message when a form tries
        // to use a template, but templates have not been configured in
        // formmail.php
        // Parameters: none
    $aMessages[MSG_TEMPLATES] = 'You must set either TEMPLATEDIR or TEMPLATEURL '.
                                'in formmail.php before you can specify '.
                                'templates in your forms.';
 
        // MSG_OPEN_TEMPLATE is sent in an Alert message when FormMail cannot
        // open a template file
        // Parameters:
        //  $NAME   the name of the template file
        //  $ERROR  information about the error
    $aMessages[MSG_OPEN_TEMPLATE] = 'Failed to open template "$NAME" $MNUM: $ERROR';
 
        // MSG_ERROR_PROC is shown to the user as part of an error
        // page.  This message introduces the error.
        // Parameters: none
    $aMessages[MSG_ERROR_PROC] = 'An error occurred while processing the '.
                                 'form $MNUM.\n\n';
 
        // MSG_ALERT_DONE is shown to the user as part of an error
        // page if an Alert message has been sent to the website owner.
        // Parameters: none
    $aMessages[MSG_ALERT_DONE] = 'Our staff have been alerted to the error $MNUM.\n';
 
        // MSG_PLS_CONTACT is shown to the user as part of an error
        // page if an Alert message could *not* be sent to the website owner.
        // Parameters: none
    $aMessages[MSG_PLS_CONTACT] = 'Please contact us directly since this form '.
                                  'is not working $MNUM.\n';
 
        // MSG_APOLOGY is shown to the user as part of an error
        // page as an apology for a problem with the form.
        // Parameters: none
    $aMessages[MSG_APOLOGY] = 'We apologize for any inconvenience this error '.
                              'may have caused.';
 
        // MSG_ABOUT_FORMMAIL is shown to the user at the foot of pages
        // generated by FormMail (e.g. the default "Thanks" page and default
        // error page).
        // Parameters:
        //  $FM_VERS    the FormMail version number
        //  $TECTITE    www.tectite.com
    $aMessages[MSG_ABOUT_FORMMAIL] = 'Your form submission was processed by bcpba.org'.
                                     ''.
                                     '';
 
        // MSG_PREG_FAILED is sent in an Alert message if the TectiteCRM
        // system failed to return the expected result.
        // Parameters: none
    $aMessages[MSG_PREG_FAILED] = 'preg_match_all failed in FindCRMFields';
 
        // MSG_URL_INVALID is sent in an Alert message if the specified
        // URL for TectiteCRM is not valid according to the TARGET_URLS
        // configuration setting
        // Parameters:
        //  $URL        the invalid URL
    $aMessages[MSG_URL_INVALID] = 'The URL "$URL" to access the Customer '.
                                  'Relationship Management System is not valid '.
                                  '(see TARGET_URLS in formmail.php)';
 
        // MSG_URL_OPEN is sent in an Alert message if the specified
        // URL for TectiteCRM cannot be opened
        // Parameters:
        //  $URL    the invalid URL
        //  $ERROR  information about the error
    $aMessages[MSG_URL_OPEN] = 'Failed to open Customer Relationship '.
                               'Management System URL "$URL" $MNUM: $ERROR';
 
        // MSG_CRM_FAILED is sent in an Alert message if the TectiteCRM
        // system doesn't return an OK message
        // Parameters:
        //  $URL    the invalid URL
        //  $MSG    more information
    $aMessages[MSG_CRM_FAILED] = 'Failure report from Customer Relationship '.
                                 'Management System (url="$URL") $MNUM: $MSG';
 
        // MSG_CRM_FORM_ERROR is shown to the user if the information
        // passed to TectiteCRM was not accepted
        // Parameters: none
    $aMessages[MSG_CRM_FORM_ERROR] = 'Your form submission was not accepted';
 
        // MSG_AND is shown to the user; it shows two items separated
        // by "and"
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_AND] = '"$ITEM1" and "$ITEM2"';
 
        // MSG_OR is shown to the user; it shows two items separated
        // by "or"
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_OR] = '"$ITEM1" or "$ITEM2"';
 
        // MSG_NOT_BOTH is shown to the user; it shows two items that must
        // be specified together
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_NOT_BOTH] = 'not both "$ITEM1" and "$ITEM2"';
 
        // MSG_XOR is shown to the user; it shows two items that must
        // not be specified together
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_XOR] = '"$ITEM1" or "$ITEM2" (but not both)';
 
        // MSG_IS_SAME_AS is shown to the user; it shows two items that must
        // not be the same value
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_IS_SAME_AS] = '"$ITEM1" is the same as "$ITEM2"';
 
        // MSG_IS_NOT_SAME_AS is shown to the user; it shows two items that must
        // be the same value
        // Parameters:
        //  $ITEM1      the first item
        //  $ITEM2      the second item
    $aMessages[MSG_IS_NOT_SAME_AS] = '"$ITEM1" is not the same as "$ITEM2"';
 
        // MSG_REQD_OPER is sent in an Alert message when an unknown
        // operator has been used in a "required" specification
        // Parameters:
        //  $OPER       the unknown operator
    $aMessages[MSG_REQD_OPER] = 'Operator "$OPER" is not valid for "required"';
 
        // MSG_PAT_FAILED is sent in an Alert message when a "conditions" pattern
        // match has not matched anything (this isn't necessarily an error)
        // Parameters:
        //  $OPER       the "conditions" operator
        //  $PAT        the "conditions" pattern
        //  $VALUE      the value that was searched
    $aMessages[MSG_PAT_FAILED] = 'Pattern operator "$OPER" failed: pattern '.
                                 '"$PAT", value searched was "$VALUE".';
 
        // MSG_COND_OPER is sent in an Alert message when a "conditions"
        // operator is not value
        // Parameters:
        //  $OPER       the "conditions" operator
    $aMessages[MSG_COND_OPER] = 'Operator "$OPER" is not valid for "conditions"';
 
        // MSG_INV_COND is sent in an Alert message when a "conditions"
        // field is not valid
        // Parameters:
        //  FLD     the field name
    $aMessages[MSG_INV_COND] = 'Invalid "conditions" field "$FLD" - not a string or array.';
 
        // MSG_COND_CHARS is sent in an Alert message when a "conditions"
        // field is missing the mandatory first 2 characters (the separators)
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
    $aMessages[MSG_COND_CHARS] = 'The conditions field "$FLD" is not valid. '.
                                 'You must provide the two separator '.
                                 'characters at the beginning. You had "$COND".';
 
        // MSG_COND_INVALID is sent in an Alert message when a "conditions"
        // field has the wrong format
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the internal separator character for the field.
    $aMessages[MSG_COND_INVALID] = 'The conditions field "$FLD" is not valid. '.
                                   'There must be at least 5 components '.
                                   'separated by "$SEP". Your value was "$COND".';
 
        // MSG_COND_TEST_LONG is sent in an Alert message when a "conditions"
        // TEST value has too many components
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the list separator character for the field.
    $aMessages[MSG_COND_TEST_LONG] = 'Field "$FLD" has too many components for '.
                                     'a "TEST" command: "$COND".\nAre you missing '.
                                     'a "$SEP"?';
 
        // MSG_COND_IF_SHORT is sent in an Alert message when a "conditions"
        // IF value has too few components
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the internal separator character for the field.
    $aMessages[MSG_COND_IF_SHORT] = 'Field "$FLD" has too few components for '.
                                    'an "IF" command: "$COND".\nThere must be '.
                                    'at least 6 components separated by "$SEP"';
 
        // MSG_COND_IF_LONG is sent in an Alert message when a "conditions"
        // IF value has too many components
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  SEP     the list separator character for the field.
    $aMessages[MSG_COND_IF_LONG] = 'Field "$FLD" has too many components for '.
                                   'an "IF" command: "$COND".\nAre you missing '.
                                   'a "$SEP"?';
 
        // MSG_COND_UNK is sent in an Alert message when a "conditions"
        // value has an unknown command
        // Parameters:
        //  FLD     the field name
        //  COND    the conditions field value
        //  CMD     the unknown command
    $aMessages[MSG_COND_UNK] = 'Field "$FLD" has an unknown command word '.
                               '"$CMD": "$COND".';
 
        // MSG_MISSING is sent in an Alert message when
        // a socket filter is incorrectly defined
        // Parameters:
        //  ITEM    the missing item
    $aMessages[MSG_MISSING] = 'Missing "$ITEM"';
 
        // MSG_NEED_ARRAY is sent in an Alert message when
        // a socket filter is incorrectly defined
        // Parameters:
        //  ITEM    the item that should be an array
    $aMessages[MSG_NEED_ARRAY] = '"$ITEM" must be an array';
 
        // MSG_SUBM_FAILED is shown to the user when an internal error
        // as occurred and that error is not to be shown
        // Parameters: none
    $aMessages[MSG_SUBM_FAILED] = 'Your form submission has failed due to '.
                                  'an error on our server.';
 
        // MSG_FILTER_WRONG is sent in an Alert message when
        // a socket filter is incorrectly defined
        // Parameters:
        //  FILTER  the filter name
        //  ERRORS  a string containing a list of errors
    $aMessages[MSG_FILTER_WRONG] = 'Filter "$FILTER" is not properly defined: '.
                                   '$ERRORS';
 
        // MSG_FILTER_CONNECT is sent in an Alert message when FormMail
        // cannot connect to a socket filter
        // Parameters:
        //  FILTER  the filter name
        //  SITE    the site
        //  ERRNUM  socket error number
        //  ERRSTR  socket error message
    $aMessages[MSG_FILTER_CONNECT] = 'Could not connect to site "$SITE" '.
                                     'for filter "$FILTER" ($ERRNUM): $ERRSTR';
 
        // MSG_FILTER_PARAM is sent in an Alert message when a socket
        // filter has an invalid parameter specification
        // Parameters:
        //  FILTER  the filter name
        //  NUM     parameter number
        //  NAME    parameter name
    $aMessages[MSG_FILTER_PARAM] = 'Filter "$FILTER" has invalid parameter '.
                                   '#$NUM: no "$NAME"';
 
        // MSG_FILTER_OPEN_FILE is sent in an Alert message when a socket
        // filter cannot open the required file
        // Parameters:
        //  FILTER  the filter name
        //  FILE    the file that could not be opened
        //  ERROR   the error message
    $aMessages[MSG_FILTER_OPEN_FILE] = 'Filter "$FILTER" cannot open file '.
                                       '"$FILE": $ERROR';
 
        // MSG_FILTER_FILE_ERROR is sent in an Alert message when a socket
        // filter gets an error message during reading a file
        // Parameters:
        //  FILTER  the filter name
        //  FILE    the file that could not be opened
        //  ERROR   the error message
        //  NLINES  the number of lines that were read successfully
    $aMessages[MSG_FILTER_FILE_ERROR] = 'Filter "$FILTER": read error on file '.
                                        '"$FILE" after $NLINES lines: $ERROR';
 
        // MSG_FILTER_READ_ERROR is sent in an Alert message when a socket
        // filter gets an error during reading from the socket
        // Parameters:
        //  FILTER  the filter name
        //  ERROR   the error message
    $aMessages[MSG_FILTER_READ_ERROR] = 'Filter "$FILTER" failed: read error: '.
                                        '$ERROR';
 
        // MSG_FILTER_NOT_OK is sent in an Alert message when a socket
        // filter fails to return the agreed __OK__ indicator
        // Parameters:
        //  FILTER  the filter name
        //  DATA    the data returned from the filter
    $aMessages[MSG_FILTER_NOT_OK] = 'Filter "$FILTER" failed (missing '.
                                    '__OK__ line): $DATA';
 
        // MSG_FILTER_UNK is sent in an Alert message
        // when an unknown filter is specified by a form
        // Parameters:
        //  FILTER  the filter name
    $aMessages[MSG_FILTER_UNK] = 'Unknown filter "$FILTER"';
 
        // MSG_FILTER_CHDIR is sent in an Alert message
        // when FormMail cannot change to the filter's directory
        // Parameters:
        //  FILTER  the filter name
        //  DIR     the directory name
        //  ERROR   an error message from the system
    $aMessages[MSG_FILTER_CHDIR] = 'Cannot chdir to "$DIR" to run filter '.
                                   '"$FILTER": $ERROR';
 
        // MSG_FILTER_NOTFOUND is sent in an Alert message
        // when FormMail cannot execute the filter
        // Parameters:
        //  FILTER  the filter name
        //  CMD     the command line being executed
        //  ERROR   an error message from the system
    $aMessages[MSG_FILTER_NOTFOUND] = 'Cannot execute filter "$FILTER" with '.
                                      'command "$CMD": $ERROR';
 
        // MSG_FILTER_ERROR is sent in an Alert message
        // when a filter returns a non-zero status
        // Parameters:
        //  FILTER  the filter name
        //  ERROR   an error message from the system
        //  STATUS  the status return from the command
    $aMessages[MSG_FILTER_ERROR] = 'Filter "$FILTER" failed (status $STATUS): '.
                                   '$ERROR';
 
        // MSG_FLD_NOTFOUND is sent as part of an Alert message
        // when a template refers to a non-existent form field
        // Parameters:
        //  FIELD   the field name
    $aMessages[MSG_FLD_NOTFOUND] = '"$FIELD" is not a field submitted from the form';
 
        // MSG_TEMPLATE_ERRORS is sent as part of an Alert message
        // when a template has generated some errors.  The message
        // should end with a new line and the actual errors are
        // output after it.
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_TEMPLATE_ERRORS] = 'Template "$NAME" caused the '.
                                      'following errors $MNUM:\n';
 
        // MSG_TEMPLATE_FAILED is sent in an Alert message
        // when processing a template has failed.
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_TEMPLATE_FAILED] = 'Failed to process template "$NAME"';
 
        // MSG_MIME_PREAMBLE is sent in the preamble of MIME emails
        // Parameters: none
    $aMessages[MSG_MIME_PREAMBLE] = '(Your mail reader should not show this '.
                                    'text.\nIf it does you may need to '.
                                    'upgrade to more modern software.)';
 
        // MSG_MIME_HTML is sent in the preamble of HTML emails
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_MIME_HTML] = 'This message has been generated by FormMail '.
                                'using an HTML template\ncalled "$NAME". The '.
                                'raw text of the form results\nhas been '.
                                'included below, but your mail reader should '.
                                'display the HTML\nversion only (unless it\'s '.
                                'not capable of doing so).';
 
        // MSG_FILE_OPEN_ERROR is sent in an Alert message when FormMail
        // cannot open a file
        // Parameters:
        //  NAME    the file name
        //  TYPE    the type of file
        //  ERROR   the system error message
    $aMessages[MSG_FILE_OPEN_ERROR] = 'Failed to open $TYPE file "$NAME": $ERROR';
 
        // MSG_ATTACH_DATA is sent in an Alert message when the file
        // attachment through 'data' has gone wrong.
        // Parameters: none
    $aMessages[MSG_ATTACH_DATA] = 'Internal error: AttachFile requires '.
                                  '"tmp_name" or "data"';
 
        // MSG_PHP_HTML_TEMPLATES is sent in an Alert message when an
        // HTML template is used but the PHP version is too old.
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_HTML_TEMPLATES] = 'HTMLTemplate option is only supported '.
                                     'with PHP version 4.0.5 or above.  Your '.
                                     'server is running version $PHPVERS.';
 
        // MSG_PHP_FILE_UPLOADS is sent in an Alert message when
        // file upload is used but the PHP version is too old.
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_FILE_UPLOADS] = 'For security reasons, file upload is only '.
                                   'allowed with PHP version 4.0.3 or above. '.
                                   'Your server is running version $PHPVERS.';
 
        // MSG_FILE_UPLOAD is sent in an Alert message when
        // file upload is attempted but FormMail is not configured to allow
        // it
        // Parameters: none
    $aMessages[MSG_FILE_UPLOAD] = 'File upload attempt ignored';
 
        // MSG_FILE_UPLOAD_ATTACK is sent in an Alert message when
        // possible file upload attack is detected
        // Parameters:
        //  NAME    file name
        //  TEMP    temporary file name
        //  FLD     name of the file upload field
    $aMessages[MSG_FILE_UPLOAD_ATTACK] = 'Possible file upload attack '.
                                         'detected: field="$FLD", name="$NAME" '.
                                         'temp name="$TEMP"';
 
        // MSG_PHP_PLAIN_TEMPLATES is sent in an Alert message when a
        // Plain template is used but the PHP version is too old.
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_PLAIN_TEMPLATES] = 'PlainTemplate option is only supported '.
                                     'with PHP version 4.0.5 or above.  Your '.
                                     'server is running version $PHPVERS.';
 
        // MSG_ATTACH_NAME is sent in an Alert message when a
        // the form uses the Attach feature without specifying a file name
        // Parameters: none
    $aMessages[MSG_ATTACH_NAME] = 'filter_options: Attach must contain a name '.
                                  '(e.g. Attach=data.txt)';
 
        // MSG_PHP_BCC is sent in an Alert message when a
        // the form uses the BCC feature and the PHP version may not support it
        // Parameters:
        //  $PHPVERS    the current PHP version
    $aMessages[MSG_PHP_BCC] = 'Warning: BCC is probably not supported on your '.
                              'PHP version ($PHPVERS)';
 
        // MSG_CSVCOLUMNS is sent in an Alert message when a csvcolumns field
        // is not correct
        // Parameters:
        //  $VALUE  the csvcolumns field value
    $aMessages[MSG_CSVCOLUMNS] = 'The "csvcolumns" setting is not '.
                                 'valid: "$VALUE"';
 
        // MSG_CSVFILE is sent in an Alert message when a csvfile field
        // is not correct
        // Parameters:
        //  $VALUE  the csvfile field value
    $aMessages[MSG_CSVFILE] = 'The "csvfile" setting is not valid: "$VALUE"';
 
        // MSG_TARG_EMAIL_PAT_START is sent in an Alert message when a
        // $TARGET_EMAIL pattern is insecure because of a missing '^'
        // at the beginning
        // Parameters:
        //  $PAT    the pattern
    $aMessages[MSG_TARG_EMAIL_PAT_START] = 'Warning: Your TARGET_EMAIL pattern '.
                                           '"$PAT" is missing a ^ at the '.
                                           'beginning.';
 
        // MSG_TARG_EMAIL_PAT_END is sent in an Alert message when a
        // $TARGET_EMAIL pattern is insecure because of a missing '$'
        // at the end
        // Parameters:
        //  $PAT    the pattern
    $aMessages[MSG_TARG_EMAIL_PAT_END] = 'Warning: Your TARGET_EMAIL pattern '.
                                         '"$PAT" is missing a $ at the end.';
 
        // MSG_CONFIG_WARN is sent in an Alert message when the FormMail
        // configuration may have some problems.  The messages are
        // passed on separate lines, so the line terminations below
        // are important.
        // Parameters:
        //  $MESGS  lines of messages
    $aMessages[MSG_CONFIG_WARN] = 'The following potential problems were found '.
                                  'in your configuration:\n$MESGS\n\n'.
                                  'These are not necessarily errors, but you '.
                                  'should review the documentation\n'.
                                  'inside formmail.php.  If you are sure your '.
                                  'configuration is correct\n'.
                                  'you can disable the above messages by '.
                                  'changing the CONFIG_CHECK settings.';
 
        // MSG_PHP_AUTORESP is sent in an Alert message when the PHP version
        // does not support autoresponding
        // Parameters:
        //  $PHPVERS    current PHP version
    $aMessages[MSG_PHP_AUTORESP] = 'Autorespond is only supported with PHP '.
                                   'version 4.0.5 or above.  Your server is '.
                                   'running version $PHPVERS.';
 
        // MSG_ALERT is the test alert message (formmail.php?testalert=1)
        // Parameters:
        //  $LANG               the language ID
        //  $PHPVERS            PHP version
        //  $FM_VERS            FormMail version
        //  $SERVER             server type
        //  $DOCUMENT_ROOT      PHP's DOCUMENT_ROOT value
        //  $SCRIPT_FILENAME    PHP's SCRIPT_FILENAME value
        //  $PATH_TRANSLATED    PHP's PATH_TRANSLATED value
        //  $REAL_DOCUMENT_ROOT the REAL_DOCUMENT_ROOT value
    $aMessages[MSG_ALERT] = 'This is a test alert message $MNUM\n'.
                            'Loaded language is $LANG\n'.
                            'PHP version is $PHPVERS\n'.
                            'FormMail version is $FM_VERS\n'.
                            'Server type: $SERVER\n'.
                            '\n'.
                            'DOCUMENT_ROOT: $DOCUMENT_ROOT\n'.
                            'SCRIPT_FILENAME: $SCRIPT_FILENAME\n'.
                            'PATH_TRANSLATED: $PATH_TRANSLATED\n'.
                            'REAL_DOCUMENT_ROOT: $REAL_DOCUMENT_ROOT';
 
        // MSG_NO_DEF_ALERT is displayed if you use the testalert feature
        // and no DEF_ALERT setting has been provided.
        // Parameters: none
    $aMessages[MSG_NO_DEF_ALERT] = 'No DEF_ALERT value has been set.';
 
        // MSG_TEST_SENT is displayed if when use the testalert feature
        // Parameters: none
    $aMessages[MSG_TEST_SENT] = 'Test message sent.  Check your email.';
 
        // MSG_TEST_FAILED is displayed if when use the testalert feature
        // and the mail sending fails.
        // Parameters: none
    $aMessages[MSG_TEST_FAILED] = 'FAILED to send alert message.  Check your '.
                                  'server error logs.';
 
        // MSG_NO_DATA_PAGE is the page that's displayed if the user
        // just opens the URL to FormMail directly.
        // Parameters: none
    $aMessages[MSG_NO_DATA_PAGE] =  'This URL is a Form submission program.\n'.
                                    'It appears the form is not working '.
                                    'correctly as there was no data found.\n'.
                                    'You\'re not supposed to browse to this '.
                                    'URL; it should be accessed from a form.';
 
        // MSG_REQD_ERROR is displayed to the user as a default error
        // message when they haven't supplied some required fields
        // Parameters: none
    $aMessages[MSG_REQD_ERROR] = 'The form required some values that you '.
                                 'did not seem to provide.';
 
        // MSG_COND_ERROR is displayed to the user as a default error
        // message when some form conditions have failed
        // Parameters: none
    $aMessages[MSG_COND_ERROR] = 'Some of the values you provided are not valid.';
 
        // MSG_CRM_FAILURE is displayed to the user when submission
        // to the CRM has failed.
        // Parameters:
        //      $URL    the URL that was used
        //      $DATA   data returned from the CRM
    $aMessages[MSG_CRM_FAILURE] = 'The form submission did not succeed due to '.
                                  'a CRM failure. URL was \'$URL\'. '.
                                  'Returned CRM data:\n$DATA';
 
        // MSG_FOPTION_WARN is sent in an Alert message when the form
        // uses the superseded SendMailFOption feature
        // Parameters:
        //  $LINE   line number for SENDMAIL_F_OPTION
    $aMessages[MSG_FOPTION_WARN] = 'Warning: You\'ve used SendMailFOption in '.
                                   '"mail_options" in your form. This has been '.
                                   'superseded with a configuration setting '.
                                   'inside formmail.php.  Please update your '.
                                   'formmail.php configuration (look for '.
                                   'SENDMAIL_F_OPTION on line $LINE) and set '.
                                   'it to "true", then remove SendMailFOption '.
                                   'from your form(s).';
 
        // MSG_NO_ACTIONS is sent in an Alert message when there is no
        // action to perform or email address to send to
        // Parameters: none
    $aMessages[MSG_NO_ACTIONS] = 'The form has an internal error - no actions '.
                                 'or recipients were specified.';
 
        // MSG_NO_RECIP is sent in an Alert message when there are no
        // valid recipients to send to
        // Parameters: none
    $aMessages[MSG_NO_RECIP] = 'The form has an internal error - no valid '.
                               'recipients were specified.';
 
        // MSG_INV_EMAIL is sent in an Alert message when there are errors
        // in the email addresses specified in the form
        // Parameters:
        //  $ERRORS     list of errors
    $aMessages[MSG_INV_EMAIL] = 'Invalid email addresses were specified '.
                                'in the form $MNUM:\n$ERRORS';
 
        // MSG_FAILED_SEND is sent in an Alert message when the mail sending fails.
        // Parameters: none
    $aMessages[MSG_FAILED_SEND] = 'Failed to send email';
 
        // MSG_ARESP_EMAIL is sent in an Alert message when
        // no email address has been specified for an autoreponse
        // Parameters: none
    $aMessages[MSG_ARESP_EMAIL] = 'No "email" field was found. Autorespond '.
                                  'requires the submitter\'s email address.';
 
        // MSG_ARESP_SUBJ is the default subject for the auto response email
        // Parameters: none
    $aMessages[MSG_ARESP_SUBJ] = 'Your form submission';
 
        // MSG_LOG_NO_VERIMG is written to the auto respond log file
        // if no VerifyImgString session variable was found
        // Parameters: none
    $aMessages[MSG_LOG_NO_VERIMG] = 'No VerifyImgString in session';
 
        // MSG_ARESP_NO_AUTH is shown to the user
        // if no VerifyImgString session variable was found
        // Parameters: none
    $aMessages[MSG_ARESP_NO_AUTH] = 'Failed to obtain authorization to send '.
                                    'you email. This is probably a fault on '.
                                    'the server.';
 
        // MSG_LOG_NO_MATCH is written to the auto respond log file
        // if the user's entry did not match the image verification
        // Parameters: none
    $aMessages[MSG_LOG_NO_MATCH] = 'User did not match image';
 
        // MSG_ARESP_NO_MATCH is shown to the user
        // if the user's entry did not match the image verification
        // Parameters: none
    $aMessages[MSG_ARESP_NO_MATCH] = 'Your entry did not match the image';
 
        // MSG_LOG_FAILED is written to the auto respond log file
        // if the autoresponding failed
        // Parameters: none
    $aMessages[MSG_LOG_FAILED] = 'Failed';
 
        // MSG_ARESP_FAILED is sent in an Alert message
        // if the autoresponding failed
        // Parameters: none
    $aMessages[MSG_ARESP_FAILED] = 'Autoresponder failed';
 
        // MSG_LOG_OK is written to the auto respond log file
        // if the autoresponding succeeded
        // Parameters: none
    $aMessages[MSG_LOG_OK] = 'OK';
 
        // MSG_THANKS_PAGE is the default page that's displayed if the
        // submission is successful
        // Parameters: none
    $aMessages[MSG_THANKS_PAGE] = 'Thanks!  We\'ve received your information '.
                                  'and, if it\'s appropriate, we\'ll be in '.
                                  'contact with you soon.';
 
        // MSG_LOAD_MODULE is sent in an alert message if a module
        // could not be loaded.
        // Parameters:
        //  $FILE    the file name
        //  $ERROR   the error message
    $aMessages[MSG_LOAD_MODULE] = 'Cannot load module from file \'$FILE\': $ERROR';
 
        // MSG_LOAD_FMCOMPUTE is sent in an alert message if the form
        // specifies at least one "fmcompute" field and the FMCompute
        // module cannot be loaded.
        // Parameters:
        //  $FILE    the file name
        //  $ERROR   the error message
    $aMessages[MSG_LOAD_FMCOMPUTE] = 'Cannot load FMCompute module from file '.
                                        '\'$FILE\': $ERROR';
 
        // MSG_REGISTER_MODULE is sent in an alert message if a module
        // could not register with FMCompute
        // Parameters:
        //  $NAME    the name of the module
        //  $ERROR   the error message
    $aMessages[MSG_REGISTER_MODULE] = 'Cannot register module $NAME with '.
                                        'FMCompute: $ERROR';
 
 
        // MSG_COMP_PARSE is sent in an alert message if a parse error
        // occurs in an fmcompute field
        // Parameters:
        //  $CODE    the code with an error
        //  $ERRORS  the error messages
    $aMessages[MSG_COMP_PARSE] = 'These parse errors occurred in the following '.
                                    'code:\n$ERRORS\n$CODE';
 
        // MSG_COMP_REG_DATA is sent in an alert message if FormMail cannot
        // register a data field with the FMCompute module
        // Parameters:
        //  $NAME    the field name
        //  $ERROR  the error message
    $aMessages[MSG_COMP_REG_DATA] = 'Failed to register data field \'$NAME\': '.
                                    '$ERROR';
 
        // MSG_COMP_ALERT is sent in an alert message if the FMCompute
        // module has generated some alert messages.
        // Parameters:
        //  $ALERTS  the alerts
    $aMessages[MSG_COMP_ALERT] = 'The following alert messages were reported '.
                                'from the FMCompute module: $ALERTS';
 
        // MSG_COMP_DEBUG is sent in an alert message if the FMCompute
        // module has generated some debug messages.
        // Parameters:
        //  $DEBUG  the alerts
    $aMessages[MSG_COMP_DEBUG] = 'The following debug messages were reported '.
                                'from the FMCompute module: $DEBUG';
 
        // MSG_COMP_EXEC is sent in an alert message if the FMCompute
        // module has generated some error messages during execution
        // Parameters:
        //  $ERRORS  the errors
    $aMessages[MSG_COMP_EXEC] = 'The following error messages were reported '.
                                'from the FMCompute module: $ERRORS';
 
        // MSG_TEMPL_ALERT is sent in an alert message if Advanced Template
        // Processing has generated some alert messages.
        // Parameters:
        //  $ALERTS  the alerts
    $aMessages[MSG_TEMPL_ALERT] = 'The following alert messages were reported '.
                                'from the Advanced Template Processor: $ALERTS';
 
        // MSG_TEMPL_DEBUG is sent in an alert message if Advanced Template
        // Processing has generated some debug messages.
        // Parameters:
        //  $DEBUG  the alerts
    $aMessages[MSG_TEMPL_DEBUG] = 'The following debug messages were reported '.
                                'from the Advanced Template Processor: $DEBUG';
 
        // MSG_TEMPL_PROC is sent in an alert message if Advanced Template Processing
        // has generated some error messages during processing
        // Parameters:
        //  $ERRORS  the errors
    $aMessages[MSG_TEMPL_PROC] = 'The following error messages were reported '.
                                'from the Advanced Template Processor: $ERRORS';
 
        // MSG_REG_FMCOMPUTE is sent in an Alert message when FormMail
        // cannot register an external function with FMCompute.
        // Parameters:
        //  FUNC    the function that could not be registered
        //  ERROR   the error message
    $aMessages[MSG_REG_FMCOMPUTE] = 'Cannot register function "$FUNC" with '.
                                    'FMCompute: $ERROR';
 
 
        // MSG_USER_ERRORS is shown as part of a user error when an FMCompute
        // has called the "UserError" function one or more times.
        // Parameters:
        //  NONE
    $aMessages[MSG_USER_ERRORS] = 'One or more errors occurred in your form submission';
 
 
        // MSG_CALL_PARAM_COUNT is sent in an alert when a call to a FormMail
        // function from FMCompute has the wrong number of parameters
        // Parameters:
        //  FUNC    the function name
        //  COUNT   the actual number of parameters passed
    $aMessages[MSG_CALL_PARAM_COUNT] = 'FMCompute called FormMail function '.
                                       '\'$FUNC\' with wrong number of '.
                                       'parameters: $COUNT';
 
        // MSG_CALL_UNK_FUNC is sent in an alert when FMCompute calls an
        // unknown FormMail function
        // Parameters:
        //  FUNC    the function name
    $aMessages[MSG_CALL_UNK_FUNC] = 'FMCompute called unknown FormMail function '.
                                       '\'$FUNC\'';
 
        // MSG_SAVE_FILE is sent in an alert when saving a file to
        // the server has failed
        // Parameters:
        //  FILE    the source file name (usually a temporary file name)
        //  DEST    the destination file name
        //  ERR     the error message
    $aMessages[MSG_SAVE_FILE] = 'Failed to save file \'$FILE\' to \'$DEST\': $ERR';
 
        // MSG_SAVE_FILE_EXISTS is sent as part of an alert when saving a file to
        // the repository ($FILE_REPOSITORY) has failed because the file
        // already exists and FILE_OVERWRITE is set to false.
        // Parameters:
        //  FILE    the destination file name
    $aMessages[MSG_SAVE_FILE_EXISTS] = 'Cannot save file to repository as this would '.
                                        'overwrite \'$FILE\' and you have '.
                                        'set FILE_OVERWRITE to false.';
 
        // MSG_EMPTY_ADDRESSES is sent as part of an alert when a number of empty
        // email addresses have been specified in recipients, cc, or bcc
        // *and* there are no valid addresses provided
        // in the list
        // Parameters:
        //  COUNT    the number of empty addresses
    $aMessages[MSG_EMPTY_ADDRESSES] = '$COUNT empty addresses';
 
        // MSG_CHMOD is sent in an alert when changing the protection
        // mode of a file to has failed
        // Parameters:
        //  FILE    the file name
        //  MODE    the mode
        //  ERR     the error message
    $aMessages[MSG_CHMOD] = 'Failed to change protection mode of file \'$FILE\' '.
                            'to $MODE: $ERR';
 
        // MSG_VERIFY_MISSING is shown to the user image verification string
        // was not found
        // Parameters: none
    $aMessages[MSG_VERIFY_MISSING] = 'Image verification string missing. This'.
                                     ' is probably a fault on the server.';
 
        // MSG_VERIFY_MATCH is shown to the user
        // if the user's entry did not match the image verification for the
        // imgverify option
        // Parameters: none
    $aMessages[MSG_VERIFY_MATCH] = 'Your entry did not match the image';
 
        // MSG_FILE_NAMES_INVALID is sent in an Alert message when
        // a form's file_names setting has errors
        // Parameters: none
        // A list of errors is appended on separate lines
    $aMessages[MSG_FILE_NAMES_INVALID] = 'Some file_names specifications are invalid $MNUM:\n';
 
        // MSG_FILE_NAMES_NOT_FILE is sent in an Alert message when
        // a form's file_names setting refers to a file field that doesn't
        // exist
        // Parameters:
        //      NAME    the name of the file field that doesn't exist
    $aMessages[MSG_FILE_NAMES_NOT_FILE] = 'Your file_names specification has '.
                                          'an error. \'$NAME\' is not the name '.
                                          'of a file upload field\n';
 
        // MSG_NEXT_PLUS_GOOD is sent in an alert message if the form is
        // ambiguous and specifies both "next_form" and "good_url" or
        // "good_template"
        // Parameters:
        //  $WHICH  the "good_" field that was specified
    $aMessages[MSG_NEXT_PLUS_GOOD] = 'The form has specified both "next_form" '.
                                    'and "$WHICH" fields - the action to '.
                                    'to perform is ambiguous';
 
        // MSG_MULTIFORM is sent in an Alert message when a form tries
        // to use a multi-form template, but templates have not been configured in
        // formmail.php
        // Parameters: none
    $aMessages[MSG_MULTIFORM] = 'You must set either MULTIFORMDIR or MULTIFORMURL '.
                                'in formmail.php before you can use '.
                                'multi-page forms.';
 
        // MSG_MULTIFORM_FAILED is sent in an Alert message
        // when processing a multi-page form template has failed.
        // Parameters:
        //  NAME    the template name
    $aMessages[MSG_MULTIFORM_FAILED] = 'Failed to process multi-page form template "$NAME"';
 
        // MSG_NEED_THIS_FORM is sent in an Alert message
        // when a multi-page form does not specify the "this_form" field.
        // Parameters:
        //  none
    $aMessages[MSG_NEED_THIS_FORM] = 'Multi-page forms require "this_form" field';
 
        // MSG_NO_PHP_SELF is sent in an Alert message
        // when FormMail requires the "PHP_SELF" server variable and PHP is not
        // providing it.
        // Parameters:
        //  none
    $aMessages[MSG_NO_PHP_SELF] = 'PHP on the server is not providing "PHP_SELF"';
 
        // MSG_RETURN_URL_INVALID is sent in an Alert message
        // when "this_form" is not a valid return URL.  This occurs for
        // multi-page forms.
        // Parameters:
        //  URL     the invalid URL
    $aMessages[MSG_RETURN_URL_INVALID] = 'Return URL "$URL" is not valid';
 
        // MSG_GO_BACK is sent in an Alert message
        // when "multi_go_back" has been submitted but this isn't part of a
        // multi-page form.
        // Parameters:
        //  none
    $aMessages[MSG_GO_BACK] = 'Cannot "go back" if not in a multi-page form '.
                              'sequence or at the first page of the form '.
                              'sequence';
 
        // MSG_OPEN_URL is sent in an Alert message when a URL cannot
        // be opened.
        // Parameters:
        //  URL     the invalid URL
        //  ERROR   error message
    $aMessages[MSG_OPEN_URL] = 'Cannot open URL "$URL": $ERROR';
 
        // MSG_CANNOT_RETURN is sent in an Alert message when an invalid return
        // request is made in a multi-page form sequence.
        // Parameters:
        //  TO          the requested page index
        //  TOPINDEX    the top page index
    $aMessages[MSG_CANNOT_RETURN] = 'Cannot return to page $TO.  The top page '.
                                    'index is $TOPINDEX';
 
        // MSG_ATTACK_DETECTED is sent in an Alert message when an attack on
        // the server has been detected
        // Parameters:
        //  ATTACK      name or description of the attack
        //  INFO        more information about the attack
    $aMessages[MSG_ATTACK_DETECTED] = 'Server attack "$ATTACK" detected. '.
                                      'Your server is safe as FormMail is '.
                                      'invulnerable to this attack.  You can '.
                                      'disable these messages by setting '.
                                      'ALERT_ON_ATTACK_DETECTION to false '.
                                      'in FormMail\'s configuration section.'.
                                      '\nMore information:\n$INFO';
 
        // MSG_ATTACK_PAGE is the contents of the browser page displayed to the
        // user when an attack is detected
        // Parameters:
        //  none
    $aMessages[MSG_ATTACK_PAGE] = 'Your form submission has been rejected '.
                                  'as it appears to be an abuse of our server. '.
                                  'For more information about this error, visit '.
                                  '<a href="http://www.tectite.com/serverabuse.php" '.
                                  ' target="_blank">'.
                                  'www.tectite.com/serverabuse.php</a>.';
 
        // MSG_ATTACK_MIME_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the MIME attack
        // Parameters:
        //  FLD     name of the field
        //  CONTENT the invalid content found in the field
    $aMessages[MSG_ATTACK_MIME_INFO] = 'The field "$FLD" contained invalid '.
                                       'content "$CONTENT"';
 
        // MSG_ATTACK_DUP_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Duplicate Data attack
        // Parameters:
        //  FLD1     name of the first field
        //  FLD2     name of the second field
    $aMessages[MSG_ATTACK_DUP_INFO] = 'The fields "$FLD1" and "$FLD2" contained '.
                                      'duplicate data';
 
        // MSG_ATTACK_SPEC_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Special Field attack
        // Parameters:
        //  FLD     name of the special field
    $aMessages[MSG_ATTACK_SPEC_INFO] = 'Special field "$FLD" contained an email address';
 
        // MSG_ATTACK_MANYURL_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Many URLs attack
        // Parameters:
        //  FLD     name of the field
        //  NUM     number of URLs detected
    $aMessages[MSG_ATTACK_MANYURL_INFO] = 'Field "$FLD" contained $NUM URLs';
 
        // MSG_ATTACK_MANYFIELDS_INFO is the contents of the INFO parameter
        // to the MSG_ATTACK_DETECTED message for the Many Fields with URLs
        // attack
        // Parameters:
        //  NUM     number of fields detected with URLs
        //  FLDS    list of fields with URLs in them
    $aMessages[MSG_ATTACK_MANYFIELDS_INFO] = '$NUM fields contained URLs: $FLDS';
 
 
        // MSG_NEED_SCRATCH_PAD is an alert message when processing requires
        // SCRATCH_PAD configuration for file upload processing.  This occurs
        // when you upload files in pages of a multi page form sequence.
        // Parameters:
        //  none
    $aMessages[MSG_NEED_SCRATCH_PAD] = 'You need to set SCRATCH_PAD in the '.
                                        'configuration section to process '.
                                        'uploaded files.';
 
        // MSG_OPEN_SCRATCH_PAD is an alert message when the SCRATCH_PAD
        // directory cannot be opened for cleanup.
        // Parameters:
        //  DIR     name of the directory
        //  ERR     more error information
    $aMessages[MSG_OPEN_SCRATCH_PAD] = 'Cannot open SCRATCH_PAD directory '.
                                        '"$DIR".  Open failed: $ERR';
 
        // MSG_NO_NEXT_NUM_FILE is an alert message when a form tries to
        // use the %nextnum% derivation feature but you haven't
        // setup FormMail's configuration correctly.
        // Parameters:
        //  none
    $aMessages[MSG_NO_NEXT_NUM_FILE] = 'You cannot use the %nextnum% feature: '.
                                        'you have not configured NEXT_NUM_FILE';
 
        // MSG_NEXT_NUM_FILE is an alert message when a form tries to
        // use the %nextnum% derivation feature but the next number file cannot
        // be processed.
        // Parameters:
        //  FILE    name of the file
        //  ACT     action
        //  ERR     more error information
    $aMessages[MSG_NEXT_NUM_FILE] = 'Cannot $ACT next number file '.
                                            '\'$FILE\': $ERR';
 
        // MSG_MULTI_UPLOAD is an alert message when processing of uploaded
        // fails during a multi-page form sequence
        // Parameters:
        //  none
    $aMessages[MSG_MULTI_UPLOAD] = 'File upload processing failed during '.
                                    'multi-page form processing.';
 
        // MSG_URL_PARSE is an error message when a URL to be opened
        // cannot be parsed
        // Parameters:
        //  none
    $aMessages[MSG_URL_PARSE] = 'Failed to parse URL';
 
        // MSG_URL_SCHEME is an error message when a URL to be opened
        // has an unsupported "scheme" value
        // Parameters:
        //  SCHEME     the scheme that was seen
    $aMessages[MSG_URL_SCHEME] = 'Unsupported URL scheme "$SCHEME"';
 
        // MSG_SOCKET is an error message when opening a socket for a URL
        // fails
        // Parameters:
        //  ERRNO     the error code
        //  ERRSTR    the error string
        //  PHPERR    the value of $php_errormsg
    $aMessages[MSG_SOCKET] = 'Socket error $ERRNO: $ERRSTR: $PHPERR';
 
        // MSG_GETURL_OPEN is an error message when the web server reports
        // a failure on opening a URL
        // Parameters:
        //  STATUS     the HTTP status value (number + string)
    $aMessages[MSG_GETURL_OPEN] = 'Open URL failed: $STATUS';
 
        // MSG_FILE_UPLOAD_ERRn are the error messages corresponding to the
        // PHP file upload error code n.
        // Parameters:
        //  none
    $aMessages[MSG_FILE_UPLOAD_ERR1] = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
    $aMessages[MSG_FILE_UPLOAD_ERR2] = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.';
    $aMessages[MSG_FILE_UPLOAD_ERR3] = 'The uploaded file was only partially uploaded.';
    $aMessages[MSG_FILE_UPLOAD_ERR4] = 'No file was uploaded.';
    $aMessages[MSG_FILE_UPLOAD_ERR6] = 'Missing a temporary folder.';
    $aMessages[MSG_FILE_UPLOAD_ERR7] = 'Failed to write file to disk.';
 
    $aMessages[MSG_FILE_UPLOAD_ERR8] = 'File upload stopped by extension.';
 
        // MSG_FILE_UPLOAD_ERR_UNK is displayed when an unknown error code
        // is provided by PHP for a file upload
        // Parameters:
        //  ERRNO   the error code
    $aMessages[MSG_FILE_UPLOAD_ERR_UNK] = 'Unknown file upload error code $ERRNO';
 
        // MSG_FILE_UPLOAD_SIZE is displayed when an uploaded file exceeds
        // the configured maximum size
        // Parameters:
        //  NAME   the uploaded file's name
        //  SIZE   the size of the uploaded file
        //  MAX    the maximum size that was exceeded
    $aMessages[MSG_FILE_UPLOAD_SIZE] = 'Uploaded file "$NAME" is too big ('.
                                        '$SIZE bytes). The maximum permitted '.
                                        'size is $MAX kilobytes.';
 
        // MSG_DER_FUNC_ERROR is sent in an Alert message when
        // a form uses a derive_fields function that's
        // formatted incorrectly
        // Parameters:
        //  $SPEC   the invalid value specification
        //  $MSG    a message describing the error or providing an example
    $aMessages[MSG_DER_FUNC_ERROR] = 'derive_fields: invalid function specification '.
                                     '"$SPEC": $MSG';
 
        // MSG_DER_FUNC_SIZE_FMT describes the right syntax for the "size" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_SIZE_FMT] = '"size" function requires this format: '.
                                    'size(file_field)';
 
        // MSG_DER_FUNC_IF_FMT describes the right syntax for the "if" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_IF_FMT] = '"if" function requires this format: '.
                                    'if(field;spec;spec)';
 
        // MSG_DER_FUNC_NEXTNUM_FMT describes the right syntax for the "nextnum" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_NEXTNUM_FMT] = '"nextnum" function requires this format: '.
                                    'nextnum(pad) or nextnum(pad;base).  pad and base '.
                                    'must be numbers. base must be 2 to 36 inclusive';
 
        // MSG_DER_FUNC_EXT_FMT describes the right syntax for the "ext" function
        // Parameters:
        //  none
    $aMessages[MSG_DER_FUNC_EXT_FMT] = '"ext" function requires this format: '.
                                    'ext(file_field)';
 
        // MSG_DER_FUNC1_FMT describes the right syntax for a function
        // requiring one parameter
        // Parameters:
        //  FUNC    name of the function
    $aMessages[MSG_DER_FUNC1_FMT] = '"$FUNC" function requires this format: '.
                                    '$FUNC(fieldname)';
 
}  // <A NAME="BuiltinMessages"> Jump to: <A HREF="#MessageNumbers">
 
    //
    // Load the default language, and then override with an optional language file.
    //
function LoadLanguage()
{
    LoadBuiltinLanguage();
    LoadLanguageFile();
}
 
    //
    // To return the value of a string or empty string if not set.
    //
function CheckString($ss)
{
    return (isset($ss) ? $ss : "");
}
 
$aGetMessageSubstituteErrors = array();
$aGetMessageSubstituteFound = array();
$bGetMessageSubstituteNoErrors = false;
 
    //
    // Worker function for GetMessage's preg_replace_callback calls.
    // Returns the value of the matched variable name.
    // Variables are searched for in the global $aGetMessageValues.
    // If no such variable exists, an empty string is returned and the
    // global variable $aGetMessageSubstituteErrors lists the missing names.
    //
function GetMessageSubstituteParam($a_matches)
{
    global  $aGetMessageValues,$aGetMessageSubstituteErrors;
    global  $aGetMessageSubstituteFound,$bGetMessageSubstituteNoErrors;
 
    $s_name = $a_matches[1];
    $aGetMessageSubstituteFound[] = $s_name;
    $s_value = "";
    if (isset($aGetMessageValues[$s_name]))
        $s_value = $aGetMessageValues[$s_name];
    elseif ($bGetMessageSubstituteNoErrors)
        $s_value = '$'.$s_name;
    else
        $aGetMessageSubstituteErrors[] = $s_name;
    return ($s_value);
}
 
    //
    // Returns message text from a message number, with optional parameters.
    //
function GetMessage($i_msg_num,$a_params = array(),
                        $b_show_mnum = true,$b_no_errors = false)
{
    global  $aMessages,$sLangID,$bShowMesgNumbers;
 
    if (!isset($aMessages[$i_msg_num]))
    {
        SendAlert("Unknown Message Number $i_msg_num was used",false,true);
        $s_text = "<UNKNOWN MESSAGE NUMBER>";
    }
    else
        $s_text = $aMessages[$i_msg_num];
    $s_mno = $bShowMesgNumbers ? "[M$i_msg_num]" : "";
 
    $s_orig_text = $s_text;
        //
        // substitute parameters; only works with PHP version 4.0.5 or later
        //
    if (strpos($s_text,'$') !== false)
    {
        global  $aGetMessageValues,$aGetMessageSubstituteErrors;
        global  $aGetMessageSubstituteFound,$bGetMessageSubstituteNoErrors;
 
        $aGetMessageSubstituteErrors = array();
        $aGetMessageSubstituteFound = array();
        $aGetMessageValues = $a_params;
        $bGetMessageSubstituteNoErrors = $b_no_errors;
        $aGetMessageValues["MNUM"] = $s_mno;    // add the message number
            //
            // search for words in this form:
            //      $word
            // where word begins with an alphabetic character and
            // consists of alphanumeric and underscore
            //
        $s_text = preg_replace_callback('/\$([a-z][a-z0-9_]*)/i',
                                            'GetMessageSubstituteParam',$s_text);
        if (count($aGetMessageSubstituteErrors) > 0)
            SendAlert("Message Number $i_msg_num ('$s_orig_text') in language $sLangID ".
                        "specified the following unsupported parameters: ".
                        implode(',',$aGetMessageSubstituteErrors));
        if (!in_array("MNUM",$aGetMessageSubstituteFound))
                //
                // append the message number
                //
            $s_text .= $b_show_mnum ? " $s_mno" : "";
    }
    else
            //
            // append the message number
            //
        $s_text .= $b_show_mnum ? " $s_mno" : "";
        //
        // replace '\n' sequences with new lines
        //
    return (str_replace('\n',"\n",$s_text));
}
 
    //
    // Check for old version of PHP - die if too old.
    //
function IsOldVersion(&$a_this_version)
{
    $a_modern = array(4,1,0);   // versions prior to this are "old" - "4.1.0"
    $s_req_string = "4.0.5";    // version 4.0.5 of PHP is required from
                                // FormMail 5.00 onward (because we use
                                // preg_replace_callback for all messages to
                                // support languages other than English)
    $a_too_old = explode(".",$s_req_string);
 
    $i_cannot_use = ($a_too_old[0] * 10000) +
                    ($a_too_old[1] * 100) +
                    $a_too_old[2];
 
    $s_vers_string = phpversion();
    $a_this_version = explode(".",$s_vers_string);
    $i_this_num = ($a_this_version[0] * 10000) +
                    ($a_this_version[1] * 100) +
                    $a_this_version[2];
 
    if ($i_this_num <= $i_cannot_use)
        die(GetMessage(MSG_SCRIPT_VERSION,array("PHPREQ"=>$s_req_string,
                                                "PHPVERS"=>$s_vers_string)));
    $i_modern_num = ($a_modern[0] * 10000) +
                    ($a_modern[1] * 100) +
                    $a_modern[2];
    return ($i_this_num < $i_modern_num);
}
 
    //
    // Check if the server is Windows
    //
function IsServerWindows()
{
    static  $bGotAnswer = false;
    static  $bAnswer;
 
    if (!$bGotAnswer)
    {
        if ((isset($_ENV["OS"]) && stristr($_ENV["OS"],"windows") !== false) ||
            (isset($_SERVER["PATH"]) && stristr($_SERVER["PATH"],"winnt") !== false) ||
            (isset($_SERVER["PATH"]) && stristr($_SERVER["PATH"],"windows") !== false) ||
            (isset($_SERVER["SystemRoot"]) && stristr($_SERVER["SystemRoot"],"winnt") !== false) ||
            (isset($_ENV["SystemRoot"]) && stristr($_ENV["SystemRoot"],"winnt") !== false) ||
            (isset($_SERVER["SystemRoot"]) && stristr($_SERVER["SystemRoot"],"windows") !== false) ||
            (isset($_ENV["SystemRoot"]) && stristr($_ENV["SystemRoot"],"windows") !== false) ||
            (isset($_SERVER["Path"]) && stristr($_SERVER["Path"],"windows") !== false))
            $bAnswer = true;
        else
            $bAnswer = false;
        $bGotAnswer = true;
    }
    return ($bAnswer);
}
 
    //
    // To return a temporary file name from $SCRATCH_PAD
    //
function GetScratchPadFile($s_prefix)
{
    global  $SCRATCH_PAD;
 
    switch (substr($SCRATCH_PAD,-1))
    {
    case '/':
    case '\\':
        $s_dir = substr($SCRATCH_PAD,0,-1);
        break;
    default:
        $s_dir = $SCRATCH_PAD;
        break;
    }
        //
        // Ideally, we could use tempnam. But,
        // tempnam is system dependent and might not use the
        // SCRATCH_PAD directory even if we tell it to.
        // So, we'll force the file into SCRATCH_PAD.
        //
        // Note that we do *not* create the file, even though tempnam
        // does create it in PHP version 4.0.3 and above. (The reason is
        // we can't guarantee a non-race condition anyway.)
        //
    do
    {
        $i_rand = mt_rand(0,16777215);  // 16777215 is FFFFFF in hex
        $s_name = $SCRATCH_PAD."/".$s_prefix.sprintf("%06X",$i_rand);
    }
    while (file_exists($s_name));
    return ($s_name);
}
 
    //
    // To return a temporary file name.
    //
function GetTempName($s_prefix)
{
    global  $SCRATCH_PAD;
 
    if (isset($SCRATCH_PAD) && !empty($SCRATCH_PAD))
        $s_name = GetScratchPadFile($s_prefix);
    else
        $s_name = tempnam("/tmp",$s_prefix);
    return ($s_name);
}
 
    //
    // To find a directory on the server for temporary files.
    //
function GetTempDir()
{
    $s_name = GetTempName("fm");
    if (file_exists($s_name))
        unlink($s_name);
    $s_dir = dirname($s_name);
    return ($s_dir);
}
 
    //
    // Returns true if the PHP version is at or later than the string specified
    // (can't use "version_compare" before 4.1.0).
    //
function IsPHPAtLeast($s_vers)
{
    global  $aPHPVERSION;
 
    $a_test_version = explode(".",$s_vers);
    if (count($a_test_version) < 3)
        return (false);
    return ($aPHPVERSION[0] > $a_test_version[0] ||
            ($aPHPVERSION[0] == $a_test_version[0] &&
                ($aPHPVERSION[1] > $a_test_version[1] ||
                    $aPHPVERSION[1] == $a_test_version[1] &&
                        $aPHPVERSION[2] >= $a_test_version[2])));
}
 
define('DEBUG',false);      // for production
//define('DEBUG',true);         // for development and debugging
 
if (DEBUG)
{
    error_reporting(E_ALL);     // trap everything!
    LoadLanguage();
}
else
{
    $iOldLevel = error_reporting(E_ALL ^ E_WARNING);
    LoadLanguage();
        //
        // report everyting except warnings and notices
        //
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
}
 
function SetRealDocumentRoot()
{
    global  $aServerVars,$REAL_DOCUMENT_ROOT;
 
    if (isset($aServerVars['SCRIPT_FILENAME']))
        $REAL_DOCUMENT_ROOT = $aServerVars['SCRIPT_FILENAME'];
    elseif (isset($aServerVars['PATH_TRANSLATED']))
        $REAL_DOCUMENT_ROOT = $aServerVars['PATH_TRANSLATED'];
    else
        $REAL_DOCUMENT_ROOT = "";
        //
        // look for 'www' or 'public_html' and strip back to that if found,
        // otherwise just get the directory name
        //
    if (($i_pos = strpos($REAL_DOCUMENT_ROOT,"/www/")) !== false)
        $REAL_DOCUMENT_ROOT = substr($REAL_DOCUMENT_ROOT,0,$i_pos+4);
    elseif (($i_pos = strpos($REAL_DOCUMENT_ROOT,"/public_html/")) !== false)
        $REAL_DOCUMENT_ROOT = substr($REAL_DOCUMENT_ROOT,0,$i_pos+12);
    elseif (!empty($REAL_DOCUMENT_ROOT))
        $REAL_DOCUMENT_ROOT = dirname($REAL_DOCUMENT_ROOT);
    elseif (isset($aServerVars['DOCUMENT_ROOT']) &&
            !empty($aServerVars['DOCUMENT_ROOT']))
        $REAL_DOCUMENT_ROOT = $aServerVars['DOCUMENT_ROOT'];
}
 
    //
    // Hook system: before initialization (but after configuration)
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookpreinit.inc");
 
if (!empty($SESSION_NAME))
    session_name($SESSION_NAME);
 
session_start();
 
function ZapSession()
{
    session_destroy();
}
 
if ($bUseOldVars)
    $aSessionVars = &$HTTP_SESSION_VARS;
else
    $aSessionVars = &$_SESSION;
 
$aSessionVars["FormError"] = NULL;
unset($aSessionVars["FormError"]);                  // start with no error
$aSessionVars["FormErrorInfo"] = NULL;
unset($aSessionVars["FormErrorInfo"]);              // start with no error
$aSessionVars["FormErrorCode"] = NULL;
unset($aSessionVars["FormErrorCode"]);              // start with no error
$aSessionVars["FormErrorItems"] = NULL;
unset($aSessionVars["FormErrorItems"]);             // start with no error
$aSessionVars["FormData"] = NULL;
unset($aSessionVars["FormData"]);                   // start with no data
$aSessionVars["FormIsUserError"] = NULL;
unset($aSessionVars["FormIsUserError"]);            // start with no data
$aSessionVars["FormAlerted"] = NULL;
unset($aSessionVars["FormAlerted"]);                // start with no data
 
//
// Note that HTTP_REFERER is easily spoofed, so there's no point in
// using it for security.
//
 
    //
    // SPECIAL_FIELDS is the list of fields that formmail.php looks for to
    // control its operation
    //
$SPECIAL_FIELDS = array(
        "email",        // email address of the person who filled in the form
        "realname",     // the real name of the person who filled in the form
        "recipients",   // comma-separated list of email addresses to which we'll send the results
        "cc",           // comma-separated list of email addresses to which we'll CC the results
        "bcc",          // comma-separated list of email addresses to which we'll BCC the results
        "required",     // comma-separated list of fields that must be found in the input
        "conditions",   // complex condition tests
        "fmcompute",    // computations
        "fmmodules",    // list of modules required
        "mail_options", // comma-separated list of options
        "good_url",     // URL to go to on success
        "good_template",// template file to display on success
        "bad_url",      // URL to go to on error
        "bad_template", // template file to display on error
        "template_list_sep", // separator when expanding lists in templates
        "this_form",    // the URL of the form (can be used by bad_url)
        "subject",      // subject for the email
        "env_report",   // comma-separated list of environment variables to report
        "filter",       // a supported filter to use
        "filter_options",// options for using the filter
        "filter_fields",// list of fields to filter (default is to filter all fields)
        "logfile",      // log file to write to
        "csvfile",      // file to write CSV records to
        "csvcolumns",   // columns to save in the csvfile
        "crm_url",      // URL for sending data to the CRM; note that the
                        // value must have a valid prefix specified in TARGET_URLS
        "crm_spec",     // CRM specification (field mapping)
        "crm_options",  // comma-separated list of options to control CRM processing
        "derive_fields", // a list of fields to derive from other fields
        "file_names",   // specifies names for files being uploaded
        "autorespond",  // specification for auto-responding
        "arverify",     // verification field to allow auto-responding
        "imgverify",    // verification field to allow submission
        "multi_start",  // set this field on the first page of a multi-page form sequence
        "multi_keep",   // set this field on the pages of a multi-page form sequence
                        // to the list of fields that should be kept when moving
                        // forward after going backwards
        "next_form",    // next form name or empty for last form
        "multi_go_back",// this field should be set when the user clicks the
                        // back button or link in a multi-page form sequence
        "alert_to");    // email address to send alerts (errors) to
 
    //
    // $SPECIAL_MULTI is the list of fields from $SPECIAL_FIELDS that can
    // have multiple values, for example:
    //      name="conditions1"
    //      name="conditions2"
    //
$SPECIAL_MULTI = array(
        "conditions",
        "fmcompute",
        );
 
    //
    // $SPECIAL_NOSTRIP is the list of fields from $SPECIAL_FIELDS that
    // should not be stripped (other than for magic_quotes_gpc reasons).
    //
$SPECIAL_NOSTRIP = array(
        "conditions",
        "fmcompute",
        );
 
    //
    // VALID_MAIL_OPTIONS lists the valid mail_options words
    //
$VALID_MAIL_OPTIONS = array(
        "AlwaysList"=>true,
        "CharSet"=>true,
        "DupHeader"=>true,
        "Exclude"=>true,
        "FromAddr"=>true,
        "HTMLTemplate"=>true,
        "KeepLines"=>true,
        "NoEmpty"=>true,
        "NoPlain"=>true,
        "PlainTemplate"=>true,
        "SendMailFOption"=>true,
        "StartLine"=>true,
        "TemplateMissing"=>true,
        );
 
    //
    // VALID_CRM_OPTIONS lists the valid crm_options words
    //
$VALID_CRM_OPTIONS = array(
        "ErrorOnFail"=>true,
        );
 
    //
    // VALID_AR_OPTIONS lists the valid autorespond words
    //
$VALID_AR_OPTIONS = array(
        "Subject"=>true,
        "HTMLTemplate"=>true,
        "PlainTemplate"=>true,
        "TemplateMissing"=>true,
        "FromAddr"=>true,
        );
 
    //
    // VALID_FILTER_OPTIONS lists the valid filter_options words
    //
$VALID_FILTER_OPTIONS = array(
        "Attach"=>true,
        "KeepInLine"=>true,
        "CSVHeading"=>true,
        "CSVSep"=>true,
        "CSVIntSep"=>true,
        "CSVQuote"=>true,
        "CSVEscPolicy"=>true,
        "CSVRaw"=>true,
        );
 
    //
    // SPECIAL_VALUES is set to the value of the fields we've found
    //  usage: $SPECIAL_VALUES["email"] is the value of the email field
    //
$SPECIAL_VALUES = array();
    //
    // Array of mail options; set by the function 'ProcessMailOptions'
    //
$MAIL_OPTS = array();
    //
    // Array of crm options; set by the function 'ProcessCRMOptions'
    //
$CRM_OPTS = array();
    //
    // Array of autorespond options; set by the function 'ProcessAROptions'
    //
$AR_OPTS = array();
    //
    // Array of filter options; set by the function 'ProcessFilterOptions'
    //
$FILTER_OPTS = array();
 
    //
    // initialise $SPECIAL_VALUES so that we don't fail on using unset values
    //
foreach ($SPECIAL_FIELDS as $sFieldName)
    $SPECIAL_VALUES[$sFieldName] = "";
 
    //
    // Special defaults for some fields....
    //
$SPECIAL_VALUES['template_list_sep'] = ",";
 
    //
    // FORMATTED_INPUT contains the input variables formatted nicely
    // This is used for error reporting and debugging only.
    //
$FORMATTED_INPUT = array();
 
    //
    // $FILTER_ATTRIBS_LOOKUP is the parsed $FILTER_ATTRIBS array
    //
$FILTER_ATTRIBS_LOOKUP = array();
 
    //
    // $EMAIL_ADDRS is the array of email addresses from the $FORM_INI_FILE
    //
$EMAIL_ADDRS = array();
 
    //
    // Access the www.tectite.com website to get the current version.
    //
function CheckVersion()
{
    global  $FM_VERS;
 
@   $fp = fopen("http://www.tectite.com/fmversion.txt","r");
    if ($fp !== false)
    {
            //
            // version file looks like this:
            //      Version=versionumber
            //      Message=a message to send in the alert
            //
        $s_version = "";
        $s_message = "";
        $s_line = "";
        $b_in_mesg = false;
        while (!feof($fp))
        {
            $s_line = fgets($fp,1024);
            if ($b_in_mesg)
                $s_message .= $s_line;
            else
            {
                $s_prefix = substr($s_line,0,8);
                if ($s_prefix == "Message=")
                {
                    $s_message .= substr($s_line,8);
                    $b_in_mesg = true;
                }
                elseif ($s_prefix == "Version=")
                    $s_version = substr($s_line,8);
            }
        }
        fclose($fp);
        $s_version = str_replace("\r","",$s_version);
        $s_version = str_replace("\n","",$s_version);
        $s_stop_mesg = GetMessage(MSG_END_VERS_CHK);
        if ((float) $s_version > (float) $FM_VERS)
            SendAlert(GetMessage(MSG_VERS_CHK,array(
                        "TECTITE"=>"www.tectite.com",
                        "FM_VERS"=>"$FM_VERS",
                        "NEWVERS"=>$s_version,
                        ))."\n$s_message\n$s_stop_mesg",true,true);
    }
}
 
    //
    // Check for new FormMail version
    //
function Check4Update($s_chk_file,$s_id = "")
{
    global  $lNow,$php_errormsg;
 
@   $l_last_chk = filemtime($s_chk_file);
    if ($l_last_chk === false || $lNow - $l_last_chk >= (CHECK_DAYS*24*60*60))
    {
        CheckVersion();
            //
            // update the check file's time stamp
            //
    @   $fp = fopen($s_chk_file,"w");
        if ($fp !== false)
        {
            fwrite($fp,"FormMail version check ".
                (empty($s_id) ? "" : "for identifier '$s_id' ").
                "at ".date("H:i:s d-M-Y",$lNow)."\n");
            fclose($fp);
        }
        else
            SendAlert(GetMessage(MSG_CHK_FILE_ERROR,array("FILE"=>$s_chk_file,
                            "ERROR"=>CheckString($php_errormsg))));
    }
}
 
    //
    // Perform various processing at the end of the script's execution.
    //
function OnExit()
{
    global  $TARGET_EMAIL,$CHECK_FILE;
 
        //
        // Check the www.tectite.com website for a new version, but only
        // do this check once every CHECK_DAYS days (or on server reboot).
        //
    if (CHECK_FOR_NEW_VERSION)
    {
        global  $SERVER;
 
        if (isset($TARGET_EMAIL[0]))
        {
                //
                // use the first few characters of the MD5 of first email
                // address pattern from $TARGET_EMAIL to get a unique file
                // for the server
                //
            $s_id = "";
            if (isset($SERVER) && !empty($SERVER))
                $s_id = $SERVER;
            $s_dir = GetTempDir();
            $s_md5 = md5($TARGET_EMAIL[0]);
            $s_uniq = substr($s_md5,0,6);
            $s_chk_file = "fm"."$s_uniq".".txt";
            Check4Update($s_dir."/".$s_chk_file,$s_id);
        }
    }
}
 
register_shutdown_function('OnExit');
 
    //
    // Return the array with each string urlencode'd.
    //
function URLEncodeArray($a_array)
{
    foreach ($a_array as $m_key=>$s_str)
    {
            //
            // only encode the value after the '='
            //
        if (($i_pos = strpos($s_str,'=')) !== false)
            $a_array[$m_key] = substr($s_str,0,$i_pos+1).
                                urlencode(substr($s_str,$i_pos+1));
        else
            $a_array[$m_key] = urlencode($s_str);
    }
    return ($a_array);
}
 
    //
    // Add a parameter or list of parameters to a URL.
    //
function AddURLParams($s_url,$m_params,$b_encode = true)
{
    if (!empty($m_params))
    {
        if (!is_array($m_params))
            $m_params = array($m_params);
        if (strpos($s_url,'?') === false)
            $s_url .= '?';
        else
            $s_url .= '&';
        $s_url .= implode('&',($b_encode) ? URLEncodeArray($m_params) : $m_params);
    }
    return ($s_url);
}
 
    //
    // Recursively trim an array of strings (non string values are converted
    // to a string first).
    //
function TrimArray($a_list)
{
    foreach ($a_list as $m_key=>$m_item)
        if (is_array($m_item))
            $a_list[$m_key] = TrimArray($m_item);
        elseif (is_scalar($m_item))
            $a_list[$m_key] = trim("$m_item");
        else
            $a_list[$m_key] = "";
    return ($a_list);
}
 
    //
    // Parse a derivation specification and return an array of
    // field names and operators.
    //
function ParseDerivation($a_form_data,$s_fld_spec,$s_name,&$a_errors)
{
    $a_deriv = array();
    while (($i_len = strlen($s_fld_spec)) > 0)
    {
            //
            // we support the following operators:
            //      +   concatenate with a single space between, but skip the space
            //          if the next field is empty
            //      *   concatenate with a single space between
            //      .   concatenate with no space between
            //
        $i_span = strcspn($s_fld_spec,'+*.');
        if ($i_span == 0)
        {
            $a_errors[] = $s_name;
            return (false);
        }
        $a_deriv[] = trim(substr($s_fld_spec,0,$i_span));
        if ($i_span < $i_len)
        {
            $a_deriv[] = substr($s_fld_spec,$i_span,1);
            $s_fld_spec = substr($s_fld_spec,$i_span+1);
        }
        else
            $s_fld_spec = "";
    }
    return ($a_deriv);
}
 
    //
    // Test if a character is an alphabetic.
    //
function IsAlpha($ch)
{
    return (strpos("abcdefghijklmnopqrstuvwxyz",strtolower($ch)) !== false);
}
 
    //
    // Test if a character is a digit.
    //
function IsNumeric($ch)
{
    return (strpos("0123456789",$ch) !== false);
}
 
    //
    // Test if a character is an alphanumeric
    //
function IsAlnum($ch)
{
    return (IsAlpha($ch) || IsNumeric($ch));
}
 
    //
    // Return an array of tokens extracted from the given string.
    // A token is:
    //  - a word (begins with alpha or _, and is followed by any number
    //    of alphanumerics or _ chars)
    //  - a number (any number of consecutive digits with up to one period)
    //  - a string enclosed in specified quotes (this can be disabled)
    //  - any punctuation character
    //
    // Anything not matching the above is silently ignored!
    //
function GetTokens($s_str,$s_quotes = "'\"")
{
    $b_allow_strings = ($s_quotes !== "") ? true : false;
    $ii = 0;
    $i_len = strlen($s_str);
    $a_toks = array();
 
    while ($ii < $i_len)
    {
        switch ($ch = $s_str{$ii})
        {
        case " ":
        case "\t":
        case "\n":
        case "\r":
            $ii++;
            continue;
        }
            //
            // start of a token
            //
        $i_start = $ii;
        if ($ch == "_" || IsAlpha($ch))
        {
                //
                // a word
                //
            $i_count = 1;
            while (++$ii < $i_len &&
                   ($s_str{$ii} == "_" || IsAlnum($s_str{$ii})))
                ++$i_count;
            $a_toks[] = substr($s_str,$i_start,$i_count);
        }
        elseif (($ch == "." && $ii < ($i_len-1) && IsNumeric($s_str{$ii+1}))||
                IsNumeric($ch))
        {
                //
                // a number
                //
            $b_had_dot = ($ch == ".");
            $i_count = 1;
            while (++$ii < $i_len)
            {
                if (IsNumeric($s_str{$ii}))
                    ++$i_count;
                elseif ($s_str{$ii} == "." && !$b_had_dot)
                {
                    ++$i_count;
                    $b_had_dot = true;
                }
                else
                    break;
            }
            $a_toks[] = substr($s_str,$i_start,$i_count);
        }
        elseif ($b_allow_strings && strpos($s_quotes,$ch) !== false)
        {
            $c_quote = $ch;
                //
                // a quoted string
                //
            while (++$ii < $i_len)
            {
                if ($s_str{$ii} == $c_quote)
                {
                    ++$ii;  // include the terminating quote
                    break;
                }
            }
            $a_toks[] = substr($s_str,$i_start,$ii-$i_start);
        }
        else
        {
            $s_punct = "~!@#$%^&*()-+={}[]|:;<>,.?/`\\";
            if (!$b_allow_strings)
                $s_punct .= "'\"";
            if (strpos($s_punct,$ch) !== false)
                $a_toks[] = $ch;
            ++$ii;
        }
    }
    return ($a_toks);
}
 
    //
    // Return the value from a derive_fields specification.
    // Specifications are in this format:
    //      %info%
    // where info is a predefined word or a literal in quotes
    // (e.g. 'the time is ')
    //
function ValueSpec($s_spec,$a_form_data,&$a_errors)
{
    global  $lNow;
 
    $s_value = "";
    switch (trim($s_spec))
    {
    case 'date':        // "standard" date format: DD-MMM-YYYY
        $s_value = date('d-M-Y',$lNow);
        break;
    case 'time':        // "standard" time format: HH:MM:SS
        $s_value = date('H:i:s',$lNow);
        break;
    case 'ampm':        // am or pm
        $s_value = date('a',$lNow);
        break;
    case 'AMPM':        // AM or PM
        $s_value = date('A',$lNow);
        break;
    case 'dom0':        // day of month with possible leading zero
        $s_value = date('d',$lNow);
        break;
    case 'dom':         // day of month with no leading zero
        $s_value = date('j',$lNow);
        break;
    case 'day':         // day name (abbreviated)
        $s_value = date('D',$lNow);
        break;
    case 'dayname':     // day name (full)
        $s_value = date('l',$lNow);
        break;
    case 'daysuffix':   // day number suffix for English (st for 1st, nd for 2nd, etc.)
        $s_value = date('S',$lNow);
        break;
    case 'moy0':        // month of year with possible leading zero
        $s_value = date('m',$lNow);
        break;
    case 'moy':         // month of year with no leading zero
        $s_value = date('n',$lNow);
        break;
    case 'month':       // month name (abbreviated)
        $s_value = date('M',$lNow);
        break;
    case 'monthname':   // month name (full)
        $s_value = date('F',$lNow);
        break;
    case 'year':        // year (two digits)
        $s_value = date('y',$lNow);
        break;
    case 'fullyear':    // year (full)
        $s_value = date('Y',$lNow);
        break;
    case 'rfcdate':     // date formatted according to RFC 822
        $s_value = date('r',$lNow);
        break;
    case 'tzname':      // timezone name
        $s_value = date('T',$lNow);
        break;
    case 'tz':          // timezone difference from Greenwich +NNNN or -NNNN
        $s_value = date('O',$lNow);
        break;
    case 'hour120':     // hour of day (01-12) with possible leading zero
        $s_value = date('h',$lNow);
        break;
    case 'hour240':     // hour of day (00-23) with possible leading zero
        $s_value = date('H',$lNow);
        break;
    case 'hour12':      // hour of day (1-12) with no leading zero
        $s_value = date('g',$lNow);
        break;
    case 'hour24':      // hour of day (0-23) with no leading zero
        $s_value = date('G',$lNow);
        break;
    case 'min':         // minute of hour (00-59)
        $s_value = date('i',$lNow);
        break;
    case 'sec':         // seconds of minute (00-59)
        $s_value = date('s',$lNow);
        break;
    default:
        if ($s_spec{0} == "'")
        {
                //
                // to get a quote, use 3 quotes:
                //      '''
                //
            if ($s_spec == "'''")
                $s_value = "'";
            elseif (substr($s_spec,-1,1) == "'")
                $s_value = substr($s_spec,1,-1);
            else
                    //
                    // missing final quote is OK
                    //
                $s_value = substr($s_spec,1);
        }
        elseif (strspn($s_spec,"0123456789ABCDEF") == 2)
        {
                //
                // insert the ASCII character corresponding to
                // the hexadecimal value
                //
            $i_val = intval(substr($s_spec,0,2),16);
            $s_value = chr($i_val);
        }
        else
        {
                //
                // look for supported functions, start by getting all
                // the tokens
                //
            $a_toks = GetTokens($s_spec);
            if (count($a_toks) > 0)
            {
                switch ($a_toks[0])
                {
                case "if":
                        //
                        // "if" function: test first field
                        //       if not empty, then use second field
                        //       else, use third field
                        //
                        // Example: if(fld1 ; fld2 ; fld3)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to test (first)
                        //      3               ;
                        //      4               the "then" spec (can be missing)
                        //      5               ;
                        //      6               the "else" spec (can be missing)
                        //      7               )
                        //
                    if (($n_tok = count($a_toks)) < 6 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ";" ||
                            $a_toks[$n_tok-1] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_IF_FMT))));
                    else
                    {
                        $b_ok = true;
                        $s_fld_name = $a_toks[2];
                        $s_then_spec = $s_else_spec = "";
                        for ($ii = 4 ; $ii < $n_tok && $a_toks[$ii] != ';' ; $ii++)
                            $s_then_spec .= $a_toks[$ii];
                        if ($ii == $n_tok)
                            $b_ok = false;
                        else
                        {
                                //
                                // Concatenate tokens until the ')'.
                                // This provides the "else" spec.
                                //
                            for ( ; ++$ii < $n_tok && $a_toks[$ii] != ')' ; )
                                $s_else_spec .= $a_toks[$ii];
                            if ($ii == $n_tok)
                                $b_ok = false;
                        }
                        if ($b_ok)
                        {
                            if (!TestFieldEmpty($s_fld_name,$a_form_data,$s_mesg))
                                $s_fld_spec = $s_then_spec;
                            else
                                $s_fld_spec = $s_else_spec;
                            $s_value = GetDerivedValue($a_form_data,$s_fld_spec);
                        }
                        else
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                            array("SPEC"=>$s_spec,
                                                  "MSG"=>GetMessage(MSG_DER_FUNC_IF_FMT))));
                    }
                    break;
                case "size":
                        //
                        // "size" function: return size of uploaded file
                        //
                        // Example: size(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name for the file upload
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_SIZE_FMT))));
                    elseif (($i_size = GetFileSize($a_toks[2])) !== false)
                        $s_value = "$i_size";
                    break;
                case "ext":
                        //
                        // "ext" function: return filename extension of uploaded file
                        //
                        // Example: ext(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name for the file upload
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_EXT_FMT))));
                    elseif (($s_name = GetFileName($a_toks[2])) !== false)
                    {
                        if (($i_pos = strrpos($s_name,".")) !== false)
                            $s_value = substr($s_name,$i_pos+1);
                    }
                    break;
                case "ucase":
                case "lcase":
                        //
                        // "ucase" and "lcase" functions: return field
                        // converted to upper or lower case
                        //
                        // Example: lcase(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to convert
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC1_FMT,
                                                    array("FUNC"=>$a_toks[0])))));
                    elseif ($a_toks[0] == "ucase")
                        $s_value = strtoupper(GetFieldValue($a_toks[2],$a_form_data));
                    else
                        $s_value = strtolower(GetFieldValue($a_toks[2],$a_form_data));
                    break;
                case "ltrim":
                case "rtrim":
                case "trim":
                        //
                        // trim functions: return field with whitespace removed
                        // from left (ltrim), right (rtrim), or both (trim)
                        // ends.
                        //
                        // Example: ltrim(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to trim
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC1_FMT,
                                              array("FUNC"=>$a_toks[0])))));
                    else
                        $s_value = $a_toks[0](GetFieldValue($a_toks[2],$a_form_data));
                    break;
                case "ltrim0":
                        //
                        // ltrim0 function: return field with blanks and
                        // leading 0's removed from the left.
                        //
                        // Example: ltrim0(fieldname)
                        //
                        // tokens are:
                        //      1               (
                        //      2               the field name to trim
                        //      3               )
                        //
                    if (count($a_toks) != 4 ||
                            $a_toks[1] != "(" ||
                            $a_toks[3] != ")")
                        SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC1_FMT,
                                              array("FUNC"=>$a_toks[0])))));
                    else
                    {
                        $s_value = GetFieldValue($a_toks[2],$a_form_data);
                        $s_value = ltrim($s_value);     // trim blanks on left
                        $i_len = strspn($s_value,"0");
                            //
                            // if the whole string is zeroes, make sure we leave
                            // one of them!
                            //
                        if ($i_len == strlen($s_value))
                            if (--$i_len < 0)
                                $i_len = 0;
                        $s_value = substr($s_value,$i_len);
                    }
                    break;
                case "nextnum":
                        //
                        // "nextnum" function: return a unique number (next number)
                        //
                        // Usage: nextnum[(pad[,base])]
                        //
                        // Examples:
                        //      %nextnum%
                        //      %nextnum(8)%
                        //      %nextnum(5;16)%
                        //
                        // You can provide a padding amount. In this case, the
                        // number is padded on the left with zeroes to the number
                        // of digits specified.
                        //
                        // You can also provide a base for your numbers.  Valid
                        // values for base are 2 to 36, inclusive.
                        //
                        // tokens are:
                        //      1               (
                        //      2               the padding amount
                        //      3               ;
                        //      4               the base
                        //      5               )
                        //
                    $i_pad = 0;     // no padding
                    $i_base = 10;   // base 10
                    if (($n_tok = count($a_toks)) > 1)
                    {
                        if (($n_tok != 4 && $n_tok != 6) ||
                            $a_toks[1] != "(" ||
                            $a_toks[$n_tok-1] != ")")
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T1)")));
                        if ($n_tok == 6 && $a_toks[3] != ";")
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T2)")));
                        if (!is_numeric($a_toks[2]) ||
                            ($n_tok == 6 && !is_numeric($a_toks[4])))
                            SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                        array("SPEC"=>$s_spec,
                                              "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T3)")));
                        $i_pad = intval($a_toks[2]);
                        if ($n_tok == 6)
                        {
                            $i_base = intval($a_toks[4]);
                            if ($i_base < 2 || $i_base > 36)
                            {
                                SendAlert(GetMessage(MSG_DER_FUNC_ERROR,
                                            array("SPEC"=>$s_spec,
                                                  "MSG"=>GetMessage(MSG_DER_FUNC_NEXTNUM_FMT)." (T4)")));
                                $i_base = 10;
                            }
                        }
                        $s_value = GetNextNum($i_pad,$i_base);
                    }
                    else
                    {
                        $s_value = GetNextNum($i_pad,$i_base);
                    }
                    break;
                default:
                    SendAlert(GetMessage(MSG_UNK_VALUE_SPEC,
                                    array("SPEC"=>$s_spec,"MSG"=>"")));
                    break;
                }
            }
            else
                SendAlert(GetMessage(MSG_UNK_VALUE_SPEC,array("SPEC"=>$s_spec,
                                                            "MSG"=>"")));
        }
        break;
    }
    return ($s_value);
}
 
    //
    // Return the next number or fail on error
    //
function GetNextNum($i_pad,$i_base)
{
    global  $NEXT_NUM_FILE,$php_errormsg;
 
    if (!isset($NEXT_NUM_FILE) || $NEXT_NUM_FILE === "")
    {
        ErrorWithIgnore("next_num_config",GetMessage(MSG_NO_NEXT_NUM_FILE));
        exit;
    }
    if (($fp = @fopen($NEXT_NUM_FILE,"r+")) === false)
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"open",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
    if (!flock($fp,defined("LOCK_EX") ? LOCK_EX : 2))
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"flock",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
        //
        // read the first line only
        //
    if (!feof($fp))
    {
        if (($s_line = fread($fp,1024)) === false)
            $i_next = 1;
        elseif (($i_next = intval($s_line)) <= 0)
            $i_next = 1;
    }
    else
        $i_next = 1;
    if (rewind($fp) == 0)
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"rewind",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
    $s_ret = strval($i_next++);
    if (fputs($fp,"$i_next\r\n") <= 0)
    {
        Error("next_num_file",GetMessage(MSG_NEXT_NUM_FILE,
                                    array("FILE"=>$NEXT_NUM_FILE,
                                        "ACT"=>"fputs",
                                        "ERR"=>$php_errormsg)));
        exit;
    }
    fclose($fp);
    if ($i_base != 10)
    {
        $s_ret = base_convert($s_ret,10,$i_base);
        $s_ret = strtoupper($s_ret);    // always upper case if alphas are used
    }
    if ($i_pad != 0)
        $s_ret = str_pad($s_ret,$i_pad,"0",STR_PAD_LEFT);
    return ($s_ret);
}
 
    //
    // Return the value of an object or array as a string.
    //
function GetObjectAsString($m_value)
{
    ob_start();
    print_r($m_value);
    $s_ret = ob_get_contents();
    ob_end_clean();
    return ($s_ret);
}
 
    //
    // Return a Server or Environment variable value.  Returns false if
    // not found, otherwise a string value.
    //
function GetEnvValue($s_name)
{
    global  $aServerVars,$aEnvVars;
 
    if (isset($aEnvVars[$s_name]))
        $m_value = $aEnvVars[$s_name];
    elseif (isset($aServerVars[$s_name]))
        $m_value = $aServerVars[$s_name];
        //
        // some values might not be strings - so convert
        //
    if (isset($m_value) && !is_scalar($m_value))
        $m_value = GetObjectAsString($m_value);
    return (isset($m_value) ? ((string) $m_value) : false);
}
 
    //
    // Same as "empty" but checks for true emptiness if ZERO_IS_EMPTY is
    // set to false.
    //
function IsFieldEmpty($s_value)
{
    if (ZERO_IS_EMPTY || is_array($s_value))
        return (empty($s_value));
    else
        return ($s_value === "");
}
 
    //
    // Test if a field is set in the given vars array or in the uploaded
    // files.
    //
function IsFieldSet($s_fld,$a_main_vars)
{
    global  $aFileVars;
 
    return (isset($a_main_vars[$s_fld]) ||
            (FILEUPLOADS && isset($aFileVars[$s_fld])));
}
 
    //
    // Return the info for the uploaded file, or false on error.
    //
function GetFileInfo($s_fld)
{
    global  $aFileVars;
 
    if (FILEUPLOADS && isset($aFileVars[$s_fld]))
    {
        $a_upload = $aFileVars[$s_fld];
        if (isset($a_upload['tmp_name']) && !empty($a_upload['tmp_name']) &&
            isset($a_upload['name']) && !empty($a_upload['name']) &&
            IsUploadedFile($a_upload))
                return ($a_upload);
    }
    return (false);
}
 
    //
    // Return the original name of the uploaded file or false on error.
    //
function GetFileName($s_fld)
{
    if (($a_upload = GetFileInfo($s_fld)) !== false)
        return ($a_upload['name']);
    return (false);
}
 
    //
    // Return the size of the uploaded file or false on error.
    //
function GetFileSize($s_fld)
{
    if (($a_upload = GetFileInfo($s_fld)) !== false)
        return ($a_upload['size']);
    return (false);
}
 
    //
    // Return a field value.  Empty string is returned if the field is
    // not found. File fields return the original name of the uploaded file.
    //
function GetFieldValue($s_fld,$a_main_vars)
{
    if (!isset($a_main_vars[$s_fld]))
    {
        if (($s_name = GetFileName($s_fld)) === false)
            $s_name = "";
        return ($s_name);
    }
    return ((string) $a_main_vars[$s_fld]);
}
 
    //
    // Tests a field against an array of vars for emptyness.
    // If the var isn't found there, then the POSTed files array is checked.
    // Returns true if the field is empty (a specific error may
    // be returned in the $s_mesg parameter).
    //
function TestFieldEmpty($s_fld,$a_main_vars,&$s_mesg)
{
    global  $aFileVars;
 
    $s_mesg = "";
    $b_empty = TRUE;
    if (!isset($a_main_vars[$s_fld]))
    {
            //
            // Each file var is an array with these elements:
            //      'name' => The original name of the file on the client machine.
            //      'type' => The mime type of the file, if the browser provided this information.
            //      'tmp_name' => The temporary filename of the file in which the uploaded file was stored on the server.
            //      'error' => The error code associated with this file upload.
            //                  NOTE: 'error' was added in PHP 4.2.0
            //      'size' => The size, in bytes, of the uploaded file.
            //
            // Error codes (the constants are only available from PHP 4.3.0 so
            // we have to use the raw numbers):
            //  UPLOAD_ERR_OK
            //      Value: 0; There is no error, the file uploaded with success.
            //  UPLOAD_ERR_INI_SIZE
            //      Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
            //  UPLOAD_ERR_FORM_SIZE
            //      Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.
            //  UPLOAD_ERR_PARTIAL
            //      Value: 3; The uploaded file was only partially uploaded.
            //  UPLOAD_ERR_NO_FILE
            //      Value: 4; No file was uploaded.
            //
        if (FILEUPLOADS && isset($aFileVars[$s_fld]))
        {
            $a_upload = $aFileVars[$s_fld];
            if (isset($a_upload['tmp_name']) && !empty($a_upload['tmp_name']) &&
                isset($a_upload['name']) && !empty($a_upload['name']))
            {
                if (IsUploadedFile($a_upload))
                    $b_empty = false;
            }
            if ($b_empty && isset($a_upload['error']))
                switch ($a_upload['error'])
                {
                case 1:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR1);
                    break;
                case 2:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR2);
                    break;
                case 3:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR3);
                    break;
                case 4:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR4);
                    break;
                case 6:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR6);
                    break;
                case 7:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR7);
                    break;
                case 8:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR8);
                    break;
                default:
                    $s_mesg = GetMessage(MSG_FILE_UPLOAD_ERR_UNK,
                                    array("ERRNO"=>$a_upload['error']));
                    break;
                }
        }
    }
    else
        $b_empty = IsFieldEmpty($a_main_vars[$s_fld]);
    return ($b_empty);
}
 
    //
    // Return a derived field value or value specification.
    //
function GetDerivedValue($a_form_data,$s_word,&$a_errors)
{
    global  $aFileVars;
 
    $s_value = "";
        //
        // a field name or a value specification
        // value specifications have the following format:
        //      %spec%
        //
    if (substr($s_word,0,1) == '%')
    {
        if (substr($s_word,-1,1) != '%')
        {
            SendAlert(GetMessage(MSG_INV_VALUE_SPEC,array("SPEC"=>$s_word)));
            $s_value = $s_word;
        }
        else
        {
            $s_spec = substr($s_word,1,-1);
            $s_value = ValueSpec($s_spec,$a_form_data,$a_errors);
        }
    }
    else
    {
        $s_fld_name = $s_word;
            //
            // try form data first, then the environment/server data
            //
        if (IsFieldSet($s_fld_name,$a_form_data))
            $s_value = GetFieldValue($s_fld_name,$a_form_data);
        elseif (($s_value = GetEnvValue($s_fld_name)) === false)
            $s_value = "";
        $s_value = trim($s_value);
    }
    return ($s_value);
}
 
    //
    // Derive a value from the form data using the specification returned
    // from ParseDerivation.
    //
function DeriveValue($a_form_data,$a_value_spec,$s_name,&$a_errors)
{
    $s_value = "";
    for ($ii = 0 ; $ii < count($a_value_spec) ; $ii++)
    {
        switch ($a_value_spec[$ii])
        {
        case '+':
                //
                // concatenate with a single space between, but skip the space
                // if the next field is empty
                //
            if ($ii < count($a_value_spec)-1)
            {
                $s_temp = GetDerivedValue($a_form_data,$a_value_spec[$ii+1],$a_errors);
                if (!IsFieldEmpty($s_temp))
                    $s_value .= ' ';
            }
            break;
        case '.':
                //
                // concatenate with no space between
                //
            break;
        case '*':
                //
                // concatenate with a single space between
                //
            $s_value .= ' ';
            break;
        default:
                //
                // a field name or a value specification
                // value specifications have the following format:
                //      %name%
                //
            $s_value .= GetDerivedValue($a_form_data,$a_value_spec[$ii],$a_errors);
            break;
        }
    }
    return ($s_value);
}
 
    //
    // Create derived fields specified by the "derive_fields" value.
    //
function CreateDerived($a_form_data)
{
    if (isset($a_form_data["derive_fields"]))
    {
        $a_errors = array();
            //
            // get the list of derived field specifications
            //
        $a_list = TrimArray(explode(",",$a_form_data["derive_fields"]));
        foreach ($a_list as $s_fld_spec)
        {
            if ($s_fld_spec === "")
                    //
                    // silently ignore empty derivations
                    //
                continue;
            if (($i_pos = strpos($s_fld_spec,"=")) === false)
            {
                $a_errors[] = $s_fld_spec;
                continue;
            }
            $s_name = trim(substr($s_fld_spec,0,$i_pos));
            $s_fld_spec = substr($s_fld_spec,$i_pos+1);
 
            if (($a_value_spec = ParseDerivation($a_form_data,$s_fld_spec,
                                                $s_name,$a_errors)) === false)
                break;
            $a_form_data[$s_name] = DeriveValue($a_form_data,$a_value_spec,$s_name,$a_errors);
        }
        if (count($a_errors) > 0)
        {
            SendAlert(GetMessage(MSG_DERIVED_INVALID).implode("\n",$a_errors));
            Error("derivation_failure",GetMessage(MSG_INT_FORM_ERROR));
        }
    }
    return ($a_form_data);
}
 
    //
    // To process the name specification for files and update the
    // array of file variables accordingly.
    //
function SetFileNames($s_name_spec,$a_order,$a_fields,$a_raw_fields,$a_all_raw_values,$a_file_vars)
{
    $a_errors = array();
        //
        // get the list of file name derivations
        //
    $a_list = TrimArray(explode(",",$s_name_spec));
    foreach ($a_list as $s_fld_spec)
    {
        if ($s_fld_spec === "")
                //
                // silently ignore empty file name derivations
                //
            continue;
        if (($i_pos = strpos($s_fld_spec,"=")) === false)
        {
            $a_errors[] = $s_fld_spec;
            continue;
        }
        $s_name = trim(substr($s_fld_spec,0,$i_pos));
        $s_fld_spec = substr($s_fld_spec,$i_pos+1);
 
        if (($a_value_spec = ParseDerivation($a_raw_fields,$s_fld_spec,
                                            $s_name,$a_errors)) === false)
            break;
        if (isset($a_file_vars[$s_name]) && is_array($a_file_vars[$s_name]))
        {
                //
                // we create our own special entry in the file variable's data
                //
            $a_file_vars[$s_name]['new_name'] = DeriveValue($a_raw_fields,
                                                        $a_value_spec,$s_name,
                                                        $a_errors);
                //
                // we also create (derive) a new field called 'name_of_X'
                // where X is the file fields's name
                //
            ProcessField("name_of_$s_name",$a_file_vars[$s_name]['new_name'],
                        $a_order,$a_fields,$a_raw_fields);
            $a_all_raw_values["name_of_$s_name"] = $a_file_vars[$s_name]['new_name'];
        }
        /* This is annoying if a file upload is optional.  Just ignore missing
            file upload fields.
        else
            SendAlert(GetMessage(MSG_FILE_NAMES_NOT_FILE,
                                            array("NAME"=>$s_name)));*/
    }
    if (count($a_errors) > 0)
    {
        SendAlert(GetMessage(MSG_FILE_NAMES_INVALID).implode("\n",$a_errors));
        Error("file_names_derivation_failure",GetMessage(MSG_INT_FORM_ERROR));
    }
    return (array($a_order,$a_fields,$a_raw_fields,$a_all_raw_values,$a_file_vars));
}
 
    //
    // Process a list of attributes or options.
    // Format for each attribute/option:
    //      name
    // or
    //      name=value
    //
    // Values can be simple values or semicolon (;) separated lists:
    //          avalue
    //          value1;value2;value3;...
    //
    // Returns attribute/options in the associative array $a_attribs.
    // Optionally, valid attributes can be provided in $a_valid_attribs
    // (if empty, all attributes found are considered valid).
    // Errors are returned in $a_errors.
    //
function ProcessAttributeList($a_list,&$a_attribs,&$a_errors,
                        $a_valid_attribs = array())
{
    $b_got_valid_list = (count($a_valid_attribs) > 0);
    foreach ($a_list as $s_attrib)
    {
            //
            // if the name begins with '.' then silently ignore it;
            // this allows you to temporarily disable an option without
            // getting an alert message
            //
        if (($i_pos = strpos($s_attrib,"=")) === false)
        {
            $s_name = trim($s_attrib);
            if (empty($s_name) || $s_name{0} == '.')
                continue;
                //
                // option is a simple "present" value
                //
            $a_attribs[$s_name] = true;
        }
        else
        {
            $s_name = trim(substr($s_attrib,0,$i_pos));
            if (empty($s_name) || $s_name{0} == '.')
                continue;
            $s_value_list = substr($s_attrib,$i_pos+1);
            if (($i_pos = strpos($s_value_list,";")) === false)
                    //
                    // single value
                    //
                $a_attribs[$s_name] = trim($s_value_list);
            else
                    //
                    // list of values
                    //
                $a_attribs[$s_name] = TrimArray(explode(";",$s_value_list));
        }
        if ($b_got_valid_list && !isset($a_valid_attribs[$s_name]))
            $a_errors[] = $s_name;
    }
}
 
    //
    // Process the options specified in the form.
    // Options can be specified in this format:
    //          option1,option2,option3,...
    // Each option can be a simple word or a word and value:
    //          name
    //          name=value
    // No name or value can contain a comma.
    // Values can be simple values or semicolon (;) separated lists:
    //          avalue
    //          value1;value2;value3;...
    // No value can contain a semicolon.
    // Be careful of values beginning and ending with whitespace characters;
    // they will be trimmed.
    //
function ProcessOptions($s_name,$a_form_data,&$a_options,$a_valid_options)
{
    $a_errors = array();
    $a_options = array();
    if (isset($a_form_data[$s_name]))
    {
            //
            // get the options list and trim each one
            //
        $a_list = TrimArray(explode(",",$a_form_data[$s_name]));
        ProcessAttributeList($a_list,$a_options,$a_errors,$a_valid_options);
    }
    if (count($a_errors) > 0)
        SendAlert(GetMessage(MSG_OPTIONS_INVALID,array("OPT"=>$s_name)).
                    implode("\n",$a_errors));
}
 
    //
    // Process the mail_options specified in the form.
    //
function ProcessMailOptions($a_form_data)
{
    global  $MAIL_OPTS,$VALID_MAIL_OPTIONS;
 
    ProcessOptions("mail_options",$a_form_data,$MAIL_OPTS,$VALID_MAIL_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsMailOptionSet($s_name)
{
    global  $MAIL_OPTS;
 
    return (isset($MAIL_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetMailOption($s_name)
{
    global  $MAIL_OPTS;
 
    return (isset($MAIL_OPTS[$s_name]) ? $MAIL_OPTS[$s_name] : NULL);
}
 
    //
    // Process the crm_options specified in the form.
    //
function ProcessCRMOptions($a_form_data)
{
    global  $CRM_OPTS,$VALID_CRM_OPTIONS;
 
    ProcessOptions("crm_options",$a_form_data,$CRM_OPTS,$VALID_CRM_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsCRMOptionSet($s_name)
{
    global  $CRM_OPTS;
 
    return (isset($CRM_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetCRMOption($s_name)
{
    global  $CRM_OPTS;
 
    return (isset($CRM_OPTS[$s_name]) ? $CRM_OPTS[$s_name] : NULL);
}
 
    //
    // Check if a field is in the mail exclusion list.
    //
function IsMailExcluded($s_name)
{
    $a_list = GetMailOption("Exclude");
    if (!isset($a_list))
        return (false);
    if (is_array($a_list))
        return (in_array($s_name,$a_list));
    else
        return ($s_name === $a_list);
}
 
    //
    // Process the autorespond specified in the form.
    //
function ProcessAROptions($a_form_data)
{
    global  $AR_OPTS,$VALID_AR_OPTIONS;
 
    ProcessOptions("autorespond",$a_form_data,$AR_OPTS,$VALID_AR_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsAROptionSet($s_name)
{
    global  $AR_OPTS;
 
    return (isset($AR_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetAROption($s_name)
{
    global  $AR_OPTS;
 
    return (isset($AR_OPTS[$s_name]) ? $AR_OPTS[$s_name] : NULL);
}
 
    //
    // Process the mail_options specified in the form.
    //
function ProcessFilterOptions($a_form_data)
{
    global  $FILTER_OPTS,$VALID_FILTER_OPTIONS;
 
    ProcessOptions("filter_options",$a_form_data,$FILTER_OPTS,$VALID_FILTER_OPTIONS);
}
 
    //
    // Check if an option is set
    //
function IsFilterOptionSet($s_name)
{
    global  $FILTER_OPTS;
 
    return (isset($FILTER_OPTS[$s_name]));
}
 
    //
    // Return an option's value or NULL if not set.
    //
function GetFilterOption($s_name)
{
    global  $FILTER_OPTS;
 
    return (isset($FILTER_OPTS[$s_name]) ? $FILTER_OPTS[$s_name] : NULL);
}
 
    //
    // Lookup a filter attribute for the given filter.
    // Return it's value or false if not set.
    //
function GetFilterAttrib($s_filter,$s_attrib)
{
    global  $FILTER_ATTRIBS,$FILTER_ATTRIBS_LOOKUP;
 
    if (!isset($FILTER_ATTRIBS[$s_filter]))
            //
            // no attributes for the filter
            //
        return (false);
    if (!isset($FILTER_ATTRIBS_LOOKUP[$s_filter]))
    {
            //
            // the attributes have not yet been parsed - create the lookup table
            //
        $a_list = TrimArray(explode(",",$FILTER_ATTRIBS[$s_filter]));
        $FILTER_ATTRIBS_LOOKUP[$s_filter] = array();
        $a_errors = array();
 
        ProcessAttributeList($a_list,$FILTER_ATTRIBS_LOOKUP[$s_filter],$a_errors);
    }
        //
        // perform the lookup and return the value
        //
    if (!isset($FILTER_ATTRIBS_LOOKUP[$s_filter][$s_attrib]))
        return (false);
    return ($FILTER_ATTRIBS_LOOKUP[$s_filter][$s_attrib]);
}
 
    //
    // Check the filter attributes for the given filter.
    // Return true if the given attribute is set otherwise false.
    //
function IsFilterAttribSet($s_filter,$s_attrib)
{
    return (GetFilterAttrib($s_filter,$s_attrib));
}
 
    //
    // Process the given .ini file.
    //
function ProcessFormIniFile($s_file)
{
    global  $EMAIL_ADDRS;
 
    $a_sections = parse_ini_file($s_file,TRUE);
    if (DB_SEE_INI)
    {
            //
            // just display the ini file
            //
        $s_text = "<p><b>The following settings were found in the file '$s_file':</b></p>";
        foreach ($a_sections as $s_sect=>$a_settings)
        {
            $s_text .= "<p>[$s_sect]\n";
            foreach ($a_settings as $s_name=>$s_value)
                $s_text .= "$s_name = \"$s_value\"\n";
            $s_text .= "</p>";
        }
        CreatePage($s_text);
        exit;
    }
        //
        // Load the email_addresses section.
        //
    if (isset($a_sections["email_addresses"]))
        $EMAIL_ADDRS = $a_sections["email_addresses"];
        //
        // Process special fields
        //
    if (isset($a_sections["special_fields"]))
    {
        foreach ($a_sections["special_fields"] as $s_name=>$m_value)
        {
            if (IsSpecialField($s_name))
                SetSpecialField($s_name,$m_value);
                //
                // check for multiple valued special fields
                //
            if (($a_multi_fld = IsSpecialMultiField($s_name)) !== false)
                SetSpecialMultiField($a_multi_fld[0],$a_multi_fld[1],$m_value);
        }
    }
}
 
    //
    // UnMangle an email address
    //
function UnMangle($email)
{
    global  $EMAIL_ADDRS;
 
        //
        // map from a name to the real email address
        //
    if (isset($EMAIL_ADDRS[$email]))
        $email = $EMAIL_ADDRS[$email];
        //
        // unmangle
        //
    if (AT_MANGLE != "")
        $email = str_replace(AT_MANGLE,"@",$email);
    return ($email);
}
 
    //
    // Check a list of email addresses (comma separated); returns a list
    // of valid email addresses (comma separated).
    // The return value is true if there is at least one valid email address.
    //
function CheckEmailAddress($s_addr,&$s_valid,&$s_invalid)
{
    global  $TARGET_EMAIL;
 
    $s_invalid = $s_valid = "";
    $a_list = TrimArray(explode(",",$s_addr));
    $a_invalid = array();
    $n_empty = 0;
    for ($ii = 0 ; $ii < count($a_list) ; $ii++)
    {
        if ($a_list[$ii] === "")
        {
                //
                // ignore, but count empty addresses
                //
            $n_empty++;
            continue;
        }
        $s_email = UnMangle($a_list[$ii]);
            //
            // UnMangle works with INI files too, and a single
            // word can expand to a list of email addresses.
            //
        $a_this_list = TrimArray(explode(",",$s_email));
        foreach ($a_this_list as $s_email)
        {
            if ($s_email === "")
            {
                    //
                    // ignore, but count empty addresses
                    //
                $n_empty++;
                continue;
            }
            $b_is_valid = false;
            for ($jj = 0 ; $jj < count($TARGET_EMAIL) ; $jj++)
                if (eregi($TARGET_EMAIL[$jj],$s_email))
                {
                    if (empty($s_valid))
                        $s_valid = $s_email;
                    else
                        $s_valid .= ",".$s_email;
                    $b_is_valid = true;
                    break;
                }
            if (!$b_is_valid)
                $a_invalid[] = $s_email;
        }
    }
        //
        // just ignore empty recipients unless there are *no* valid recipients
        //
    if (empty($s_valid) && $n_empty > 0)
        $a_invalid[] = GetMessage(MSG_EMPTY_ADDRESSES,array("COUNT"=>$n_empty));
    if (count($a_invalid) > 0)
        $s_invalid = implode(",",$a_invalid);
    return (!empty($s_valid));
}
 
    //
    // Redirect to another URL
    //
function Redirect($url)
{
        //
        // for browsers without cookies enabled, append the Session ID
        //
    if (session_id() !== "")
        $url = AddURLParams($url,session_name()."=".urlencode(session_id()));
    if (defined("SID"))
        $url = AddURLParams($url,SID);
 
        //
        // this is probably a good idea to ensure the session data
        // is written away
        //
    if (function_exists('session_write_close'))
        session_write_close();
 
    header("Location: $url");
        //
        // if the header doesn't work, try JavaScript.
        // if that doesn't work, provide a manual link
        //
    $s_text = GetMessage(MSG_PLSWAIT_REDIR)."\n\n";
    $s_text .= "<script language=\"JavaScript\" type=\"text/javascript\">";
    $s_text .= "window.location.href = '$url';";
    $s_text .= "</script>";
    $s_text .= "\n\n".GetMessage(MSG_IFNOT_REDIR,array("URL"=>$url));
    CreatePage($s_text);
    exit;
}
 
    //
    // JoinLines is just like "implode" except that it checks
    // the end of each array for the separator already being
    // there. This allows us to join a mixture of mail
    // header lines (already terminated) with body lines.
    // This logic works if HEAD_CRLF, for example, is the same
    // as BODY_LF (i.e. both "\r\n") or if BODY_LF is the
    // same as the last character in HEAD_CRLF (i.e.
    // HEAD_CRLF = "\r\n" and BODY_LF = "\n").
    // Other value combinations may break things.
    //
function JoinLines($s_sep,$a_lines)
{
    $s_str = "";
    if (($i_sep_len = strlen($s_sep)) == 0)
            //
            // no separator
            //
        return (implode("",$a_lines));
    $n_lines = count($a_lines);
    for ($ii = 0 ; $ii < $n_lines ; $ii++)
    {
        $s_line = $a_lines[$ii];
        if (substr($s_line,-$i_sep_len) == $s_sep)
            $s_str .= $s_line;
        else
        {
            $s_str .= $s_line;
                //
                // don't append a separator to the last line
                //
            if ($ii < $n_lines-1)
                $s_str .= $s_sep;
        }
    }
    return ($s_str);
}
 
    //
    // Expands an array of mail headers into mail header lines.
    //
function ExpandMailHeaders($a_headers)
{
    $s_hdrs = "";
    foreach ($a_headers as $s_name=>$s_value)
        if ($s_name != "")
        {
            if ($s_hdrs != "")
                $s_hdrs .= HEAD_CRLF;
            $s_hdrs .= $s_name.": ".$s_value;
        }
    return ($s_hdrs);
}
 
    //
    // Expands an array of mail headers into an array containing header lines.
    //
function ExpandMailHeadersArray($a_headers)
{
    $a_hdrs = array();
    foreach ($a_headers as $s_name=>$s_value)
        if ($s_name != "")
            $a_hdrs[] = $s_name.": ".$s_value.HEAD_CRLF;
    return ($a_hdrs);
}
 
    //
    // Low-level email send function; either calls PHP's mail function
    // or uses the PEAR Mail object.
    // NOTE: for some errors, there's no point trying to email
    // an alert message!  So, in these cases, we just display the error to
    // the user.
    //
function DoMail($s_to,$s_subject,$s_mesg,$a_headers)
{
    global  $PEAR_SMTP_HOST,$PEAR_SMTP_PORT,$PEAR_SMTP_USER,$PEAR_SMTP_PWD;
 
    if (isset($PEAR_SMTP_HOST) && !empty($PEAR_SMTP_HOST))
    {
        require_once("Mail.php");
 
        $a_params = array(  "host"=>$PEAR_SMTP_HOST,
                            "port"=>$PEAR_SMTP_PORT);
        if (isset($PEAR_SMTP_USER) && !empty($PEAR_SMTP_USER))
        {
            $a_params["auth"] = TRUE;
            $a_params["username"] = $PEAR_SMTP_USER;
            $a_params["password"] = $PEAR_SMTP_PWD;
        }
        $mailer = Mail::factory("smtp",$a_params);
        if (!is_object($mailer))
        {
            ShowError("pear_error",GetMessage(MSG_PEAR_OBJ),FALSE,FALSE);
            exit;
        }
        if (get_class($mailer) === 'pear_error')
        {
            ShowError("pear_error",$mailer->getMessage(),FALSE,FALSE);
            exit;
        }
        if (!isset($a_headers['To']) && !isset($a_headers['to']))
            $a_headers['To'] = $s_to;
        if (!isset($a_headers['Subject']) && !isset($a_headers['subject']))
            $a_headers['Subject'] = $s_subject;
        $res = $mailer->send($s_to,$a_headers,$s_mesg);
        if ($res === TRUE)
            return (TRUE);
 
        global  $aAlertInfo;
 
        $aAlertInfo[] = GetMessage(MSG_PEAR_ERROR,array("MSG"=>$res->getMessage()));
        return (FALSE);
    }
    return (mail($s_to,$s_subject,$s_mesg,ExpandMailHeaders($a_headers)));
}
 
    //
    // Send an email
    //
function SendCheckedMail($to,$subject,$mesg,$sender,$a_headers = array())
{
    global  $PEAR_SMTP_HOST;
 
    $b_f_option = false;
    $b_form_option = IsMailOptionSet("SendMailFOption");    // this is superseded, but still supported
    if (SENDMAIL_F_OPTION || $b_form_option)
    {
        if (empty($sender))
        {
                //
                // SENDMAIL_F_OPTION with no sender is silently ignored
                //
            if ($b_form_option)
            {
                    //
                    // form has specified SendMailFOption, but there's no
                    // sender address
                    //
                static  $b_in_here = false;
                global  $SERVER;
 
                if (!$b_in_here)        // prevent infinite recursion
                {
                    $b_in_here = true;
                    SendAlert(GetMessage(MSG_NO_FOPT_ADDR));
                    $b_in_here = false;
                }
                    //
                    // if there's no from address, create a dummy one
                    //
                $sender = "dummy@".(isset($SERVER) ? $SERVER : "UnknownServer");
                $a_headers['From'] = $sender;
                $b_f_option = true;
            }
        }
        else
            $b_f_option = true;
    }
    if (INI_SET_FROM && !empty($sender))
        ini_set('sendmail_from',$sender);
 
    if ((!isset($PEAR_SMTP_HOST) || empty($PEAR_SMTP_HOST)) && $b_f_option)
        return (mail($to,$subject,$mesg,ExpandMailHeaders($a_headers),"-f$sender"));
    else
        return (DoMail($to,$subject,$mesg,$a_headers));
}
 
    //
    // Send an alert email
    //
function SendAlert($s_error,$b_filter = true,$b_non_error = false)
{
    global  $SPECIAL_VALUES,$FORMATTED_INPUT,$FROM_USER,$aServerVars,$aStrippedFormVars;
    global  $aAlertInfo,$aCleanedValues,$aFieldOrder;
 
    $s_error = str_replace("\n",BODY_LF,$s_error);
    $b_got_filter = (isset($SPECIAL_VALUES["filter"]) && !empty($SPECIAL_VALUES["filter"]));
 
        //
        // if there is a filter specified and we're not sending the alert
        // through the filter, don't show the user's data.  This is
        // on the assumption that the filter is an encryption program; so,
        // we don't want to send the user's data in clear text inside the
        // alerts.
        //
    $b_show_data = true;
    if ($b_got_filter && !$b_filter)
        $b_show_data = false;
 
    $s_form_subject = $s_alert_to = "";
    $b_check = true;
        //
        // might be too early to have $SPECIAL_VALUES set, so
        // look in the form vars too
        //
    if (isset($SPECIAL_VALUES["alert_to"]))
        $s_alert_to = trim($SPECIAL_VALUES["alert_to"]);
    if (empty($s_alert_to) && isset($aStrippedFormVars["alert_to"]))
        $s_alert_to = trim($aStrippedFormVars["alert_to"]);
 
    if (isset($SPECIAL_VALUES["subject"]))
        $s_form_subject = trim($SPECIAL_VALUES["subject"]);
    if (empty($s_form_subject) && isset($aStrippedFormVars["subject"]))
        $s_form_subject = trim($aStrippedFormVars["subject"]);
 
    if (empty($s_alert_to))
    {
        $s_alert_to = DEF_ALERT;
        $b_check = false;
    }
    if (!empty($s_alert_to))
    {
        $s_from_addr = $s_from = "";
        $a_headers = array();
        if (isset($FROM_USER) && !empty($FROM_USER))
        {
            if ($FROM_USER != "NONE")
            {
                $a_headers['From'] = $FROM_USER;
                $s_from = "From: $FROM_USER";
                $s_from_addr = $FROM_USER;
            }
        }
        else
        {
            global  $SERVER;
 
            $s_from_addr = "FormMail@".$SERVER;
            $a_headers['From'] = $s_from_addr;
            $s_from = "From: $s_from_addr";
        }
        $s_mesg = "To: ".UnMangle($s_alert_to).BODY_LF;
        if (!empty($s_from))
            $s_mesg .= $s_from.BODY_LF;
        $s_mesg .= BODY_LF;
        if (count($aAlertInfo) > 0)
        {
            if ($b_show_data)
            {
                $s_error .= BODY_LF.GetMessage(MSG_MORE_INFO).BODY_LF;
                $s_error .= implode(BODY_LF,$aAlertInfo);
            }
            else
                $s_error .= BODY_LF.GetMessage(MSG_INFO_STOPPED).BODY_LF;
        }
            //
            // some fields aren't security issues - show those in the alert
            //
        $a_safe_fields = array(
                    "email: ".$SPECIAL_VALUES["email"],
                    "realname: ".$SPECIAL_VALUES["realname"],
                        );
        $s_safe_data = implode(BODY_LF,$a_safe_fields);
 
        if ($b_non_error)
        {
            $s_preamble = $s_error.BODY_LF.BODY_LF;
            $s_mesg .= $s_preamble;
            $s_subj = GetMessage(MSG_FM_ALERT);
            if (!empty($s_form_subject))
                $s_subj .= " ($s_form_subject)";
        }
        else
        {
            $s_preamble = GetMessage(MSG_FM_ERROR_LINE).BODY_LF.
                            $s_error.BODY_LF.BODY_LF;
            $s_mesg .= $s_preamble;
            $s_subj = GetMessage(MSG_FM_ERROR);
            if (!empty($s_form_subject))
                $s_subj .= " ($s_form_subject)";
            $s_mesg .= $s_safe_data;
            $s_mesg .= BODY_LF.BODY_LF;
            if ($b_show_data)
                $s_mesg .= implode(BODY_LF,$FORMATTED_INPUT);
            else
                $s_mesg .= GetMessage(MSG_USERDATA_STOPPED);
        }
            
            /*
             * We only need to filter the form fields if the filter that
             * is specified is an encrypting filter.
             */
        if ($b_filter && $b_got_filter &&
                IsFilterAttribSet($SPECIAL_VALUES["filter"],"Encrypts"))
        {
            $s_new_mesg = $s_preamble.$s_safe_data;
            $s_new_mesg .= BODY_LF.BODY_LF;
 
            $s_filter = $SPECIAL_VALUES["filter"];
 
            if (($a_filter_list = GetFilterList()) !== false)
            {
                    //
                    // just filter the critical fields
                    //
                list($s_unfiltered,$s_filtered_results) =
                            GetFilteredOutput($aFieldOrder,$aCleanedValues,
                                    $s_filter,$a_filter_list);
                $s_new_mesg .= $s_unfiltered;
            }
            else
            {
                    //
                    // filter everything
                    //
                $s_filtered_results = Filter($s_filter,$s_mesg);
            }
            $s_new_mesg .= GetMessage(MSG_FILTERED,array("FILTER"=>$s_filter)).
                            BODY_LF.BODY_LF.
                            $s_filtered_results;
            $s_mesg = $s_new_mesg;
        }
        if (isset($aServerVars['HTTP_REFERER']))
            $s_mesg .= BODY_LF.BODY_LF."Referring page was ".$aServerVars['HTTP_REFERER'];
        elseif (isset($SPECIAL_VALUES['this_form']) && $SPECIAL_VALUES['this_form'] !== "")
            $s_mesg .= BODY_LF.BODY_LF."Referring form was ".$SPECIAL_VALUES['this_form'];
 
        if (isset($aServerVars['REMOTE_ADDR']))
            $s_mesg .= BODY_LF.BODY_LF."User IP address was ".$aServerVars['REMOTE_ADDR'];
 
        if ($b_check)
        {
            if (CheckEmailAddress($s_alert_to,$s_valid,$s_invalid))
                return (SendCheckedMail($s_valid,$s_subj,$s_mesg,$s_from_addr,$a_headers));
        }
        else
            return (SendCheckedMail($s_alert_to,$s_subj,$s_mesg,$s_from_addr,$a_headers));
    }
    return (false);
}
 
    //
    // Read the lines in a file and return an array.
    // Each line is stripped of line termination characters.
    //
function ReadLines($fp)
{
    $a_lines = array();
    while (!feof($fp))
    {
        $s_line = fgets($fp,4096);
            //
            // strip carriage returns and line feeds
            //
        $s_line = str_replace("\r","",$s_line);
        $s_line = str_replace("\n","",$s_line);
        $a_lines[] = $s_line;
    }
    return ($a_lines);
}
 
    //
    // Open a URL and return the data from it as a string.
    // Returns false on failure ($s_error has the error string)
    //
function GetURL($s_url,&$s_error)
{
    global  $php_errormsg,$aServerVars,$FM_VERS;
    global  $AUTHENTICATE,$AUTH_USER,$AUTH_PW;
 
        //
        // open the URL with the same session as we have
        //
    if (session_id() !== "")
        $s_url = AddURLParams($s_url,session_name()."=".urlencode(session_id()));
    if (defined("SID"))
        $s_url = AddURLParams($s_url,SID);
        //
        // parse the URL to get the component parts
        //
    $a_parts = parse_url($s_url);
        //
        // must have a host
        //
    if (!isset($a_parts["host"]))
    {
        $s_error = GetMessage(MSG_URL_PARSE);
        return (false);
    }
    $s_host_hdr = $a_parts["host"];
        //
        // if no port number is given, we support http and https
        //
    if (!isset($a_parts["port"]))
    {
        if (!isset($a_parts["scheme"]) || strtolower($a_parts["scheme"]) == "http")
            $a_parts["port"] = 80;
        elseif (strtolower($a_parts["scheme"]) == "https")
            $a_parts["port"] = 443;
        else
        {
           $s_error = GetMessage(MSG_URL_SCHEME,
                                    array("SCHEME"=>$a_parts["scheme"]));
           return (false);
        }
    }
    if ($a_parts["port"] == 443)
            //
            // fsockopen requires ssl:// in the host name
            //
        $a_parts["host"] = "ssl://".$a_parts["host"];
 
        //
        // default the path if empty
        //
    if (!isset($a_parts["path"]) || $a_parts["path"] === "")
        $a_parts["path"] = "/";
 
    $f_sock = @fsockopen($a_parts["host"],(int) $a_parts["port"],$i_errno,$s_errstr,30);
    if ($f_sock === false)
    {
        $s_error = GetMessage(MSG_SOCKET,
                            array("ERRNO"=>$i_errno,
                                "ERRSTR"=>$s_errstr,
                                "PHPERR"=>isset($php_errormsg) ? $php_errormsg : ""));
        return (false);
    }
 
    $s_req = $a_parts["path"];
        //
        // add the query to the path
        // Note that parse_url decodes the query string (urldecode), so
        // we need to split it into its component parameters
        // are re-encode their values.  Calling urlencode($a_parts["query"])
        // encodes the '=' between parameters and this breaks things.
        //
    if (isset($a_parts["query"]))
    {
        $a_params = explode('&',$a_parts["query"]);
        foreach ($a_params as $i_idx=>$s_param)
        {
            if (($i_pos = strpos($s_param,"=")) === false)
                $a_params[$i_idx] = urlencode($s_param);
            else
                $a_params[$i_idx] = substr($s_param,0,$i_pos).'='.
                                        urlencode(substr($s_param,$i_pos+1));
        }
        $s_req .= '?'.implode('&',$a_params);
    }
 
        //
        // add the fragment to the path.  Note, however, this
        // won't actually make the user's browser jump to that
        // location (because we'd need to alter our current URL
        // and add the fragment to achieve that - we might
        // add that feature in a later version if we can
        // figure out how to do it!)
        //
    if (isset($a_parts["fragment"]))
        $s_req .= '#'.urlencode($a_parts["fragment"]);
 
        //
        // Since we might be opening a URL within the same session, we can
        // get locks.  So, close the session for writing to prevent this.
        //
    if (function_exists('session_write_close'))
    {
        session_write_close();
        ob_flush();             // probably a good idea
    }
        //
        // the GET request
        //
    fputs($f_sock,"GET ".$s_req." HTTP/1.0\r\n");
 
        //
        // Determine authentication requirements
        //
    if ($AUTHENTICATE !== "" || $AUTH_USER !== "" || $AUTH_PW !== "")
    {
        if ($AUTHENTICATE === "")
            fputs($f_sock,"Authorization: Basic ".
                        base64_encode("$AUTH_USER:$AUTH_PW")."\r\n");
        else
            fputs($f_sock,"Authorization: $AUTHENTICATE\r\n");
 
    }
    else
    {
        if (isset($a_parts["user"]) || isset($a_parts["pass"]))
        {
            $s_auth_user = isset($a_parts["user"]) ? $a_parts["user"] : "";
            $s_auth_pass = isset($a_parts["pass"]) ? $a_parts["pass"] : "";
        }
        else
        {
            $s_auth_type = isset($aServerVars["PHP_AUTH_TYPE"]) ? $aServerVars["PHP_AUTH_TYPE"] : "";
            $s_auth_user = isset($aServerVars["PHP_AUTH_USER"]) ? $aServerVars["PHP_AUTH_USER"] : "";
            $s_auth_pass = isset($aServerVars["PHP_AUTH_PW"]) ? $aServerVars["PHP_AUTH_PW"] : "";
        }
        if (!isset($s_auth_type) || $s_auth_type === "")
            $s_auth_type = "Basic";
            //
            // Add the authentication header
            //
        if ($s_auth_user !== "" || $s_auth_pass !== "")
            fputs($f_sock,"Authorization: $s_auth_type ".
                        base64_encode("$s_auth_user:$s_auth_pass")."\r\n");
    }
 
        //
        // Specify the host name
        //
    fputs($f_sock,"Host: $s_host_hdr\r\n");
        //
        // Specify the user agent
        //
    fputs($f_sock,"User-Agent: FormMail/$FM_VERS (from www.tectite.com)\r\n");
        //
        // Accept any output
        //
    fputs($f_sock,"Accept: */*\r\n");
        //
        // End of request headers
        //
    fputs($f_sock,"\r\n");
 
        //
        // Read and parse the response header
        //
    $i_http_code = 0;
    $s_status = "";
    while (!feof($f_sock))
    {
        $s_line = fgets($f_sock,4096);
        if ($s_line == "\r\n" || $s_line == "\n")
            break;
        if (substr($s_line,0,4) == "HTTP")
        {
            $i_pos = strpos($s_line," ");
            $s_status = substr($s_line,$i_pos+1);
            $i_end_pos = strpos($s_status," ");
            if ($i_end_pos === false)
                $i_end_pos = strlen($s_status);
            $i_http_code = (int) substr($s_status,0,$i_end_pos);
        }
    }
    if ($i_http_code < 200 || $i_http_code > 299)
    {
        $s_error = GetMessage(MSG_GETURL_OPEN,array("STATUS"=>$s_status));
        $m_buf = false;
    }
    else
    {
            //
            // read content into one big string buffer and return
            //
        $m_buf = "";
        while (!feof($f_sock))
            $m_buf .= fread($f_sock,1024);
    }
    fclose($f_sock);
        //
        // re-open our session
        //
    session_start();
    return ($m_buf);
}
 
    //
    // Load a template file into a string.
    //
function LoadTemplate($s_name,$s_dir,$s_url,$b_ret_lines = false)
{
    global  $php_errormsg;
 
    $s_buf = "";
    $a_lines = array();
    if (!empty($s_dir))
    {
        $s_name = "$s_dir/".basename($s_name);
@       $fp = fopen($s_name,"r");
        if ($fp === false)
        {
            SendAlert(GetMessage(MSG_OPEN_TEMPLATE,array("NAME"=>$s_name,
                                                    "ERROR"=>CheckString($php_errormsg))));
            return (false);
        }
        if ($b_ret_lines)
            $a_lines = ReadLines($fp);
        else
                //
                // load the whole template into a string
                //
            $s_buf = fread($fp,filesize($s_name));
        fclose($fp);
    }
    else
    {
        global  $aServerVars;
 
        $s_name = "$s_url/".basename($s_name);
        if (isset($aServerVars['HTTP_USER_AGENT']))
            $s_name = AddURLParams($s_name,"USER_AGENT=".$aServerVars['HTTP_USER_AGENT']);
 
            //
            // open the URL with the same session as we have
            //
        if (session_id() !== "")
            $s_name = AddURLParams($s_name,session_name()."=".urlencode(session_id()));
        if (defined("SID"))
            $s_name = AddURLParams($s_name,SID);
 
            //
            // Since we might be opening a URL within the same session, we can
            // get locks.  So, close the session for writing to prevent this.
            //
        if (function_exists('session_write_close'))
        {
            session_write_close();
            ob_flush();             // probably a good idea
        }
 
@       $fp = fopen($s_name,"r");
        if ($fp === false)
        {
            SendAlert(GetMessage(MSG_OPEN_TEMPLATE,array("NAME"=>$s_name,
                                                    "ERROR"=>CheckString($php_errormsg))));
            return (false);
        }
        if ($b_ret_lines)
            $a_lines = ReadLines($fp);
        else
                //
                // load the whole template into a string
                //
            while (!feof($fp))
                $s_buf .= fread($fp,4096);
        fclose($fp);
            //
            // now re-open our session
            //
        session_start();
    }
    return ($b_ret_lines ? $a_lines : $s_buf);
}
 
    //
    // To show an error template.  The template must be HTML and, for security
    // reasons, must be a file on the server in the directory specified
    // by $TEMPLATEDIR or $TEMPLATEURL.
    // $a_specs is an array of substitutions to perform, as follows:
    //      tag-name    replacement string
    //
    // For example:
    //      "fmerror"=>"An error message"
    //
function ShowErrorTemplate($s_name,$a_specs,$b_user_error)
{
    global  $TEMPLATEURL,$TEMPLATEDIR;
 
    if (empty($TEMPLATEDIR) && empty($TEMPLATEURL))
    {
        SendAlert(GetMessage(MSG_TEMPLATES));
        return (false);
    }
    if (($s_buf = LoadTemplate($s_name,$TEMPLATEDIR,$TEMPLATEURL)) === false)
        return (false);
 
        //
        // now look for the tags to replace
        //
    foreach ($a_specs as $s_tag=>$s_value)
            //
            // search for
            //      <tagname/>
            // with optional whitespace
            //
        $s_buf = preg_replace('/<\s*'.preg_quote($s_tag,"/").'\s*\/\s*>/ims',
                            nl2br($s_value),$s_buf);
    if ($b_user_error)
    {
            // strip any <fmusererror> and </fmusererror> tags
            //
            // You can show information that's specific to user
            // errors between these special tags.
            //
        $s_buf = preg_replace('/<\s*\/?\s*fmusererror\s*>/ims','',$s_buf);
            //
            // since this isn't a system error, strip anything between
            // <fmsyserror> and </fmsyserror>
            //
        $s_buf = preg_replace('/<\s*fmsyserror\s*>.*<\s*\/\s*fmsyserror\s*>/ims','',$s_buf);
    }
    else
    {
            // strip any <fmsyserror> and </fmsyserror> tags
            //
            // You can show information that's specific to system
            // errors between these special tags.
            //
        $s_buf = preg_replace('/<\s*\/?\s*fmsyserror\s*>/ims','',$s_buf);
            //
            // since this isn't a user error, strip anything between
            // <fmusererror> and </fmusererror>
            //
        $s_buf = preg_replace('/<\s*fmusererror\s*>.*<\s*\/\s*fmusererror\s*>/ims','',$s_buf);
    }
        //
        // just output the page
        //
    echo $s_buf;
    return (true);
}
 
    //
    // To show an error to the user.
    //
function ShowError($error_code,$error_mesg,$b_user_error,
                $b_alerted = false,$a_item_list = array(),$s_extra_info = "")
{
    global  $SPECIAL_FIELDS,$SPECIAL_MULTI,$SPECIAL_VALUES;
    global  $aServerVars,$aSessionVars,$aStrippedFormVars;
 
        //
        // Testing with PHP 4.0.6 indicates that sessions don't always work.
        // So, we'll also add the error to the URL, unless
        // PUT_DATA_IN_URL is false.
        //
    $aSessionVars["FormError"] = $error_mesg;
    $aSessionVars["FormErrorInfo"] = $s_extra_info;
    $aSessionVars["FormErrorCode"] = $error_code;
    $aSessionVars["FormErrorItems"] = $a_item_list;
    $aSessionVars["FormIsUserError"] = $b_user_error;
    $aSessionVars["FormAlerted"] = $b_alerted;
    $aSessionVars["FormData"] = array();
 
    $bad_url = $SPECIAL_VALUES["bad_url"];
    $bad_template = $SPECIAL_VALUES["bad_template"];
    $this_form = $SPECIAL_VALUES["this_form"];
    if (!empty($bad_url))
    {
        $a_params = array();
        $a_params[] = "this_form=".urlencode("$this_form");
        $a_params[] = "bad_template=".urlencode("$bad_template");
        if (PUT_DATA_IN_URL)
        {
            $a_params[] = "error=".urlencode("$error_mesg");
            $a_params[] = "extra=".urlencode("$s_extra_info");
            $a_params[] = "errcode=".urlencode("$error_code");
            $a_params[] = "isusererror=".($b_user_error ? "1" : "0");
            $a_params[] = "alerted=".($b_alerted ? "1" : "0");
            $i_count = 1;
            foreach ($a_item_list as $s_item)
            {
                $a_params[] = "erroritem$i_count=".urlencode("$s_item");
                $i_count++;
            }
        }
        else
                //
                // tell the bad_url to look in the session only
                //
            $a_params[] = "insession=1";
            //
            // Add the posted data to the URL so that an intelligent
            // $bad_url can call the form again
            //
        foreach ($aStrippedFormVars as $s_name=>$m_value)
        {
                //
                // skip special fields
                //
            $b_special = false;
            if (in_array($s_name,$SPECIAL_FIELDS))
                $b_special = true;
            else
            {
                foreach ($SPECIAL_MULTI as $s_multi_fld)
                {
                    $i_len = strlen($s_multi_fld);
                    if (substr($s_name,0,$i_len) == $s_multi_fld)
                    {
                        $i_index = (int) substr($s_name,$i_len);
                        if ($i_index > 0)
                        {
                            $b_special = true;
                            break;
                        }
                    }
                }
            }
            if (!$b_special)
            {
                if (PUT_DATA_IN_URL)
                {
                    if (is_array($m_value))
                        foreach ($m_value as $s_value)
                            $a_params[] = "$s_name".'[]='.
                                        urlencode(substr($s_value,0,MAXSTRING));
                    else
                        $a_params[] = "$s_name=".urlencode(substr($m_value,0,MAXSTRING));
                }
                else
                {
                    if (is_array($m_value))
                        $aSessionVars["FormData"]["$s_name"] = $m_value;
                    else
                        $aSessionVars["FormData"]["$s_name"] = substr($m_value,0,MAXSTRING);
                }
            }
        }
            //
            // Now add the authentication data, if any
            //
        if ((isset($aServerVars["PHP_AUTH_USER"]) &&
                $aServerVars["PHP_AUTH_USER"] !== "") ||
            (isset($aServerVars["PHP_AUTH_PW"]) &&
                $aServerVars["PHP_AUTH_PW"] !== ""))
        {
            if (PUT_DATA_IN_URL)
            {
                if (isset($aServerVars["PHP_AUTH_USER"]))
                    $a_params[] = "PHP_AUTH_USER=".urlencode($aServerVars["PHP_AUTH_USER"]);
 
                if (isset($aServerVars["PHP_AUTH_PW"]))
                    $a_params[] = "PHP_AUTH_PW=".urlencode($aServerVars["PHP_AUTH_PW"]);
 
                if (isset($aServerVars["PHP_AUTH_TYPE"]))
                    $a_params[] = "PHP_AUTH_TYPE=".urlencode($aServerVars["PHP_AUTH_TYPE"]);
            }
            else
            {
                if (isset($aServerVars["PHP_AUTH_USER"]))
                    $aSessionVars["FormData"]["PHP_AUTH_USER"] = $aServerVars["PHP_AUTH_USER"];
 
                if (isset($aServerVars["PHP_AUTH_PW"]))
                    $aSessionVars["FormData"]["PHP_AUTH_PW"] = $aServerVars["PHP_AUTH_PW"];
 
                if (isset($aServerVars["PHP_AUTH_TYPE"]))
                    $aSessionVars["FormData"]["PHP_AUTH_TYPE"] = $aServerVars["PHP_AUTH_TYPE"];
            }
        }
        $bad_url = AddURLParams($bad_url,$a_params,false);
        Redirect($bad_url);
    }
    else
    {
        if (!empty($bad_template))
        {
            $a_specs = array("fmerror"=>htmlspecialchars("$error_mesg"),
                            "fmerrorcode"=>htmlspecialchars("$error_code"),
                            "fmfullerror"=>htmlspecialchars("$error_mesg")."\n".
                                            htmlspecialchars("$s_extra_info"),
                            "fmerrorextra"=>htmlspecialchars("$s_extra_info"),);
            $i_count = 1;
            foreach ($a_item_list as $s_item)
            {
                $a_specs["fmerroritem$i_count"] = htmlspecialchars($s_item);
                $i_count++;
            }
            $s_list = "";
            foreach ($a_item_list as $s_item)
                $s_list .= "<li>".htmlspecialchars($s_item)."</li>\n";
            $a_specs["fmerroritemlist"] = $s_list;
            if (ShowErrorTemplate($bad_template,$a_specs,$b_user_error))
                return;
        }
        $s_text = GetMessage(MSG_ERROR_PROC);
        if ($b_user_error)
            $s_text .= $error_mesg."\n".$s_extra_info;
        else
        {
            if ($b_alerted)
                $s_text .= GetMessage(MSG_ALERT_DONE);
            else
                $s_text .= GetMessage(MSG_PLS_CONTACT);
            $s_text .= GetMessage(MSG_APOLOGY);
        }
        CreatePage($s_text);
            //
            // the session data is not needed now
            //
        ZapSession();
    }
}
 
    //
    // Report an error.  Same as Error, but implements
    // ATTACK_DETECTION_IGNORE_ERRORS.
    //
function ErrorWithIgnore($error_code,$error_mesg,$b_filter = true,$show = true,$int_mesg = "")
{
    $b_alerted = false;
    if (!ATTACK_DETECTION_IGNORE_ERRORS)
        if (SendAlert("$error_code\n *****$int_mesg*****\nError=$error_mesg\n",$b_filter))
            $b_alerted = true;
    if ($show)
        ShowError($error_code,$error_mesg,false,$b_alerted);
    else
            //
            // show something to the user
            //
        ShowError($error_code,GetMessage(MSG_SUBM_FAILED),false,$b_alerted);
    exit;
}
 
    //
    // Report an error
    //
function Error($error_code,$error_mesg,$b_filter = true,$show = true,$int_mesg = "")
{
    $b_alerted = false;
    if (SendAlert("$error_code\n *****$int_mesg*****\nError=$error_mesg\n",$b_filter))
        $b_alerted = true;
    if ($show)
        ShowError($error_code,$error_mesg,false,$b_alerted);
    else
            //
            // show something to the user
            //
        ShowError($error_code,GetMessage(MSG_SUBM_FAILED),false,$b_alerted);
    exit;
}
 
    //
    // Report a user error
    //
function UserError($s_error_code,$s_error_mesg,
                    $s_extra_info = "",$a_item_list = array())
{
    $b_alerted = false;
    if (ALERT_ON_USER_ERROR &&
            SendAlert("$s_error_code\nError=$s_error_mesg\n$s_extra_info\n"))
        $b_alerted = true;
    ShowError($s_error_code,$s_error_mesg,true,$b_alerted,$a_item_list,$s_extra_info);
    exit;
}
 
    //
    // Create a simple page with the given text.
    //
function CreatePage($text)
{
    global  $FM_VERS,$sHTMLCharSet;
 
    echo "<html>\n";
    echo "<head>\n";
    if (isset($sHTMLCharSet) && $sHTMLCharSet !== "")
        echo "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=$sHTMLCharSet\">\n";
    echo "</head>\n";
    echo "<body>\n";
    echo nl2br($text);
    echo "<p /><p><small>";
    echo GetMessage(MSG_ABOUT_FORMMAIL,array("FM_VERS"=>$FM_VERS,
                                            "TECTITE"=>"www.tectite.com"));
    echo "</small></p>\n";
    echo "</body>\n";
    echo "</html>\n";
}
 
    //
    // Strip slashes if magic_quotes_gpc is set.
    //
function StripGPC($s_value)
{
    if (get_magic_quotes_gpc() != 0)
        $s_value = stripslashes($s_value);
    return ($s_value);
}
 
    //
    // return an array, stripped of slashes if magic_quotes_gpc is set
    //
function StripGPCArray($a_values)
{
    if (get_magic_quotes_gpc() != 0)
        foreach ($a_values as $m_key=>$m_value)
            if (is_array($m_value))
                    //
                    // strip arrays recursively
                    //
                $a_values[$m_key] = StripGPCArray($m_value);
            else
                    //
                    // convert scalar to string and strip
                    //
                $a_values[$m_key] = stripslashes("$m_value");
    return ($a_values);
}
 
    //
    // Strip a value of unwanted characters, which might be hacks.
    // If $b_conv_quotes is true, also swaps all double quotes with single quotes.
    //
function Strip($value,$b_conv_quotes = true)
{
    if ($b_conv_quotes)
            //
            // "standard" quote conversion
            //
        $value = str_replace("\"","'",$value);
    $value = preg_replace('/[[:cntrl:][:space:]]+/'," ",$value);    // zap all control chars and multiple blanks
    return ($value);
}
 
    //
    // Clean a value.  This means:
    //  1. convert to string
    //  2. truncate to maximum length
    //  3. strip the value of unwanted or dangerous characters (hacks)
    //  4. trim both ends of whitespace
    // Each element of an array is cleaned as above.  This process occurs
    // recursively, so arrays of arrays work OK too (though there's no
    // need for that in this program).
    //
    // Non-scalar values are changed to the string "<X>" where X is the type.
    // In general, FormMail won't receive non-scalar non-array values, so this
    // is more a future-proofing measure.
    //
function CleanValue($m_value,$b_conv_quotes = true)
{
    if (is_array($m_value))
    {
        foreach ($m_value as $m_key=>$m_item)
            $m_value[$m_key] = CleanValue($m_item,$b_conv_quotes);
    }
    elseif (!is_scalar($m_value))
        $m_value = "<".gettype($m_value).">";
    else
    {
            //
            // convert to string and truncate
            //
        $m_value = substr("$m_value",0,MAXSTRING);
            //
            // strip unwanted chars and trim
            //
        $m_value = trim(Strip($m_value,$b_conv_quotes));
    }
    return ($m_value);
}
 
    //
    // Clean a special value.  Special values listed in $SPECIAL_NOSTRIP
    // will not be cleaned.
    //
function SpecialCleanValue($s_name,$m_value)
{
    global  $SPECIAL_NOSTRIP;
 
    if (!in_array($s_name,$SPECIAL_NOSTRIP))
        $m_value = CleanValue($m_value);
    return ($m_value);
}
 
    //
    // Return the fields and their values in a string containing one
    // field per line.
    //
function MakeFieldOutput($a_order,$a_fields,$s_line_feed = BODY_LF)
{
    $n_order = count($a_order);
    $s_output = "";
    for ($ii = 0 ; $ii < $n_order ; $ii++)
    {
        $s_name = $a_order[$ii];
        if (isset($a_fields[$s_name]))
            $s_output .= "$s_name: ".$a_fields[$s_name].$s_line_feed;
    }
    return ($s_output);
}
 
    //
    // Check if a field name is special. Returns true if it is.
    //
function IsSpecialField($s_name)
{
    global  $SPECIAL_FIELDS;
 
    return (in_array($s_name,$SPECIAL_FIELDS));
}
 
    //
    // Set a special field value.
    //
function SetSpecialField($s_name,$m_value)
{
    global  $SPECIAL_VALUES;
 
        //
        // special values cannot be arrays; ignore them if they are
        //
    if (!is_array($m_value))
        $SPECIAL_VALUES[$s_name] = SpecialCleanValue($s_name,$m_value);
}
 
    //
    // Check if a field name is a special "multi" field.
    // A multi field is the name plus a sequence number.  For example,
    //      conditions1
    //      conditions2
    // Returns a list (array) if it is, otherwise false if not.
    // The list contains:
    //      1. the name of the special multi field
    //      2. the index number for multi field
    //
function IsSpecialMultiField($s_name)
{
    global  $SPECIAL_MULTI;
 
    foreach ($SPECIAL_MULTI as $s_multi_fld)
    {
        $i_len = strlen($s_multi_fld);
            //
            // look for nameN where N is a number starting from 1
            //
        if (substr($s_name,0,$i_len) == $s_multi_fld)
        {
            $i_index = (int) substr($s_name,$i_len);
            if ($i_index > 0)
            {
                    //
                    // re-index to zero
                    //
                --$i_index;
                return (array($s_multi_fld,$i_index));
            }
        }
    }
    return (false);
}
 
    //
    // Set a multi field value.
    //
function SetSpecialMultiField($s_name,$i_index,$m_value)
{
    global  $SPECIAL_VALUES;
 
        //
        // special fields cannot be arrays - ignore if it is
        //
    if (!is_array($m_value))
        $SPECIAL_VALUES[$s_name][$i_index] = SpecialCleanValue($s_name,$m_value);
}
 
    //
    // Process a field
    //
function ProcessField($s_name,$raw_value,&$a_order,&$a_fields,&$a_raw_fields)
{
    global  $FORMATTED_INPUT;
 
        //
        // fields go into an array of special values or an array of other values
        //
    $b_special = false;
    if (IsSpecialField($s_name))
    {
        SetSpecialField($s_name,$raw_value);
        $b_special = true;
    }
        //
        // check for multiple valued special fields
        //
    if (($a_multi_fld = IsSpecialMultiField($s_name)) !== false)
    {
        SetSpecialMultiField($a_multi_fld[0],$a_multi_fld[1],$raw_value);
        $b_special = true;
    }
    if (!$b_special)
    {
            //
            // return the raw value unchanged in the $a_raw_fields array
            //
        $a_raw_fields[$s_name] = $raw_value;
            //
            // handle checkboxes and multiple-selection lists
            // Thanks go to Theodore Boardman for the suggestion
            // and initial working code.
            //
        if (is_array($raw_value))
        {
                //
                // the array must be an array of scalars (not an array
                // of arrays, for example)
                //
            if (is_scalar($raw_value[0]))
            {
                $a_cleaned_values = CleanValue($raw_value);
                    //
                    // the output is a comma separated list of values for the
                    // checkbox.  For example,
                    //          events: Diving,Cycling,Running
                    //
                    // Set the clean value to the list of cleaned checkbox
                    // values.
                    // First, remove any commas in the values themselves.
                    //
                $a_cleaned_values = str_replace(",","",$a_cleaned_values);
                $s_cleaned_value = implode(",",$a_cleaned_values);
            }
            else
                $s_cleaned_value = "<invalid list>";
        }
        else
        {
                //
                // NOTE: there is a minor bug here now that we support
                // $FORM_INI_FILE. The INI file is processed at the end
                // so if you set the mail_options below in the INI file they
                // won't get processed here.  This means you must set
                // the following mail_options in the HTML form for now.
                // (To be fixed at a later date.  RJR 17-Feb-06).
                //
 
                //
                // if the form specifies the "KeepLines" option,
                // don't strip new lines
                //
            if (IsMailOptionSet("KeepLines") && strpos($raw_value,"\n") !== false)
            {
                    //
                    // truncate first
                    //
                $s_truncated = substr("$raw_value",0,MAXSTRING);
                    //
                    // split into lines, clean each individual line,
                    // then put it back together again
                    //
                $a_lines = explode("\n",$s_truncated);
                $a_lines = CleanValue($a_lines);
                $s_cleaned_value = implode(BODY_LF,$a_lines);
                    //
                    // and, for this special case, prepend a new line
                    // so that the value is shown on a fresh line
                    //
                $s_cleaned_value = BODY_LF.$s_cleaned_value;
            }
            else
                $s_cleaned_value = CleanValue($raw_value);
        }
            //
            // if the form specifies the "NoEmpty" option, skip
            // empty values.
            //
        if (!IsMailOptionSet("NoEmpty") || !IsFieldEmpty($s_cleaned_value))
            if (!IsMailExcluded($s_name))
            {
                    //
                    // by default, we maintain the order as passed in
                    // the HTTP request
                    //
                $a_order[] = $s_name;
                $a_fields[$s_name] = $s_cleaned_value;
            }
 
            //
            // add to the $FORMATTED_INPUT array for debugging and
            // error reporting
            //
        array_push($FORMATTED_INPUT,"$s_name: '$s_cleaned_value'");
    }
}
 
    //
    // Parse the input variables and return:
    //  1. an array that specifies the required field order in the output
    //  2. an array containing the non-special cleaned field values indexed
    //     by field name.
    //  3. an array containing the non-special raw field values indexed by
    //     field name.
    //
function ParseInput($a_vars)
{
    $a_order = array();
    $a_fields = array();
    $a_raw_fields = array();
        //
        // scan the array of values passed in (name-value pairs) and
        // produce slightly formatted (not HTML) textual output
        // and extract any special values found.
        //
    foreach ($a_vars as $s_name=>$raw_value)
        ProcessField($s_name,$raw_value,$a_order,$a_fields,$a_raw_fields);
 
    return (array($a_order,$a_fields,$a_raw_fields));
}
 
    //
    // Get the URL for sending to the CRM.
    //
function GetCRMURL($spec,$vars,$url)
{
    $bad = false;
    $list = TrimArray(explode(",",$spec));
    $map = array();
    for ($ii = 0 ; $ii < count($list) ; $ii++)
    {
        $name = $list[$ii];
        if ($name)
        {
                //
                // the specification must be in this format:
                //      form-field-name:CRM-field-name
                //
            if (($i_crm_name_pos = strpos($name,":")) > 0)
            {
                $s_crm_name = substr($name,$i_crm_name_pos + 1);
                $name = substr($name,0,$i_crm_name_pos);
                if (isset($vars[$name]))
                {
                    $map[] = $s_crm_name."=".urlencode($vars[$name]);
                    $map[] = "Orig_".$s_crm_name."=".urlencode($name);
                }
            }
            else
            {
                    //
                    // not the right format, so just include as a parameter
                    // check for name=value format to choose encoding
                    //
                $a_values = explode("=",$name);
                if (count($a_values) > 1)
                    $map[] = urlencode($a_values[0])."=".urlencode($a_values[1]);
                else
                    $map[] = urlencode($a_values[0]);
            }
        }
    }
    if (count($map) == 0)
        return ("");
    return (AddURLParams($url,$map,false));
}
 
    //
    // strip the HTML from a string
    //
function StripHTML($s_str,$s_line_feed = "\n")
{
        //
        // strip HTML comments (s option means include new lines in matches)
        //
    $s_str = preg_replace('/<!--([^-]*([^-]|-([^-]|-[^>])))*-->/s','',$s_str);
        //
        // strip any scripts (i option means case-insensitive)
        //
    $s_str = preg_replace('/<script[^>]*?>.*?<\/script[^>]*?>/si','',$s_str);
        //
        // replace paragraphs with new lines (line feeds)
        //
    $s_str = preg_replace('/<p[^>]*?>/i',$s_line_feed,$s_str);
        //
        // replace breaks with new lines (line feeds)
        //
    $s_str = preg_replace('/<br[[:space:]]*\/?[[:space:]]*>/i',$s_line_feed,$s_str);
        //
        // overcome this bug: http://bugs.php.net/bug.php?id=21311
        //
    $s_str = preg_replace('/<![^>]*>/s','',$s_str);
        //
        // get rid of all HTML tags
        //
    $s_str = strip_tags($s_str);
    return ($s_str);
}
 
    //
    // Check for valid URL in TARGET_URLS
    //
function CheckValidURL($s_url)
{
    global  $TARGET_URLS;
 
    foreach ($TARGET_URLS as $s_prefix)
        if (!empty($s_prefix) &&
                strtolower(substr($s_url,0,strlen($s_prefix))) ==
                strtolower($s_prefix))
            return (true);
    return (false);
}
 
    //
    // Scan the given data for fields returned from the CRM.
    // A field has this following format:
    //      __FIELDNAME__=value
    // terminated by a line feed.
    //
function FindCRMFields($s_data)
{
    $a_ret = array();
    if (preg_match_all('/^__([A-Za-z][A-Za-z0-9_]*)__=(.*)$/m',$s_data,$a_matches) === false)
        SendAlert(GetMessage(MSG_PREG_FAILED));
    else
    {
        $n_matches = count($a_matches[0]);
    //  SendAlert("$n_matches on '$s_data'");
        for ($ii = 0 ; $ii < $n_matches ; $ii++)
            if (isset($a_matches[1][$ii]) && isset($a_matches[2][$ii]))
                $a_ret[$a_matches[1][$ii]] = $a_matches[2][$ii];
    }
    return ($a_ret);
}
 
    //
    // open the given URL to send data to it, we expect the response
    // to contain at least '__OK__=' followed by true or false
    //
function SendToCRM($s_url,&$a_data)
{
    global  $php_errormsg;
 
    if (!CheckValidURL($s_url))
    {
        SendAlert(GetMessage(MSG_URL_INVALID,array("URL"=>$s_url)));
        return (false);
    }
@   $fp = fopen($s_url,"r");
    if ($fp === false)
    {
        SendAlert(GetMessage(MSG_URL_OPEN,array("URL"=>$s_url,
                                        "ERROR"=>CheckString($php_errormsg))));
        return (false);
    }
    $s_mesg = "";
    while (!feof($fp))
    {
        $s_line = fgets($fp,4096);
        $s_mesg .= $s_line;
    }
    fclose($fp);
    $s_mesg = StripHTML($s_mesg);
    $s_result = preg_match('/__OK__=(.*)/',$s_mesg,$a_matches);
    if (count($a_matches) < 2 || $a_matches[1] === "")
    {
            //
            // no agreed __OK__ value returned - assume system error
            //
        SendAlert(GetMessage(MSG_CRM_FAILED,array("URL"=>$s_url,
                                                "MSG"=>$s_mesg)));
        return (false);
    }
        //
        // look for fields to return
        //
    $a_data = FindCRMFields($s_mesg);
        //
        // check for success or user error
        //
    switch (strtolower($a_matches[1]))
    {
    case "true":
        break;
    case "false":
            //
            // check for user error
            //
        if (isset($a_data["USERERRORCODE"]))
        {
            $s_error_code = "crm_error";
            $s_error_mesg = GetMessage(MSG_CRM_FORM_ERROR);
            $s_error_code .= $a_data["USERERRORCODE"];
            if (isset($a_data["USERERRORMESG"]))
                $s_error_mesg = $a_data["USERERRORMESG"];
            UserError($s_error_code,$s_error_mesg);
                // no return
        }
        return (false);
    }
    return (true);
}
 
    //
    // Split into field name and friendly name; returns an array with
    // two elements.
    // Format is:
    //      fieldname:Nice printable name for displaying
    //
function GetFriendlyName($s_name)
{
    if (($i_pos = strpos($s_name,':')) === false)
        return (array(trim($s_name),trim($s_name)));
    return (array(trim(substr($s_name,0,$i_pos)),trim(substr($s_name,$i_pos+1))));
}
 
define("REQUIREDOPS","|^!=");       // operand characters for advanced required processing
 
    //
    // Perform a field comparison test.
    //
function FieldTest($s_oper,$s_fld1,$s_fld2,$a_vars,&$s_error_mesg,
                        $s_friendly1 = "",$s_friendly2 = "")
{
    $b_ok = true;
        //
        // perform the test
        //
    switch ($s_oper)
    {
    case '&':       // both fields must be present
        if (!TestFieldEmpty($s_fld1,$a_vars,$s_empty1) &&
            !TestFieldEmpty($s_fld2,$a_vars,$s_empty2))
            ;       // OK
        else
        {
                //
                // failed
                //
            $s_error_mesg = GetMessage(MSG_AND,array("ITEM1"=>$s_friendly1,
                                                    "ITEM2"=>$s_friendly2));
            $b_ok = false;
        }
        break;
    case '|':       // either field or both must be present
        if (!TestFieldEmpty($s_fld1,$a_vars,$s_empty1) ||
            !TestFieldEmpty($s_fld2,$a_vars,$s_empty2))
            ;       // OK
        else
        {
                //
                // failed
                //
            $s_error_mesg = GetMessage(MSG_OR,array("ITEM1"=>$s_friendly1,
                                                    "ITEM2"=>$s_friendly2));
            $b_ok = false;
        }
        break;
    case '^':       // either field but not both must be present
        $b_got1 = !TestFieldEmpty($s_fld1,$a_vars,$s_empty1);
        $b_got2 = !TestFieldEmpty($s_fld2,$a_vars,$s_empty2);
        if ($b_got1 || $b_got2)
        {
            if ($b_got1 && $b_got2)
            {
                    //
                    // failed
                    //
                $s_error_mesg = GetMessage(MSG_NOT_BOTH,
                                            array("ITEM1"=>$s_friendly1,
                                                  "ITEM2"=>$s_friendly2));
                $b_ok = false;
            }
        }
        else
        {
                //
                // failed
                //
            $s_error_mesg = GetMessage(MSG_XOR,
                                        array("ITEM1"=>$s_friendly1,
                                              "ITEM2"=>$s_friendly2));
            $b_ok = false;
        }
        break;
    case '!=':
    case '=':
        $b_got1 = !TestFieldEmpty($s_fld1,$a_vars,$s_empty1);
        $b_got2 = !TestFieldEmpty($s_fld2,$a_vars,$s_empty2);
        if ($b_got1 && $b_got2)
            $b_match = (GetFieldValue($s_fld1,$a_vars) ==
                            GetFieldValue($s_fld2,$a_vars));
        elseif (!$b_got1 && !$b_got2)
                //
                // haven't got either value - they match
                //
            $b_match = true;
        else
                //
                // got one value, but not the other - they don't match
                //
            $b_match = false;
        if ($s_oper != '=')
        {
                //
                // != operator
                //
            $b_match = !$b_match;
            $s_desc = GetMessage(MSG_IS_SAME_AS,
                                        array("ITEM1"=>$s_friendly1,
                                              "ITEM2"=>$s_friendly2));
        }
        else
            $s_desc = GetMessage(MSG_IS_NOT_SAME_AS,
                                        array("ITEM1"=>$s_friendly1,
                                              "ITEM2"=>$s_friendly2));
        if (!$b_match)
        {
                //
                // failed
                //
            $s_error_mesg = $s_desc;
            $b_ok = false;
        }
        break;
    }
    return ($b_ok);
}
 
    //
    // Process advanced "required" conditionals
    //
function AdvancedRequired($s_cond,$i_span,$a_vars,&$s_missing,&$a_missing_list)
{
    $b_ok = true;
        //
        // get first field name
        //
    list($s_fld1,$s_friendly1) = GetFriendlyName(substr($s_cond,0,$i_span));
        //
        // get the operator
        //
    $s_rem = substr($s_cond,$i_span);
    $i_span = strspn($s_rem,REQUIREDOPS);
    $s_oper = substr($s_rem,0,$i_span);
    switch ($s_oper)
    {
    case '|':
    case '^':
    case '=':
    case '!=':
            //
            // second component is a field name
            //
        list($s_fld2,$s_friendly2) = GetFriendlyName(substr($s_rem,$i_span));
        if (!FieldTest($s_oper,$s_fld1,$s_fld2,$a_vars,$s_error_mesg,
                                                    $s_friendly1,$s_friendly2))
        {
                //
                // failed
                //
            $s_missing .= "$s_error_mesg\n";
            $a_missing_list[] = "$s_error_mesg";
            $b_ok = false;
        }
        break;
    default:
        SendAlert(GetMessage(MSG_REQD_OPER,array("OPER"=>$s_oper)));
        break;
    }
    return ($b_ok);
}
 
    //
    // Check the input for required values.  The list of required fields
    // is a comma-separated list of field names or conditionals
    //
function CheckRequired($s_reqd,$a_vars,&$s_missing,&$a_missing_list)
{
    $b_bad = false;
    $a_list = TrimArray(explode(",",$s_reqd));
    $s_missing = "";
    $a_missing_list = array();
    for ($ii = 0 ; $ii < count($a_list) ; $ii++)
    {
        $s_cond = $a_list[$ii];
        $i_len = strlen($s_cond);
        if ($i_len <= 0)
            continue;
        if (($i_span = strcspn($s_cond,REQUIREDOPS)) >= $i_len)
        {
                //
                // no advanced operator; just a field name
                //
            list($s_fld,$s_friendly) = GetFriendlyName($s_cond);
            if (TestFieldEmpty($s_fld,$a_vars,$s_mesg))
            {
                if ($s_mesg === "")
                    $s_mesg = "$s_friendly";
                else
                    $s_mesg = "$s_friendly ($s_mesg)";
                $b_bad = true;
                $s_missing .= "$s_mesg\n";
                $a_missing_list[] = "$s_mesg";
            }
        }
        elseif (!AdvancedRequired($s_cond,$i_span,$a_vars,
                                    $s_missing,$a_missing_list))
            $b_bad = true;
    }
    return (!$b_bad);
}
 
    //
    // Run a condition test
    //
function RunTest($s_test,$a_vars)
{
    global  $aAlertInfo;
 
    $s_op_chars = "&|^!=~#<>";      // these are the characters for the operators
    $i_len = strlen($s_test);
    $b_ok = true;
    if ($i_len <= 0)
            //
            // empty test - true
            //
        ;
    elseif ($s_test == "!")
            //
            // test asserts false
            //
        $b_ok = false;
    elseif (($i_span = strcspn($s_test,$s_op_chars)) >= $i_len)
            //
            // no operator - just check field presence
            //
        $b_ok = !TestFieldEmpty($s_test,$a_vars,$s_mesg);
    else
    {
            //
            // get first field name
            //
        $s_fld1 = trim(substr($s_test,0,$i_span));
            //
            // get the operator
            //
        $s_rem = substr($s_test,$i_span);
        $i_span = strspn($s_rem,$s_op_chars);
        $s_oper = substr($s_rem,0,$i_span);
        switch ($s_oper)
        {
        case '&':
        case '|':
        case '^':
        case '=':
        case '!=':
                //
                // get the second field name
                //
            $s_fld2 = trim(substr($s_rem,$i_span));
            $b_ok = FieldTest($s_oper,$s_fld1,$s_fld2,$a_vars,$s_error_mesg);
            break;
        case '~':
        case '!~':
                //
                // get the regular expression
                //
            $s_pat = trim(substr($s_rem,$i_span));
            if (!TestFieldEmpty($s_fld1,$a_vars,$s_mesg))
                $s_value = GetFieldValue($s_fld1,$a_vars);
            else
                $s_value = "";
            //echo "<p>Pattern: '".htmlspecialchars($s_pat)."': count=".preg_match($s_pat,$s_value)."<br /></p>";
                //
                // match the regular expression
                //
            if (preg_match($s_pat,$s_value) > 0)
                $b_ok = ($s_oper == '~');
            else
                $b_ok = ($s_oper == '!~');
            if (!$b_ok)
                $aAlertInfo[] = GetMessage(MSG_PAT_FAILED,array("OPER"=>$s_oper,
                                                            "PAT"=>$s_pat,
                                                            "VALUE"=>$s_value));
            break;
        case '#=':
        case '#!=':
        case '#<':
        case '#>':
        case '#<=':
        case '#>=':
                //
                // numeric tests
                //
            $s_num = trim(substr($s_rem,$i_span));
                //
                // if this is a file field, get the size of the file for
                // numeric tests
                //
            if (($s_value = GetFileSize($s_fld1)) === false)
                $s_value = $a_vars[$s_fld1];
            if (strpos($s_num,'.') === false)
            {
                    //
                    // treat as integer
                    //
                $m_num = (int) $s_num;
                $m_fld = (int) $s_value;
            }
            else
            {
                    //
                    // treat as floating point
                    //
                $m_num = (float) $s_num;
                $m_fld = (float) $s_value;
            }
            switch ($s_oper)
            {
            case '#=':
                $b_ok = ($m_fld == $m_num);
                break;
            case '#!=':
                $b_ok = ($m_fld != $m_num);
                break;
            case '#<':
                $b_ok = ($m_fld < $m_num);
                break;
            case '#>':
                $b_ok = ($m_fld > $m_num);
                break;
            case '#<=':
                $b_ok = ($m_fld <= $m_num);
                break;
            case '#>=':
                $b_ok = ($m_fld >= $m_num);
                break;
            }
            break;
        default:
            SendAlert(GetMessage(MSG_COND_OPER,array("OPER"=>$s_oper)));
            break;
        }
    }
    return ($b_ok);
}
 
    //
    // Check the input for condition tests.
    //
function CheckConditions($m_conditions,$a_vars,&$s_missing,&$a_missing_list,$m_id = false)
{
    if (is_array($m_conditions))
    {
            //
            // Sort the conditions by their numeric value.  This ensures
            // conditions are executed in the right order.
            //
        ksort($m_conditions,SORT_NUMERIC);
        foreach ($m_conditions as $m_key=>$s_cond)
            if (!CheckConditions($s_cond,$a_vars,$s_missing,$a_missing_list,$m_key))
                return (false);
        return (true);
    }
    $s_fld_name = "conditions".($m_id === false ? "" : ($m_id+1));
    if (!is_string($m_conditions))
    {
        SendAlert(GetMessage(MSG_INV_COND,array("FLD"=>$s_fld_name)));
        return (true);  // pass invalid conditions
    }
    if ($m_conditions == "")
        return (true);  // pass empty conditions
    $s_cond = $m_conditions;
        //
        // extract the separator characters
        //
    if (strlen($s_cond) < 2)
    {
        SendAlert(GetMessage(MSG_COND_CHARS,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond)));
        return (true);  // pass invalid conditions
    }
    $s_list_sep = $s_cond{0};
    $s_int_sep = $s_cond{1};
    $s_full_cond = $s_cond = substr($s_cond,2);
    $b_bad = false;
    $a_list = TrimArray(explode($s_list_sep,$s_cond));
    $s_missing = "";
    $a_missing_list = array();
    for ($ii = 0 ; $ii < count($a_list) ; $ii++)
    {
        $s_cond = $a_list[$ii];
        $i_len = strlen($s_cond);
        if ($i_len <= 0)
            continue;
            //
            // split the condition into its internal components
            //
        $a_components = TrimArray(explode($s_int_sep,$s_cond));
        if (count($a_components) < 5)
        {
            SendAlert(GetMessage(MSG_COND_INVALID,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_int_sep)));
                //
                // the smallest condition has 5 components
                //
            continue;
        }
            //
            // first component is ignored (it's blank)
            //
        $a_components = array_slice($a_components,1);
        switch ($a_components[0])
        {
        case "TEST":
            if (count($a_components) > 5)
            {
                SendAlert(GetMessage(MSG_COND_TEST_LONG,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_list_sep)));
                continue;
            }
            if (!RunTest($a_components[1],$a_vars))
            {
                $s_missing .= $a_components[2]."\n";
                $a_missing_list[] = $a_components[2];
                $b_bad = true;
            }
            break;
        case "IF":
            if (count($a_components) < 6)
            {
                SendAlert(GetMessage(MSG_COND_IF_SHORT,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_int_sep)));
                continue;
            }
            if (count($a_components) > 7)
            {
                SendAlert(GetMessage(MSG_COND_IF_LONG,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "SEP"=>$s_list_sep)));
                continue;
            }
            if (RunTest($a_components[1],$a_vars))
                $b_test = RunTest($a_components[2],$a_vars);
            else
                $b_test = RunTest($a_components[3],$a_vars);
            if (!$b_test)
            {
                $s_missing .= $a_components[4]."\n";
                $a_missing_list[] = $a_components[4];
                $b_bad = true;
            }
            break;
        default:
            SendAlert(GetMessage(MSG_COND_UNK,
                        array("FLD"=>$s_fld_name,"COND"=>$s_cond,
                              "CMD"=>$a_components[0])));
            break;
        }
    }
    return (!$b_bad);
}
 
    //
    // Return a formatted list of the given environment variables.
    //
function GetEnvVars($list,$s_line_feed)
{
    global  $VALID_ENV,$aServerVars;
 
    $output = "";
    for ($ii = 0 ; $ii < count($list) ; $ii++)
    {
        $name = $list[$ii];
        if ($name && array_search($name,$VALID_ENV,true) !== false)
        {
                //
                // if the environment variable is empty or non-existent, try
                // looking for the value in the server vars.
                //
            if (($s_value = getenv($name)) === "" || $s_value === false)
                if (isset($aServerVars[$name]))
                    $s_value = $aServerVars[$name];
                else
                    $s_value = "";
            $output .= $name."=".$s_value.$s_line_feed;
        }
    }
    return ($output);
}
    //
    // open a socket connection to a filter and post the data there
    //
function SocketFilter($filter,$a_filter_info,$m_data)
{
    static  $b_in_here = false;
    global  $php_errormsg;
 
        //
        // prevent recursive errors
        //
    if ($b_in_here)
        return ("<DATA DISCARDED>");
    $b_in_here = true;
 
    $a_errors = array();
    if (!isset($a_filter_info["site"]))
        $a_errors[] = GetMessage(MSG_MISSING,array("ITEM"=>"site"));
    else
        $s_site = $a_filter_info["site"];
 
    if (!isset($a_filter_info["port"]))
        $a_errors[] = GetMessage(MSG_MISSING,array("ITEM"=>"port"));
    else
        $i_port = (int) $a_filter_info["port"];
 
    if (!isset($a_filter_info["path"]))
        $a_errors[] = GetMessage(MSG_MISSING,array("ITEM"=>"path"));
    else
        $s_path = $a_filter_info["path"];
 
    if (!isset($a_filter_info["params"]))
        $a_params = array();
    elseif (!is_array($a_filter_info["params"]))
        $a_errors[] = GetMessage(MSG_NEED_ARRAY,array("ITEM"=>"params"));
    else
        $a_params = $a_filter_info["params"];
 
    if (!empty($a_errors))
    {
        Error("bad_filter",GetMessage(MSG_FILTER_WRONG,array(
                            "FILTER"=>$filter,
                            "ERRORS"=>implode(', ',$a_errors))),false,false);
        exit;
    }
 
        //
        // ready to build the socket - we need a longer time limit for the
        // script if we're doing this; we allow 30 seconds for the connection
        // (should be instantaneous, especially if it's the same domain)
        //
    set_time_limit(60);
@   $f_sock = fsockopen($s_site,$i_port,$i_errno,$s_errstr,30);
    if ($f_sock === false)
    {
        Error("filter_connect",GetMessage(MSG_FILTER_CONNECT,array(
                            "FILTER"=>$filter,
                            "SITE"=>$s_site,
                            "ERRNUM"=>$i_errno,
                            "ERRSTR"=>"$s_errstr (".CheckString($php_errormsg).")")),
                            false,false);
        exit;
    }
        //
        // build the data to send
        //
    $m_request_data = array();
    $i_count = 0;
    foreach ($a_params as $m_var)
    {
        $i_count++;
            //
            // if the parameter spec is an array, process it specially;
            // it must have "name" and "file" elements
            //
        if (is_array($m_var))
        {
            if (!isset($m_var["name"]))
            {
                Error("bad_filter",GetMessage(MSG_FILTER_PARAM,
                                    array("FILTER"=>$filter,
                                          "NUM"=>$i_count,
                                          "NAME"=>"name")),false,false);
                fclose($f_sock);
                exit;
            }
            $s_name = $m_var["name"];
            if (!isset($m_var["file"]))
            {
                Error("bad_filter",GetMessage(MSG_FILTER_PARAM,
                                    array("FILTER"=>$filter,
                                          "NUM"=>$i_count,
                                          "NAME"=>"file")),false,false);
                fclose($f_sock);
                exit;
            }
                //
                // open the file and read its contents
                //
@           $fp = fopen($m_var["file"],"r");
            if ($fp === false)
            {
                Error("filter_error",GetMessage(MSG_FILTER_OPEN_FILE,
                                    array("FILTER"=>$filter,
                                          "FILE"=>$m_var["file"],
                                          "ERROR"=>CheckString($php_errormsg))),false,false);
                fclose($f_sock);
                exit;
            }
            $s_data = "";
            $n_lines = 0;
            while (!feof($fp))
            {
                if (($s_line = fgets($fp,2048)) === false)
                    if (feof($fp))
                        break;
                    else
                    {
                        Error("filter_error",GetMessage(MSG_FILTER_FILE_ERROR,
                                    array("FILTER"=>$filter,
                                          "FILE"=>$m_var["file"],
                                          "ERROR"=>CheckString($php_errormsg),
                                          "NLINES"=>$n_lines)),false,false);
                        fclose($f_sock);
                        exit;
                    }
                $s_data .= $s_line;
                $n_lines++;
            }
 
            fclose($fp);
            $m_request_data[] = "$s_name=".urlencode($s_data);
        }
        else
            $m_request_data[] = (string) $m_var;
    }
        //
        // add the data
        //
    if (is_array($m_data))
        $m_request_data[] = "data=".urlencode(implode(BODY_LF,$m_data));
    else
        $m_request_data[] = "data=".urlencode($m_data);
    $s_request = implode("&",$m_request_data);
 
    if (($i_pos = strpos($s_site,"://")) !== false)
        $s_site_name = substr($s_site,$i_pos+3);
    else
        $s_site_name = $s_site;
 
    fputs($f_sock,"POST $s_path HTTP/1.0\r\n");
    fputs($f_sock,"Host: $s_site_name\r\n");
    fputs($f_sock,"Content-Type: application/x-www-form-urlencoded\r\n");
    fputs($f_sock,"Content-Length: ".strlen($s_request)."\r\n");
    fputs($f_sock,"\r\n");
    fputs($f_sock,"$s_request\r\n");
 
        //
        // now read the response
        //
    $m_hdr = "";
    $m_data = "";
    $b_in_hdr = true;
    $b_ok = false;
    while (!feof($f_sock))
    {
        if (($s_line = fgets($f_sock,2048)) === false)
            if (feof($f_sock))
                break;
            else
            {
                Error("filter_failed",GetMessage(MSG_FILTER_READ_ERROR,
                            array("FILTER"=>$filter,
                                  "ERROR"=>CheckString($php_errormsg))),false,false);
                fclose($f_sock);
                exit;
            }
            //
            // look for an "__OK__" line
            //
        if (trim($s_line) == "__OK__")
            $b_ok = true;
        elseif ($b_in_hdr)
        {
                //
                // blank line signals end of header
                //
            if (trim($s_line) == "")
                $b_in_hdr = false;
            else
                $m_hdr .= $s_line;
        }
        else
            $m_data .= $s_line;
    }
        //
        // if not OK, then report error
        //
    if (!$b_ok)
    {
        Error("filter_failed",GetMessage(MSG_FILTER_NOT_OK,
                    array("FILTER"=>$filter,
                          "DATA"=>$m_data)),false,false);
        fclose($f_sock);
        exit;
    }
    fclose($f_sock);
    $b_in_here = false;
    return ($m_data);
}
 
    //
    // run data through a supported filter
    //
function Filter($filter,$m_data)
{
    global  $FILTERS,$SOCKET_FILTERS;
    global  $php_errormsg;
    static  $b_in_here = false;
 
        //
        // prevent recursive errors
        //
    if ($b_in_here)
        return ("<DATA DISCARDED>");
    $b_in_here = true;
 
        //
        // Any errors sent in an alert are flagged to not run through the
        // filter - this also means the user's data won't be included in the
        // alert.
        // The reason for this is that the Filter is typically an encryption
        // program. If the filter fails, then sending the user's data in
        // clear text in an alert breaks the security of having encryption
        // in the first place!
        //
 
        //
        // find the filter
        //
    if (!isset($FILTERS[$filter]) || $FILTERS[$filter] == "")
    {
            //
            // check for SOCKET_FILTERS
            //
        if (!isset($SOCKET_FILTERS[$filter]) || $SOCKET_FILTERS[$filter] == "")
        {
            ErrorWithIgnore("bad_filter",GetMessage(MSG_FILTER_UNK,
                        array("FILTER"=>$filter)),false,false);
            exit;
        }
        $m_data = SocketFilter($filter,$SOCKET_FILTERS[$filter],$m_data);
    }
    elseif ($FILTERS[$filter] == "null")
            //
            // do nothing - just return the original data unchanged
            //
        ;
    elseif ($FILTERS[$filter] == "csv")
        $m_data = BuiltinFilterCSV();
    else
    {
        $cmd = $FILTERS[$filter];
            //
            // get the program name - assumed to be the first blank-separated word
            //
        $a_words = preg_split('/\s+/',$cmd);
        $prog = $a_words[0];
 
        $s_cwd = getcwd();
            //
            // change to the directory that contains the filter program
            //
        $dirname = dirname($prog);
        if ($dirname != "" && $dirname != "." && !chdir($dirname))
        {
            Error("chdir_filter",GetMessage(MSG_FILTER_CHDIR,
                        array("DIR"=>$dirname,"FILTER"=>$filter,
                              "ERROR"=>CheckString($php_errormsg))),false,false);
            exit;
        }
 
            //
            // the output of the filter goes to a temporary file; this works
            // OK on Windows too, even with the Unix shell syntax.
            //
        $temp_file = GetTempName("FMF");
        $cmd = "$cmd > $temp_file 2>&1";
            //
            // start the filter
            //
        $pipe = popen($cmd,"w");
        if ($pipe === false)
        {
            $s_sv_err = CheckString($php_errormsg);
            $err = join('',file($temp_file));
            unlink($temp_file);
            Error("filter_not_found",GetMessage(MSG_FILTER_NOTFOUND,
                        array("CMD"=>$cmd,"FILTER"=>$filter,
                              "ERROR"=>$s_sv_err)),false,false,$err);
            exit;
        }
            //
            // write the data to the filter
            //
        if (is_array($m_data))
            fwrite($pipe,implode(BODY_LF,$m_data));
        else
            fwrite($pipe,$m_data);
        if (($i_st = pclose($pipe)) != 0)
        {
            $s_sv_err = CheckString($php_errormsg);
            $err = join('',file($temp_file));
            unlink($temp_file);
            Error("filter_failed",GetMessage(MSG_FILTER_ERROR,
                        array("FILTER"=>$filter,
                              "ERROR"=>$s_sv_err,
                              "STATUS"=>$i_st)),false,false,$err);
            exit;
        }
            //
            // read in the filter's output and return as the data to be sent
            //
        $m_data = join('',file($temp_file));
        unlink($temp_file);
 
            //
            // return to previous directory
            //
        chdir($s_cwd);
    }
    $b_in_here = false;
    return ($m_data);
}
 
/*
 * Class:       CSVFormat
 * Description:     
 *  Manages formatting of CSV content.
 */
class   CSVFormat
{
    var         $_cSep;         /* field separator character */
    var         $_cQuote;       /* field quote character */
    var         $_cIntSep;      /* internal separator character (for lists) */
    var         $_sEscPolicy;   /* escape processing policy */
    var         $_sCleanFunc;   /* cleaning function for fields */
 
    /*
     * Method:      CSVFormat ctor
     * Parameters:  $c_sep          the field separator
     *              $c_quote        the quote character to use
     *              $c_int_sep      the internal field separator to use
     *              $s_esc_policy   escape processing policy to use
     *              $s_clean_func   a cleaning function
     * Returns:     n/a
     * Description: 
     *  Constructs the object.
     */
    function    CSVFormat($c_sep = ',',$c_quote = '"',$c_int_sep = ';',
                            $s_esc_policy = "backslash",$s_clean_func = NULL)
    {
        $this->SetSep($c_sep);
        $this->SetQuote($c_quote);
        $this->SetIntSep($c_int_sep);
        $this->SetEscPolicy($s_esc_policy);
        $this->SetCleanFunc($s_clean_func);
    }
 
    /*
     * Method:      SetEscPolicy
     * Parameters:  $s_esc_policy   a string specifying the escape processing
     *                              policy to use
     * Returns:     void
     * Description: 
     *  Set the escape processing policy.
     */
 
    function    SetEscPolicy($s_esc_policy)
    {
        switch ($s_esc_policy)
        {
        default:        /* should generate a warning */
        case "backslash":
                $this->_sEscPolicy = "b";
                break;
        case "double":
                $this->_sEscPolicy = "d";
                break;
        case "strip":
                $this->_sEscPolicy = "s";
                break;
        case "conv":
                $this->_sEscPolicy = "c";
                break;
        }
    }
 
    /*
     * Method:      SetSep
     * Parameters:  $c_sep      the separator character to use
     * Returns:     void
     * Description: 
     *  Set the separator character for between fields.
     */
    function    SetSep($c_sep)
    {
        $this->_cSep = $c_sep;
    }
 
    /*
     * Method:      SetQuote
     * Parameters:  $c_quote      the quote character to use
     * Returns:     void
     * Description: 
     *  Set the quote character for quoting fields.
     */
    function    SetQuote($c_quote)
    {
        $this->_cQuote = $c_quote;
    }
 
    /*
     * Method:      SetIntSep
     * Parameters:  $c_int_sep      the internal separator character to use
     * Returns:     void
     * Description: 
     *  Set the internal separator character for inside fields.
     */
    function    SetIntSep($c_int_sep)
    {
        $this->_cIntSep = $c_int_sep;
    }
 
    /*
     * Method:      SetCleanFunc
     * Parameters:  $s_clean_func   the name of a cleaning function (can be NULL)
     * Returns:     void
     * Description: 
     *  Set the cleaning function for fields.
     */
    function    SetCleanFunc($s_clean_func)
    {
        $this->_sCleanFunc = $s_clean_func;
    }
 
    /*
     * Method:      _Escape
     * Parameters:  $m_value    the field value; string or array of strings 
     * Returns:     mixed       the field value escaped according to the
     *                          escape processing policy
     * Description: 
     *  Escapes a field value according to the configured requirements.
     */
    function    _Escape($m_value)
    {
        switch ($this->_sEscPolicy)
        {
        default:            /* should generate an error */
        case "b":
                    /*
                     * 'backslash' escape policy: replace \ with \\ and
                     * " with \"
                     */
                $m_value = str_replace("\\","\\\\",$m_value);
                $m_value = str_replace($this->_cQuote,"\\".$this->_cQuote,
                                                                    $m_value);
                break;
        case "d":
                    /*
                     * 'double' escape policy: replace " with ""
                     * This is suitable for Microsoft apps such as Excel
                     * and Access. It also meets the specification of
                     * RFC4180, though this RFC only specified double
                     * quotes whereas we handle any quote character.
                     */
                $m_value = str_replace($this->_cQuote,
                                        $this->_cQuote.$this->_cQuote,$m_value);
                break;
        case "s":
                    /*
                     * 'strip' escape policy: strip quotes
                     */
                $m_value = str_replace($this->_cQuote,"",$m_value);
                break;
        case "c":
                    /*
                     * 'conv' escape policy: convert quotes to the other quotes
                     */
                switch ($this->_cQuote)
                {
                case '"':
                        /*
                         * convert double quotes in the data to single quotes
                         */
                    $m_value = str_replace("\"","'",$m_value);
                    break;
                case '\'':
                        /*
                         * convert single quotes in the data to double quotes
                         */
                    $m_value = str_replace("'","\"",$m_value);
                    break;
                default:
                        /*
                         * otherwise, leave the data unchanged
                         */
                    break;
                }
                break;
        }
        return ($m_value);
    }
 
    function    _Format($m_value)
    {
        $m_value = $this->_Escape($m_value);
            /*
             * we handle strings and arrays of strings
             */
        if (is_array($m_value))
                /*
                 * separate the values with the internal field separator
                 */
            $m_value = implode($this->_cIntSep,$m_value);
        return ($this->_cQuote.$m_value.$this->_cQuote);
    }
 
    /*
     * Method:      MakeCSVRecord
     * Parameters:  $a_column_list  a list of column names (field names) to
     *                              include
     *              $a_vars         raw data array indexed by column name
     *                              (field name).
     *                              A data value can be a string or an array
     *                              of strings.
     * Returns:     string          the comma-separated value    
     * Description: 
     *  Creates a single CSV record for a list of columns.
     */
    function    MakeCSVRecord($a_column_list,$a_vars)
    {
        $s_rec = "";
        $n_columns = count($a_column_list);
        for ($ii = 0 ; $ii < $n_columns ; $ii++)
        {
            $s_col_name = $a_column_list[$ii];
                /*
                 * if a column is specified it must be included, even if there
                 * is no data for it.
                 */
            if (isset($a_vars[$s_col_name]))
            {
                $m_value = $a_vars[$s_col_name];
                if (isset($this->_sCleanFunc))
                {
                    $s_func = $this->_sCleanFunc;
                    $m_value = $s_func($m_value);
                }
            }
            else
                $m_value = "";
 
            $m_value = $this->_Format($m_value);
            if ($ii > 0)
                    /*
                     * prepend the separator from the second field onwards
                     */
                $s_rec .= $this->_cSep;
            $s_rec .= $m_value;
        }
        return ($s_rec);
    }
 
    /*
     * Method:      MakeHeading
     * Parameters:  $a_column_list  a list of column names (field names) to
     *                              include
     * Returns:     string          the comma-separated heading record    
     * Description: 
     *  Creates a heading record for the CSV data.
     */
    function    MakeHeading($a_column_list)
    {
        $s_rec = "";
        $n_columns = count($a_column_list);
        for ($ii = 0 ; $ii < $n_columns ; $ii++)
        {
            $s_col_name = $a_column_list[$ii];
            $m_value = $this->_Format($s_col_name);
            if ($ii > 0)
                    /*
                     * prepend the separator from the second field onwards
                     */
                $s_rec .= $this->_cSep;
            $s_rec .= $m_value;
        }
        return ($s_rec);
    }
};
 
    /*
     * Built-in filter.  Generates CSV (comma separated values) content from
     * the submitted fields. The special field "filter_fields" determines
     * which fields to include in the CSV content.
     * The following options are support in "filter_options":
     *      CSVHeading  if set, includes a heading line first with the field names
     *      CSVSep      specifies a separator character instead of comma
     *      CSVIntSep   specifies an internal separator character for lists
     *      CSVQuote    specifies the character to use to quote each column; default
     *                  is double quotes
     *      CSVEscPolicy controls the way quotes are escaped in the data.  Supported
     *                  values are: backslash (the default),double,strip
     *      CSVRaw      if set, then the fields are recorded as raw values and
     *                  are *not* cleaned according to FormMail's normal field
     *                  cleaning process.
     * If the "filter_fields" field does not exist, then the "csvcolumns" field is
     * used instead.  If neither exist, then all fields are included along with
     * a Heading line.
     */
function BuiltinFilterCSV()
{
    global  $aAllRawValues,$aRawDataValues,$SPECIAL_VALUES,$CSVLINE;
 
    $b_heading = false;
    $a_column_list = array();
    $s_cols = $SPECIAL_VALUES["filter_fields"];
    if (!isset($s_cols) || empty($s_cols) || !is_string($s_cols))
    {
        $s_cols = $SPECIAL_VALUES["csvcolumns"];
        if (!isset($s_cols) || empty($s_cols) || !is_string($s_cols))
        {
                /*
                 * neither filter_fields nor csvcolumns defined - get all
                 * columns
                 */
            $s_cols = "";
                /*
                 * special case - include these two special fields
                 */
            $a_column_list = array("email","realname");
                /*
                 * now include all the data fields
                 */
            $a_column_list = array_merge($a_column_list,
                                            array_keys($aRawDataValues));
            $b_heading = true;
        }
    }
    if (empty($a_column_list))
        $a_column_list = TrimArray(explode(",",$s_cols));
 
    $csv_format = new CSVFormat();
 
        /*
         * get the various options and set them
         */
    $m_temp = GetFilterOption("CSVQuote");
    if (isset($m_temp))
        $csv_format->SetQuote($m_temp);
    $m_temp = GetFilterOption("CSVSep");
    if (isset($m_temp))
        $csv_format->SetSep($m_temp);
    $m_temp = GetFilterOption("CSVIntSep");
    if (isset($m_temp))
        $csv_format->SetIntSep($m_temp);
    $m_temp = GetFilterOption("CSVEscPolicy");
    if (isset($m_temp))
        $csv_format->SetEscPolicy($m_temp);
    $m_temp = GetFilterOption("CSVHeading");
    if (isset($m_temp))
        $b_heading = true;
 
        /*
         * clean fields unless CSVRaw is specified
         */
    $m_temp = GetFilterOption("CSVRaw");
    if (!isset($m_temp))
        $csv_format->SetCleanFunc(create_function('$m_value',
                                    'return CleanValue($m_value,false);'));
 
    $s_csv = $csv_format->MakeCSVRecord($a_column_list,$aAllRawValues);
 
    if ($b_heading)
    {
        $s_head = $csv_format->MakeHeading($a_column_list);
            /*
             * return the heading and the record with $CSVLINE as record separator
             */
        return ($s_head.$CSVLINE.$s_csv.$CSVLINE);
    }
    else
            /*
             * return this record with $CSVLINE appended
             */
        return ($s_csv.$CSVLINE);
}
 
$aSubstituteErrors = array();
$aSubstituteValues = NULL;
$sSubstituteMissing = NULL;
 
    //
    // Run htmlspecialchars on every value in an array.
    //
function ArrayHTMLSpecialChars($a_list)
{
    $a_new = array();
    foreach ($a_list as $m_key=>$m_value)
        if (is_array($m_value))
            $a_new[$m_key] = ArrayHTMLSpecialChars($m_value);
        else
            $a_new[$m_key] = htmlspecialchars($m_value);
    return ($a_new);
}
 
    //
    // Worker function for SubstituteValue and SubstituteValueForPage.
    // Returns the value of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, an error is reported or the given
    // replacement string is used.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValueWorker($a_matches,$s_repl,$b_html = true)
{
    global  $aSubstituteErrors,$aSubstituteValues,$SPECIAL_VALUES;
 
    $b_insert_br = true;       // option to put "<br />" tags before newlines in HTML templates
 
    $s_name = $a_matches[0];
    assert(strlen($s_name) > 1 && $s_name{0} == '$');
    $s_name = substr($s_name,1);
    if (($i_len = strlen($s_name)) > 0 && $s_name{0} == '{')
    {
        assert($s_name{$i_len-1} == '}');
        $s_name = substr($s_name,1,-1);
            //
            // grab any processing options
            //
        $a_args = explode(":",$s_name);
        $s_name = $a_args[0];
        if (($n_args = count($a_args)) > 1)
        {
            for ($ii = 1 ; $ii < $n_args ; $ii++)
            {
                switch ($a_args[$ii])
                {
                case "nobr":
                    $b_insert_br = false;
                    break;
                }
            }
        }
    }
    $s_value = "";
    if (IsFieldSet($s_name,$aSubstituteValues) &&
        !TestFieldEmpty($s_name,$aSubstituteValues,$s_mesg))
    {
        if (is_array($aSubstituteValues[$s_name]))
                //
                // note that the separator can include HTML special chars
                //
            $s_value = implode($SPECIAL_VALUES['template_list_sep'],
                            $b_html ?
                            ArrayHTMLSpecialChars($aSubstituteValues[$s_name]) :
                            $aSubstituteValues[$s_name]);
        else
        {
            $s_value = GetFieldValue($s_name,$aSubstituteValues);
            if ($b_html)
                $s_value = htmlspecialchars($s_value);
        }
        if ($b_html && $b_insert_br)
                //
                // Insert HTML line breaks before newlines.
                //
            $s_value = nl2br($s_value);
    }
    elseif (isset($SPECIAL_VALUES[$s_name]))
        $s_value = $b_html ?
                        htmlspecialchars((string) $SPECIAL_VALUES[$s_name]) :
                        (string) $SPECIAL_VALUES[$s_name];
    elseif (isset($s_repl))
            //
            // If a replacement value has been specified use it, and
            // don't call htmlspecialchars.  This allows the use
            // of HTML tags in a replacement string.
            //
        $s_value = $s_repl;
    else
        $aSubstituteErrors[] = GetMessage(MSG_FLD_NOTFOUND,array("FIELD"=>$s_name));
    return ($s_value);
}
 
    //
    // Callback function for preg_replace_callback.  Returns the value
    // of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, an error is reported or an special
    // replacement string is used.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValue($a_matches)
{
    global  $sSubstituteMissing;
 
    return (SubstituteValueWorker($a_matches,$sSubstituteMissing));
}
 
    //
    // Callback function for preg_replace_callback.  Returns the value
    // of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, an error is reported or an special
    // replacement string is used.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValuePlain($a_matches)
{
    global  $sSubstituteMissing;
 
    return (SubstituteValueWorker($a_matches,$sSubstituteMissing,false));
}
 
    //
    // Callback function for preg_replace_callback.  Returns the value
    // of the matched variable name.
    // Variables are searched for in the global $aSubstituteValues.
    // If no such variable exists, the empty string is substituted.
    // Errors are stored in the global $aSubstituteErrors.
    //
function SubstituteValueForPage($a_matches)
{
    return (SubstituteValueWorker($a_matches,""));
}
 
    //
    // Process the given HTML template and fill the fields.
    //
function DoProcessTemplate($s_dir,$s_url,$s_template,&$a_lines,
                            $a_values,$s_missing,$s_subs_func)
{
    global  $aSubstituteErrors,$aSubstituteValues,$sSubstituteMissing;
 
    if (($a_template_lines = LoadTemplate($s_template,$s_dir,
                                            $s_url,true)) === false)
        return (false);
 
    $b_ok = true;
        //
        // initialize the errors list
        //
    $aSubstituteErrors = array();
        //
        // initialize the values
        //
    $aSubstituteValues = $a_values;
    $sSubstituteMissing = $s_missing;
 
    foreach ($a_template_lines as $s_line)
    {
            //
            // search for words in these forms:
            //      $word
            //      ${word:options}
            // where word begins with an alphabetic character and
            // consists of alphanumeric and underscore
            //
        $a_lines[] = preg_replace_callback('/\$[a-z][a-z0-9_]*|\$\{[a-z][a-z0-9_]*(:[^\}]*)*\}/i',
                                            $s_subs_func,$s_line);
    }
 
//  SendAlert("Error count=".count($aSubstituteErrors));
    if (count($aSubstituteErrors) != 0)
    {
        SendAlert(GetMessage(MSG_TEMPLATE_ERRORS,array("NAME"=>$s_template)).
                            implode("\n",$aSubstituteErrors));
        $b_ok = false;
    }
    global  $FMCTemplProc;
 
        //
        // note that it's possible for an old version of FormMail Computation
        // module to get loaded which doesn't provide FMCTemplProc
        //
    if ($b_ok && ADVANCED_TEMPLATES && isset($FMCTemplProc))
    {
        $a_mesgs = array();
        /*foreach ($a_lines as $i_lno=>$s_line)
            if (strpos($s_line,"\n") !== false)
                SendAlert("Line $i_lno has a newline");*/
        set_time_limit(60);
        if (($m_result = $FMCTemplProc->Process(implode("\n",$a_lines),$a_mesgs)) === false)
        {
            $s_msgs = "\n";
            foreach ($a_mesgs as $a_msg)
            {
                $s_msgs .= "Line ".$a_msg["LINE"];
                $s_msgs .= ", position ".$a_msg["CHAR"].": ";
                $s_msgs .= $a_msg["MSG"]."\n";
            }
            Error("fmadvtemplates",GetMessage(MSG_TEMPL_PROC,
                        array("ERRORS"=>$s_msgs)),false,false);
            $b_ok = false;
        }
        else
        {
            /*foreach ($m_result as $i_lno=>$s_line)
                if (($nn = substr_count($s_line,"\n")) > 1)
                    SendAlert("Result line $i_lno has $nn newlines");*/
                //
                // strip the new lines
                //
            $a_lines = explode("\n",implode("",$m_result));
        }
        $a_alerts = $FMCTemplProc->GetAlerts();
        if (count($a_alerts) > 0)
            SendAlert(GetMessage(MSG_TEMPL_ALERT,
                        array("ALERTS"=>implode("\n",$a_alerts))));
        $a_debug = $FMCTemplProc->GetDebug();
        if (count($a_debug) > 0)
            SendAlert(GetMessage(MSG_TEMPL_DEBUG,
                        array("DEBUG"=>implode("\n",$a_debug))));
    }
 
    return ($b_ok);
}
 
    //
    // Process the given HTML template and fill the fields.
    //
function ProcessTemplate($s_template,&$a_lines,$a_values,$s_missing = NULL,
                            $s_subs_func = 'SubstituteValue')
{
    global  $TEMPLATEURL,$TEMPLATEDIR;
 
    if (empty($TEMPLATEDIR) && empty($TEMPLATEURL))
    {
        SendAlert(GetMessage(MSG_TEMPLATES));
        return (false);
    }
    return (DoProcessTemplate($TEMPLATEDIR,$TEMPLATEURL,$s_template,$a_lines,
                                $a_values,$s_missing,$s_subs_func));
}
 
    //
    // Output the given HTML template after filling in the fields.
    //
function OutputTemplate($s_template,$a_values)
{
    $a_lines = array();
    if (!ProcessTemplate($s_template,$a_lines,$a_values,"",'SubstituteValueForPage'))
        Error("template_failed",GetMessage(MSG_TEMPLATE_FAILED,
                                    array("NAME"=>$s_template)),false,false);
    else
    {
        for ($ii = 0 ; $ii < count($a_lines) ; $ii++)
            echo $a_lines[$ii]."\n";
    }
}
 
    //
    // This function handles input type "text" and "password"
    //
function FixInputText($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <input type="text" name="thename"...
        // and change it to:
        //  <input type="text" name="thename" value="thevalue" ...
        //
        // Note that the value attribute must appear *after* the
        // type and name attributes.
        //
 
        //
        // first strip any current value attribute for the field
        //
 
        //
        // (?:) is a grouping subpattern that does no capturing
        //
 
        // handle type attribute first
    $s_pat  = '/(<\s*input[^>]*type="(?:text|password)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*)(value="[^"]*")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:text|password)"[^>]*)(value="[^"]*")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        //
        // now add in the new value
        //
    $s_repl  = '$1 value="'.htmlspecialchars($s_value).'" $2>';
 
        // handle type attribute first
    $s_pat  = '/(<\s*input[^>]*type="(?:text|password)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:text|password)"[^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles textareas.
    //
function FixTextArea($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <textarea name="thename"...>value</textarea>
        // and change it to:
        //  <textarea name="thename"...>new value</textarea>
        //
 
    $s_pat  = '/(<\s*textarea[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*)>.*?<\s*\/\s*textarea\s*>';
    $s_pat .= '/ims';
        //
        // we exclude the closing '>' from the match above so that
        // we can put it below.  We need to do this so that the replacement
        // string is not faulty if the value begins with a digit:
        //      $19 Some Street
        //
    $s_repl = '$1>'.htmlspecialchars($s_value).'</textarea>';
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles radio buttons and non-array checkboxes.
    //
function FixButton($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <input type="radio" name="thename" value="thevalue" ...
        // and change it to:
        //  <input type="radio" name="thename" value="thevalue" checked="checked"
        //
        // Note that the value attribute must appear *after* the
        // type and name attributes.
        //
 
        //
        // first strip any current checked attributes
        //
 
        //
        // (?:) is a grouping subpattern that does no capturing
        //
 
        // handle type attribute first
        // match: input tag with type 'radio' or 'checkbox' with attribute
        // 'checked' or 'checked="checked"'
        //              <A NAME="PatternInfo">
        //      [^>]*?[^"\w] matches up to a word boundary starting with
        //      'checked' but not '"checked'
        //      (="checked"|(?=[^"\w]))? this matches:
        //              nothing
        //              ="checked"
        //              any character except a word character or " (without
        //              consuming it)
        //
    $s_pat  = '/(<\s*input[^>]*type="(?:radio|checkbox)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:radio|checkbox)"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle type attribute first
    $s_pat  = '/(<\s*input[^>]*type="(?:radio|checkbox)"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*value="';
    $s_pat .= preg_quote($s_value,"/");
    $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$2 checked="checked" $3>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '"[^>]*type="(?:radio|checkbox)"[^>]*value="';
    $s_pat .= preg_quote($s_value,"/");
    $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$2 checked="checked" $3>',$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles checkboxes as an array of values.
    //
function FixCheckboxes($s_name,$a_values,$s_buf)
{
    //global $aDebug;
 
        //
        // we search for:
        //  <input type="checkbox" name="thename" value="thevalue" ...
        // and change it to:
        //  <input type="checkbox" name="thename" value="thevalue" checked
        //
        // Note that the value attribute must appear *after* the
        // type and name attributes.
        //
 
        //
        // first strip any current checked attributes
        //
    //$aDebug[] = "FixCheckboxes: Name='$s_name'";
 
        // handle type attribute first
        // see <A HREF="fmbadhandler.php#PatternInfo">
    $s_pat  = '/(<\s*input[^>]*type="checkbox"[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '\[]"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        // handle name attribute first
    $s_pat  = '/(<\s*input[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '\[]"[^>]*type="checkbox"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
    foreach ($a_values as $s_value)
    {
            // handle type attribute first
        $s_pat  = '/(<\s*input[^>]*type="checkbox"[^>]*name="';
        $s_pat .= preg_quote($s_name,"/");
        $s_pat .= '\[\]"[^>]*value="';
        $s_pat .= preg_quote($s_value,"/");
        $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
        $s_pat .= '/ims';
        $s_buf = preg_replace($s_pat,'$1$2 checked="checked"$3>',$s_buf);
        //$aDebug[] = "Name='$s_name', pat='$s_pat'";
 
            // handle name attribute first
        $s_pat  = '/(<\s*input[^>]*name="';
        $s_pat .= preg_quote($s_name,"/");
        $s_pat .= '\[\]"[^>]*type="checkbox"[^>]*value="';
        $s_pat .= preg_quote($s_value,"/");
        $s_pat .= '")([^>]*?)(\s*\/\s*)?>';
        $s_pat .= '/ims';
        $s_buf = preg_replace($s_pat,'$1$2 checked="checked">',$s_buf);
    }
    return ($s_buf);
}
 
    //
    // This function handles selects.
    //
function FixSelect($s_name,$s_value,$s_buf)
{
        //
        // we search for:
        //  <select name="thename"...>
        //  <option value="thevalue">...</option>
        //  </select>
        //
 
    $s_pat  = '/(<\s*select[^>]*name="';
    $s_pat .= preg_quote($s_name,"/");
    $s_pat .= '".*?<\s*option[^>]*value="';
    $s_pat .= preg_quote($s_value,"/");
    $s_pat .= '"[^>]*)>';
    $s_pat .= '/ims';
    $s_repl = '$1 selected="selected">';
//  echo "<p>pat: ".htmlspecialchars($s_pat);
    $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
 
    return ($s_buf);
}
 
    //
    // This function handles multiple selects.
    //
function FixMultiSelect($s_name,$a_values,$s_buf)
{
        //
        // we search for:
        //  <select name="thename"...>
        //  <option value="thevalue">...</option>
        //  </select>
        //
 
    foreach ($a_values as $s_value)
    {
        $s_pat  = '/(<\s*select[^>]*name="';
        $s_pat .= preg_quote($s_name,"/");
        $s_pat .= '\[\]".*?<\s*option[^>]*value="';
        $s_pat .= preg_quote($s_value,"/");
        $s_pat .= '"[^>]*)>';
        $s_pat .= '/ims';
        $s_repl = '$1 selected="selected">';
    //  echo "<p>pat: ".htmlspecialchars($s_pat);
        $s_buf = preg_replace($s_pat,$s_repl,$s_buf);
    }
    return ($s_buf);
}
 
    //
    // This function unchecks all checkboxes and select options.
    //
function UnCheckStuff($s_buf)
{
    global  $php_errormsg;
 
        //
        // we search for:
        //  <input type="checkbox" ... checked
        // and remove "checked" (checked="checked" is OK too)
        //
        // Note that the check attribute must appear *after* the
        // type attribute.
        // see <A HREF="fmbadhandler.php#PatternInfo">
        //
 
    $s_pat  = '/(<\s*input[^>]*type="checkbox"[^>]*?[^"\w])checked(="checked"|(?=[^"\w]))?([^>]*?)(\s*\/\s*)?>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3$4>',$s_buf);
 
        //
        // we search for:
        //  <option... selected
        // and remove "selected" (selected="selected" is OK too)
        // see <A HREF="fmbadhandler.php#PatternInfo">
        //
 
    $s_pat  = '/(<\s*option[^>]*?[^"\w])selected(="selected"|(?=[^"\w]))?([^>]*)>';
    $s_pat .= '/ims';
    $s_buf = preg_replace($s_pat,'$1$3>',$s_buf);
 
    return ($s_buf);
}
 
    //
    // Add the user agent to the url as a parameter called USER_AGENT.
    // This allows dynamic web sites to know what the user's browser is.
    //
function AddUserAgent($s_url)
{
    global  $aServerVars;
 
        //
        // check for ? in the name
        //
    $b_quest = (strpos($s_url,'?') !== false);
    unset($s_agent);
    if (isset($aServerVars['HTTP_USER_AGENT']))
        $s_agent = $aServerVars['HTTP_USER_AGENT'];
    if (isset($s_agent))
        $s_url .= ($b_quest ? '&' : '?')."USER_AGENT=".urlencode($s_agent);
    return ($s_url);
}
 
    //
    // Sets previous values in a form.
    //
function SetPreviousValues($s_form_buf,$a_values)
{
        //
        // Uncheck any checkboxes and select options
        //
    $s_form_buf = UnCheckStuff($s_form_buf);
    foreach ($a_values as $s_name=>$m_value)
    {
        if (is_array($m_value))
        {
                //
                // note that if no values are selected for a field,
                // then we will never get here for that field
                //
            $s_form_buf = FixCheckboxes($s_name,$m_value,$s_form_buf);
            $s_form_buf = FixMultiSelect($s_name,$m_value,$s_form_buf);
        }
        else
        {
                //
                // Fix the field if it's an input type "text" or "password".
                //
            $s_form_buf = FixInputText($s_name,$m_value,$s_form_buf);
                //
                // Fix the field if it's radio button.
                //
            $s_form_buf = FixButton($s_name,$m_value,$s_form_buf);
                //
                // Fix the field if it's a "textarea".
                //
            $s_form_buf = FixTextArea($s_name,$m_value,$s_form_buf);
                //
                // Fix the field if it's a "select".
                //
            $s_form_buf = FixSelect($s_name,$m_value,$s_form_buf);
        }
    }
    return ($s_form_buf);
}
 
    //
    // Open a URL, do value substitutions, and send to browser.
    //
function ProcessReturnToForm($s_url,$a_values)
{
    global  $aSubstituteErrors,$aSubstituteValues,$sSubstituteMissing;
    global  $php_errormsg;
 
        //
        // read the original form, and modify it to provide values
        // for the fields
        //
    if (!CheckValidURL($s_url))
        Error("invalid_url",GetMessage(MSG_RETURN_URL_INVALID,
                                    array("URL"=>$s_url)),false,false);
 
    $s_form_url = AddUserAgent($s_url);
    $s_error = "";
    $s_form_buf = GetURL($s_form_url,$s_error);
    if ($s_form_buf === false)
        Error("invalid_url",GetMessage(MSG_OPEN_URL,
                                array("URL"=>$s_form_url,
                                      "ERROR"=>$s_error.": ".(isset($php_errormsg) ?
                                            $php_errormsg : ""))),false,false);
 
    /*****
        This is not correct here, because this function is only called
        for non-template URLs.
        //
        // First, we do any "$var" substitutions
        //
 
        //
        // initialize the errors list
        //
    $aSubstituteErrors = array();
        //
        // initialize the values
        //
    $aSubstituteValues = $a_values;
    $sSubstituteMissing = $s_missing;
 
        //
        // search for words in this form:
        //      $word
        // where word begins with an alphabetic character and
        // consists of alphanumeric and underscore
        //
//    $s_form_buf = preg_replace_callback('/\$([a-z][a-z0-9_]*)/i',
//                                      'SubstituteValueForPage',$s_form_buf);
 
//  SendAlert("Error count=".count($aSubstituteErrors));
    if (count($aSubstituteErrors) != 0)
        Error("template_failed",
                    GetMessage(MSG_TEMPLATE_ERRORS,array("NAME"=>$s_template)).
                            implode("\n",$aSubstituteErrors),false,false);
    ******/
 
        //
        // Next, we replace or set actual field values.
        //
    echo SetPreviousValues($s_form_buf,$a_values);
}
 
    //
    // To return the URL for returning to a particular multi-page form URL.
    //
function GetReturnLink($s_this_script,$i_form_index)
{
    if (!CheckValidURL($s_this_script))
        Error("not_valid_url",GetMessage(MSG_RETURN_URL_INVALID,
                                array("URL"=>$s_this_script)),false,false);
 
    $a_params = array();
    $a_params[] = "return=$i_form_index";
    if (isset($aServerVars["QUERY_STRING"]))
        $a_params[] = $aServerVars["QUERY_STRING"];
    $a_params[] = session_name()."=".session_id();
    return (AddURLParams($s_this_script,$a_params));
}
 
    //
    // Process a multi-page form template.
    //
function ProcessMultiFormTemplate($s_template,$a_values,&$a_lines)
{
    global  $MULTIFORMURL,$MULTIFORMDIR,$SPECIAL_VALUES,$aSessionVars;
 
    if (empty($MULTIFORMDIR) && empty($MULTIFORMURL))
    {
        SendAlert(GetMessage(MSG_MULTIFORM));
        return (false);
    }
    $i_index = $aSessionVars["FormIndex"];
    $a_values["this_form_url"] = $aSessionVars["FormList"][$i_index]["URL"];
    //$a_values["prev_form"] = GetReturnLink($SPECIAL_VALUES["this_form"]);
    return (DoProcessTemplate($MULTIFORMDIR,$MULTIFORMURL,$s_template,$a_lines,
                            $a_values,"",'SubstituteValueForPage'));
}
 
    //
    // Output the multi-form template after filling in the fields.
    //
function OutputMultiFormTemplate($s_template,$a_values)
{
    $a_lines = array();
    if (!ProcessMultiFormTemplate($s_template,$a_values,$a_lines))
        Error("multi_form_failed",GetMessage(MSG_MULTIFORM_FAILED,
                                    array("NAME"=>$s_template)),false,false);
    else
    {
        $n_lines = count($a_lines);
        $s_buf = "";
        for ($ii = 0 ; $ii < $n_lines ; $ii++)
        {
            $s_buf .= $a_lines[$ii]."\n";
            unset($a_lines[$ii]);       // free memory (hopefully)
        }
        unset($a_lines);       // free memory (hopefully)
 
        global  $aSessionVars;
 
        if (isset($aSessionVars["FormKeep"]))
                //
                // put in any values that are being forward-remembered
                //
            echo SetPreviousValues($s_buf,$aSessionVars["FormKeep"]);
        else
            echo $s_buf;
    }
}
 
    //
    // Insert a preamble into a MIME message.
    //
function MimePreamble(&$a_lines,$a_mesg = array())
{
    $a_preamble = explode("\n",GetMessage(MSG_MIME_PREAMBLE));
    foreach ($a_preamble as $s_line)
        $a_lines[] = $s_line.HEAD_CRLF;
 
    $a_lines[] = HEAD_CRLF;     // blank line
    $b_need_blank = false;
    foreach ($a_mesg as $s_line)
    {
        $a_lines[] = $s_line.HEAD_CRLF;
        if (!empty($s_line))
            $b_need_blank = true;
    }
    if ($b_need_blank)
        $a_lines[] = HEAD_CRLF;     // blank line
}
 
    //
    // Create the HTML mail
    //
function HTMLMail(&$a_lines,&$a_headers,$s_body,$s_template,$s_missing,$s_filter,
                            $s_boundary,$a_raw_fields,$b_no_plain)
{
    $s_charset = GetMailOption("CharSet");
    if (!isset($s_charset))
        $s_charset = "ISO-8859-1";
    if ($b_no_plain)
    {
        $b_multi = false;
            //
            // don't provide a plain text version - just the HTML
            //
        $a_headers['Content-Type'] = "text/html; charset=$s_charset";
    }
    else
    {
        $b_multi = true;
        $a_headers['Content-Type'] = "multipart/alternative; boundary=\"$s_boundary\"";
 
        $a_pre_lines = explode("\n",GetMessage(MSG_MIME_HTML,
                                                array("NAME"=>$s_template)));
 
        MimePreamble($a_lines,$a_pre_lines);
 
            //
            // first part - the text version only
            //
        $a_lines[] = "--$s_boundary".HEAD_CRLF;
        $a_lines[] = "Content-Type: text/plain; charset=$s_charset".HEAD_CRLF;
        $a_lines[] = HEAD_CRLF;     // blank line
            //
            // treat the body like one line, even though it isn't
            //
        $a_lines[] = $s_body;
        $a_lines[] = HEAD_CRLF;     // blank line
            //
            // second part - the HTML version
            //
        $a_lines[] = "--$s_boundary".HEAD_CRLF;
        $a_lines[] = "Content-Type: text/html; charset=$s_charset".HEAD_CRLF;
        $a_lines[] = HEAD_CRLF;     // blank line
    }
 
    $a_html_lines = array();
    if (!ProcessTemplate($s_template,$a_html_lines,$a_raw_fields,$s_missing))
        return (false);
 
    if (!empty($s_filter))
            //
            // treat the data like one line, even though it isn't
            //
        $a_lines[] = Filter($s_filter,$a_html_lines);
    else
        foreach ($a_html_lines as $s_line)
            $a_lines[] = $s_line;
 
    if ($b_multi)
    {
            //
            // end
            //
        $a_lines[] = "--$s_boundary--".HEAD_CRLF;
        $a_lines[] = HEAD_CRLF;     // blank line
    }
    return (true);
}
 
    //
    // Add the contents of a file in base64 encoding.
    //
function AddFile(&$a_lines,$s_file_name,$i_file_size,$b_remove = true)
{
    global  $php_errormsg;
 
@   $fp = fopen($s_file_name,"rb");
    if ($fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$s_file_name,
                                            "TYPE"=>"attachment",
                                            "ERROR"=>CheckString($php_errormsg))));
        return (false);
    }
        //
        // PHP under IIS has problems with the filesize function when
        // the file is on another drive.  So, we replaced a call
        // to filesize with the $i_file_size parameter (this occurred
        // in version 3.01).
        //
    $s_contents = fread($fp,$i_file_size);
        //
        // treat as a single line, even though it isn't
        //
    $a_lines[] = chunk_split(base64_encode($s_contents));
    fclose($fp);
    if ($b_remove)
        @unlink($s_file_name);
    return (true);
}
 
    //
    // Add the contents of a string in base64 encoding.
    //
function AddData(&$a_lines,$s_data)
{
        //
        // treat as a single line, even though it isn't
        //
    $a_lines[] = chunk_split(base64_encode($s_data));
    return (true);
}
    //
    // Check if a file is a valid uploaded file.
    //
function IsUploadedFile($a_file_spec)
{
        //
        // $a_file_spec['moved'] is our own internal flag to say we've
        // saved the file
        //
    if (isset($a_file_spec['moved']) && $a_file_spec['moved'])
        return (true);
    return (is_uploaded_file($a_file_spec['tmp_name']));
}
 
    //
    // Save an uploaded file to the repository directory.
    //
function SaveFileInRepository(&$a_file_spec)
{
    global  $php_errormsg,$FILE_REPOSITORY;
 
        //
        // if a replacement name has been specified, use that, otherwise
        // use the original name
        //
    if (isset($a_file_spec['new_name']))
        $s_file_name = basename($a_file_spec['new_name']);
    else
        $s_file_name = basename($a_file_spec['name']);
    $s_dest = $FILE_REPOSITORY."/".$s_file_name;
 
    $b_ok = true;
    $s_error = "";
 
    if (isset($a_file_spec['saved_as']) && !empty($a_file_spec['saved_as']))
        $s_srce = $a_file_spec['saved_as'];
    else
        $s_srce = $a_file_spec['tmp_name'];
 
    if (!FILE_OVERWRITE)
    {
        clearstatcache();
        if (@file_exists($s_dest))
        {
            $b_ok = false;
            $s_error = GetMessage(MSG_SAVE_FILE_EXISTS,array("FILE"=>$s_dest));
        }
    }
    if (MAX_FILE_UPLOAD_SIZE != 0 &&
        $a_file_spec['size'] > MAX_FILE_UPLOAD_SIZE*1024)
            //
            // this exits
            //
        UserError("upload_size",GetMessage(MSG_FILE_UPLOAD_SIZE,
                                  array("NAME"=>$a_file_spec['name'],
                                        "SIZE"=>$a_file_spec['size'],
                                        "MAX"=>MAX_FILE_UPLOAD_SIZE)));
    if ($b_ok)
    {
        if (isset($a_file_spec['saved_as']) && !empty($a_file_spec['saved_as']))
        {
            if (!copy($s_srce,$s_dest) || !@unlink($s_srce))
                $b_ok = false;
        }
        else
        {
            if (!move_uploaded_file($s_srce,$s_dest))
                $b_ok = false;
        }
        if ($b_ok)
        {
                //
                // Flag to say it's been put in the repository.
                //
            $a_file_spec['in_repository'] = true;
                //
                // Its new location
                //
            $a_file_spec['saved_as'] = $s_dest;
                //
                // Now that the file has been saved, "is_uploaded_file"
                // will return false.  So, we create a flag to say it was
                // valid.
                //
            $a_file_spec['moved'] = true;
        }
        else
            $s_error = $php_errormsg;
    }
    if (!$b_ok)
    {
        SendAlert(GetMessage(MSG_SAVE_FILE,array(
                            "FILE"=>$s_srce,
                            "DEST"=>$s_dest,
                            "ERR"=>$s_error)));
        return (false);
    }
        //
        // ignore chmod fails (other than reporting them)
        //
    if (FILE_MODE != 0 && !chmod($s_dest,FILE_MODE))
        SendAlert(GetMessage(MSG_CHMOD,array(
                            "FILE"=>$s_dest,
                            "MODE"=>FILE_MODE,
                            "ERR"=>$s_error)));
    return (true);
}
 
    //
    // Save all uploaded files to the repository directory.
    //
function SaveAllFilesToRepository()
{
    global  $aFileVars;
 
    if (!FILEUPLOADS || $FILE_REPOSITORY === "")
            //
            // nothing to do
            //
        return (true);
 
    foreach ($aFileVars as $m_file_key=>$a_upload)
    {
            //
            // One customer reported:
            //  Possible file upload attack detected: name='' temp name='none'
            // on PHP 4.1.2 on RAQ4.
            // So, we now also test for 'name'.
            //
        if (!isset($a_upload['tmp_name']) || empty($a_upload['tmp_name']) ||
            !isset($a_upload['name']) || empty($a_upload['name']))
            continue;
        if (isset($a_upload['in_repository']) && $a_upload['in_repository'])
                //
                // already saved
                //
            continue;
        if (!IsUploadedFile($a_upload))
        {
            SendAlert(GetMessage(MSG_FILE_UPLOAD_ATTACK,
                            array("NAME"=>$a_upload['name'],
                                    "TEMP"=>$a_upload['tmp_name'],
                                    "FLD"=>$m_file_key)));
            continue;
        }
        if (!SaveFileInRepository($aFileVars[$m_file_key]))
            return (false);
    }
    return (true);
}
 
    //
    // Save an uploaded file for later processing.
    //
function SaveUploadedFile(&$a_file_spec,$s_prefix)
{
    global  $php_errormsg;
 
    $s_dest = GetScratchPadFile($s_prefix);
    if (!move_uploaded_file($a_file_spec['tmp_name'],$s_dest))
    {
        SendAlert(GetMessage(MSG_SAVE_FILE,array(
                            "FILE"=>$a_file_spec['tmp_name'],
                            "DEST"=>$s_dest,
                            "ERR"=>$php_errormsg)));
        return (false);
    }
    $a_file_spec['saved_as'] = $s_dest;
    $a_file_spec['moved'] = true;
    return (true);
}
 
    //
    // Remove old files from the scratchpad directory.
    //
function CleanScratchPad($s_prefix = "")
{
    global  $lNow,$CLEANUP_TIME,$CLEANUP_CHANCE;
    global  $php_errormsg,$SCRATCH_PAD;
 
    if (!isset($SCRATCH_PAD) || empty($SCRATCH_PAD))
            //
            // no scratchpad to cleanup!
            //
        return;
    if ($CLEANUP_TIME <= 0)
            //
            // cleanup disabled
            //
        return;
        //
        // compute chance of cleanup
        //
    if ($CLEANUP_CHANCE < 100)
    {
        $i_rand = mt_rand(1,100);
        if ($i_rand > $CLEANUP_CHANCE)
            return;
    }
    if (($f_dir = @opendir($SCRATCH_PAD)) === false)
    {
        Error("open_scratch_pad",GetMessage(MSG_OPEN_SCRATCH_PAD,array(
                                        "DIR"=>$SCRATCH_PAD,
                                        "ERR"=>$php_errormsg)),false,false);
        return;
    }
    $i_len = strlen($s_prefix);
    while (($s_file = readdir($f_dir)) !== false)
    {
        $s_path = $SCRATCH_PAD."/".$s_file;
        if (is_file($s_path) && ($i_len == 0 || substr($s_file,0,$i_len) == $s_prefix))
        {
            if (($a_stat = @stat($s_path)) !== false)
            {
                if (isset($a_stat['mtime']))
                    $l_time = $a_stat['mtime'];
                else
                    $l_time = $a_stat[9];
                if (($lNow - $l_time) / 60 >= $CLEANUP_TIME)
                    @unlink($s_path);
            }
        }
    }
    closedir($f_dir);
}
 
    //
    // Save all uploaded files for later processing.
    //
function SaveAllUploadedFiles(&$a_file_vars)
{
    global  $php_errormsg,$SCRATCH_PAD;
 
    $s_prefix = "UPLD";
    if (!isset($SCRATCH_PAD) || empty($SCRATCH_PAD))
    {
        Error("need_scratch_pad",GetMessage(MSG_NEED_SCRATCH_PAD),false,false);
        return (false);
    }
 
        //
        // remove old uploaded files that have not been moved out.
        //
    CleanScratchPad($s_prefix);
 
    foreach (array_keys($a_file_vars) as $m_file_key)
    {
        $a_upload = &$a_file_vars[$m_file_key];
            //
            // One customer reported:
            //  Possible file upload attack detected: name='' temp name='none'
            // on PHP 4.1.2 on RAQ4.
            // So, we now also test for 'name'.
            //
        if (!isset($a_upload['tmp_name']) || empty($a_upload['tmp_name']) ||
            !isset($a_upload['name']) || empty($a_upload['name']))
            continue;
            //
            // ensure we don't move the file more than once
            //
        if (!isset($a_upload['saved_as']) || empty($a_upload['saved_as']))
            if (!IsUploadedFile($a_upload))
                SendAlert(GetMessage(MSG_FILE_UPLOAD_ATTACK,
                                array("NAME"=>$a_upload['name'],
                                        "TEMP"=>$a_upload['tmp_name'],
                                        "FLD"=>$m_file_key)));
            elseif (!SaveUploadedFile($a_upload,$s_prefix))
                return (false);
    }
    return (true);
}
 
    //
    // Attach a file to the body of a MIME formatted email.  $a_lines is the
    // current body, and is modified to include the file.
    // $a_file_spec must have the following values (just like an uploaded
    // file specification):
    //      name        the name of the file
    //      type        the mime type
    //      tmp_name    the name of the temporary file
    //      size        the size of the temporary file
    //
    // Alternatively, you supply the following instead of tmp_name and size:
    //      data        the data to attach
    //
function AttachFile(&$a_lines,$s_att_boundary,$a_file_spec,$s_charset)
{
    $a_lines[] = "--$s_att_boundary".HEAD_CRLF;
        //
        // if a replacement name has been specified, use that, otherwise
        // use the original name
        //
    if (isset($a_file_spec['new_name']))
        $s_file_name = $a_file_spec['new_name'];
    else
        $s_file_name = $a_file_spec['name'];
    $s_file_name = str_replace('"','',$s_file_name);
    $s_mime_type = $a_file_spec['type'];
            //
            // The following says that the data is encoded in
            // base64 and is an attachment and that once decoded the
            // character set of the decoded data is $s_charset.
            // (See RFC 1521 Section 5.)
            //
    $a_lines[] = "Content-Type: $s_mime_type; name=\"$s_file_name\"; charset=$s_charset".HEAD_CRLF;
    $a_lines[] = "Content-Transfer-Encoding: base64".HEAD_CRLF;
    $a_lines[] = "Content-Disposition: attachment; filename=\"$s_file_name\"".HEAD_CRLF;
    $a_lines[] = HEAD_CRLF;         // blank line
    if (isset($a_file_spec['tmp_name']) && isset($a_file_spec['size']))
    {
        $s_srce = $a_file_spec['tmp_name'];
            //
            // check if the file has been saved elsewhere
            //
        if (isset($a_file_spec['saved_as']) && !empty($a_file_spec['saved_as']))
            $s_srce = $a_file_spec['saved_as'];
        return (AddFile($a_lines,$s_srce,$a_file_spec['size']));
    }
    if (!isset($a_file_spec['data']))
    {
        SendAlert(GetMessage(MSG_ATTACH_DATA));
        return (false);
    }
    return (AddData($a_lines,$a_file_spec['data']));
}
 
    //
    // Reformat the email to be in MIME format.
    // Process file attachments and and fill out any
    // specified HTML template.
    //
function MakeMimeMail(&$s_body,&$a_headers,$a_raw_fields,$s_template = "",
                    $s_missing = NULL,$b_no_plain = false,
                    $s_filter = "",$a_file_vars = array(),
                    $a_attach_spec = array())
{
    global  $FM_VERS,$aPHPVERSION;
    global  $SPECIAL_VALUES,$FILTER_ATTRIBS,$FILE_REPOSITORY;
 
    $s_charset = GetMailOption("CharSet");
    if (!isset($s_charset))
        $s_charset = "ISO-8859-1";
    $b_att = $b_html = false;
    $b_got_filter = (isset($s_filter) && !empty($s_filter));
    if (isset($s_template) && !empty($s_template))
    {
            //
            // need PHP 4.0.5 for the preg_replace_callback function
            //
        if (!IsPHPAtLeast("4.0.5"))
        {
            SendAlert(GetMessage(MSG_PHP_HTML_TEMPLATES,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
            return (false);
        }
        $b_html = true;
    }
    if (count($a_file_vars) > 0)
    {
        if (!IsPHPAtLeast("4.0.3"))
        {
            SendAlert(GetMessage(MSG_PHP_FILE_UPLOADS,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
            return (false);
        }
        if (!FILEUPLOADS)
            SendAlert(GetMessage(MSG_FILE_UPLOAD));
        elseif ($FILE_REPOSITORY === "")    // if storing on the server, don't attach
            foreach ($a_file_vars as $a_upload)
            {
                    //
                    // One customer reported:
                    //  Possible file upload attack detected: name='' temp name='none'
                    // on PHP 4.1.2 on RAQ4.
                    // So, we now also test for 'name'.
                    //
                if (isset($a_upload['tmp_name']) && !empty($a_upload['tmp_name']) &&
                    isset($a_upload['name']) && !empty($a_upload['name']))
                {
                    $b_att = true;
                    break;
                }
            }
    }
        //
        // check for an internally-generated attachment
        //
    if (isset($a_attach_spec["Data"]))
        $b_att = true;
 
    $s_uniq = md5($s_body);
    $s_body_boundary = "BODY$s_uniq";
    $s_att_boundary = "PART$s_uniq";
    $a_headers['MIME-Version'] = "1.0 (produced by FormMail $FM_VERS from www.tectite.com)";
 
        //
        // if the filter strips formatting, then we'll only have plain text
        // to send, even after the template has been used
        //
    if ($b_got_filter && IsFilterAttribSet($s_filter,"Strips"))
            //
            // no HTML if the filter strips the formatting
            //
        $b_html = false;
    $a_new = array();
    if ($b_att)
    {
        $a_headers['Content-Type'] = "multipart/mixed; boundary=\"$s_att_boundary\"";
 
        MimePreamble($a_new);
            //
            // add the body of the email
            //
        $a_new[] = "--$s_att_boundary".HEAD_CRLF;
        if ($b_html)
        {
            $a_lines = $a_local_headers = array();
            if (!HTMLMail($a_lines,$a_local_headers,$s_body,$s_template,
                            $s_missing,($b_got_filter) ? $s_filter : "",
                            $s_body_boundary,$a_raw_fields,$b_no_plain))
                return (false);
            $a_new = array_merge($a_new,ExpandMailHeadersArray($a_local_headers));
            $a_new[] = HEAD_CRLF;       // blank line after header
            $a_new = array_merge($a_new,$a_lines);
        }
        else
        {
            $a_new[] = "Content-Type: text/plain; charset=$s_charset".HEAD_CRLF;
            $a_new[] = HEAD_CRLF;       // blank line
                //
                // treat the body like one line, even though it isn't
                //
            $a_new[] = $s_body;
        }
            //
            // now add the attachments or save to the $FILE_REPOSITORY
            //
        if (FILEUPLOADS && $FILE_REPOSITORY === "")
            foreach ($a_file_vars as $m_file_key=>$a_upload)
            {
                    //
                    // One customer reported:
                    //  Possible file upload attack detected: name='' temp name='none'
                    // on PHP 4.1.2 on RAQ4.
                    // So, we now also test for 'name'.
                    //
                if (!isset($a_upload['tmp_name']) || empty($a_upload['tmp_name']) ||
                    !isset($a_upload['name']) || empty($a_upload['name']))
                    continue;
                if (!IsUploadedFile($a_upload))
                {
                    SendAlert(GetMessage(MSG_FILE_UPLOAD_ATTACK,
                                    array("NAME"=>$a_upload['name'],
                                          "TEMP"=>$a_upload['tmp_name'],
                                          "FLD"=>$m_file_key)));
                    continue;
                }
                if (MAX_FILE_UPLOAD_SIZE != 0 &&
                    $a_upload['size'] > MAX_FILE_UPLOAD_SIZE*1024)
                    UserError("upload_size",GetMessage(MSG_FILE_UPLOAD_SIZE,
                                              array("NAME"=>$a_upload['name'],
                                                    "SIZE"=>$a_upload['size'],
                                                    "MAX"=>MAX_FILE_UPLOAD_SIZE)));
                if (!AttachFile($a_new,$s_att_boundary,$a_upload,$s_charset))
                    return (false);
            }
        if (isset($a_attach_spec["Data"]))
        {
                //
                // build a specification similar to a file upload
                //
            $a_file_spec["name"] = isset($a_attach_spec["Name"]) ?
                                        $a_attach_spec["Name"] :
                                        "attachment.dat";
            $a_file_spec["type"] = isset($a_attach_spec["MIME"]) ?
                                        $a_attach_spec["MIME"] :
                                        "text/plain";
            $a_file_spec["data"] = $a_attach_spec["Data"];
            if (!AttachFile($a_new,$s_att_boundary,$a_file_spec,
                                isset($a_attach_spec["CharSet"]) ?
                                $a_attach_spec["CharSet"] :
                                $s_charset))
                return (false);
        }
        $a_new[] = "--$s_att_boundary--".HEAD_CRLF;     // the end
        $a_new[] = HEAD_CRLF;           // blank line
    }
    elseif ($b_html)
    {
        if (!HTMLMail($a_new,$a_headers,$s_body,$s_template,
                            $s_missing,($b_got_filter) ? $s_filter : "",
                            $s_body_boundary,$a_raw_fields,$b_no_plain))
            return (false);
    }
    else
    {
        $a_headers['Content-Type'] = "text/plain; charset=$s_charset";
            //
            // treat the body like one line, even though it isn't
            //
        $a_new[] = $s_body;
    }
 
    $s_body = JoinLines(BODY_LF,$a_new);
    return (true);
}
 
    //
    // to make a From line for the email
    //
function MakeFromLine($s_email,$s_name)
{
    $s_line = "";
    if (!empty($s_email))
        $s_line .= $s_email." ";
    if (!empty($s_name))
        $s_line .= "(".$s_name.")";
    return ($s_line);
}
 
    //
    // Return two sets of plain text output: the filtered fields and the
    // non-filtered fields.
    //
function GetFilteredOutput($a_fld_order,$a_clean_fields,$s_filter,$a_filter_list)
{
        //
        // find the non-filtered fields and make unfiltered text from them
        //
    $a_unfiltered_list = array();
    $n_flds = count($a_fld_order);
    for ($ii = 0 ; $ii < $n_flds ; $ii++)
        if (!in_array($a_fld_order[$ii],$a_filter_list))
            $a_unfiltered_list[] = $a_fld_order[$ii];
    $s_unfiltered_results = MakeFieldOutput($a_unfiltered_list,$a_clean_fields);
        //
        // filter the specified fields only
        //
    $s_filtered_results = MakeFieldOutput($a_filter_list,$a_clean_fields);
    $s_filtered_results = Filter($s_filter,$s_filtered_results);
    return (array($s_unfiltered_results,$s_filtered_results));
}
 
    //
    // Make a plain text email body
    //
function MakePlainEmail($a_fld_order,$a_clean_fields,
                        $s_to,$s_cc,$s_bcc,$a_raw_fields,$s_filter,$a_filter_list)
{
    global  $SPECIAL_VALUES,$aPHPVERSION;
 
    $s_unfiltered_results = $s_filtered_results = "";
    $b_got_filter = (isset($s_filter) && !empty($s_filter));
    if ($b_got_filter)
        if (isset($a_filter_list) && count($a_filter_list) > 0)
            $b_limited_filter = true;
        else
            $b_limited_filter = false;
    $b_used_template = false;
    if (IsMailOptionSet("PlainTemplate"))
    {
            //
            // need PHP 4.0.5 for the preg_replace_callback function
            //
        if (!IsPHPAtLeast("4.0.5"))
            SendAlert(GetMessage(MSG_PHP_PLAIN_TEMPLATES,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
        else
        {
            $s_template = GetMailOption("PlainTemplate");
            if (ProcessTemplate($s_template,$a_lines,$a_raw_fields,
                                GetMailOption('TemplateMissing'),
                                'SubstituteValuePlain'))
            {
                $b_used_template = true;
                $s_unfiltered_results = implode(BODY_LF,$a_lines);
                if ($b_got_filter)
                {
                        //
                        // with a limited filter, the template goes unfiltered
                        // and the named fields get filtered
                        //
                    if ($b_limited_filter)
                        list($s_discard,$s_filtered_results) =
                                    GetFilteredOutput($a_fld_order,$a_clean_fields,
                                            $s_filter,$a_filter_list);
                    else
                    {
                        $s_filtered_results = Filter($s_filter,$s_unfiltered_results);
                        $s_unfiltered_results = "";
                    }
                }
            }
        }
    }
    if (!$b_used_template)
    {
        $res_hdr = "";
 
        if (IsMailOptionSet("DupHeader"))
        {
                //
                // write some standard mail headers
                //
            $res_hdr = "To: $s_to".BODY_LF;
            if (!empty($s_cc))
                $res_hdr .= "Cc: $s_cc".BODY_LF;
            if (!empty($SPECIAL_VALUES["email"]))
                $res_hdr .= "From: ".MakeFromLine($SPECIAL_VALUES["email"],
                                        $SPECIAL_VALUES["realname"]).BODY_LF;
            $res_hdr .= BODY_LF;
            if (IsMailOptionSet("StartLine"))
                $res_hdr .= "--START--".BODY_LF;        // signals the beginning of the text to filter
        }
 
            //
            // put the realname and the email address at the top of the results
            // (if not excluded)
            //
        if (!IsMailExcluded("realname"))
        {
            array_unshift($a_fld_order,"realname");
            $a_clean_fields["realname"] = $SPECIAL_VALUES["realname"];
        }
        if (!IsMailExcluded("email"))
        {
            array_unshift($a_fld_order,"email");
            $a_clean_fields["email"] = $SPECIAL_VALUES["email"];
        }
        if ($b_got_filter)
        {
            if ($b_limited_filter)
                list($s_unfiltered_results,$s_filtered_results) =
                            GetFilteredOutput($a_fld_order,$a_clean_fields,
                                    $s_filter,$a_filter_list);
            else
            {
                    //
                    // make text output and filter it (filter all fields)
                    //
                $s_filtered_results = MakeFieldOutput($a_fld_order,$a_clean_fields);
                $s_filtered_results = Filter($s_filter,$s_filtered_results);
            }
        }
        else
        {
//SendAlert("There are ".count($a_fld_order)." fields in the order array");
//SendAlert("Here is the clean fields array:\r\n".var_export($a_clean_fields,true));
            $s_unfiltered_results = MakeFieldOutput($a_fld_order,$a_clean_fields);
        }
        $s_unfiltered_results = $res_hdr.$s_unfiltered_results;
    }
    $s_results = $s_unfiltered_results;
    if ($b_got_filter && !empty($s_filtered_results))
    {
        if (!empty($s_results))
            $s_results .= BODY_LF;
        $s_results .= $s_filtered_results;
    }
    return (array($s_results,$s_unfiltered_results,$s_filtered_results));
}
 
    //
    // Return the list of fields to be filtered, FALSE if no list provided.
    //
function GetFilterList()
{
    global  $SPECIAL_VALUES;
 
        //
        // no filter means no list of fields
        //
    if (!empty($SPECIAL_VALUES["filter"]))
        if (isset($SPECIAL_VALUES["filter_fields"]) && !empty($SPECIAL_VALUES["filter_fields"]))
            return (TrimArray(explode(",",$SPECIAL_VALUES["filter_fields"])));
    return (false);
}
 
    //
    // send the given results to the given email addresses
    //
function SendResults($a_fld_order,$a_clean_fields,$s_to,$s_cc,$s_bcc,$a_raw_fields)
{
    global  $SPECIAL_VALUES,$aFileVars,$FILE_REPOSITORY,$FIXED_SENDER;
 
        //
        // check for a filter and how to use it
        //
    $b_got_filter = (isset($SPECIAL_VALUES["filter"]) && !empty($SPECIAL_VALUES["filter"]));
    $b_filter_attach = false;
    $a_attach_spec = array();
    $s_filter = "";
    $a_filter_list = array();
    if ($b_got_filter)
    {
        $s_filter = $SPECIAL_VALUES["filter"];
        $a_filter_list = GetFilterList();
        if ($a_filter_list === false)
        {
                //
                // not a limited filter, so filter all fields
                //
            $b_limited_filter = false;
            $a_filter_list = array();
        }
        else
            $b_limited_filter = true;
        $s_filter_attach_name = GetFilterOption("Attach");
        if (isset($s_filter_attach_name))
             if (!is_string($s_filter_attach_name) || empty($s_filter_attach_name))
                SendAlert(GetMessage(MSG_ATTACH_NAME));
            else
            {
                $b_filter_attach = true;
                $a_attach_spec = array("Name"=>$s_filter_attach_name);
                if (($s_mime = GetFilterAttrib($s_filter,"MIME")) !== false)
                    $a_attach_spec["MIME"] = $s_mime;
                    //
                    // Regarding the character set...
                    // A filter will not generally change the character set
                    // of the message, however, if it does, then we
                    // provide that information to the MIME encoder.
                    // Remember: this character set specification refers
                    // to the data *after* the effect of the filter
                    // has been reversed (e.g. an encrypted message
                    // in UTF-8 is in UTF-8 when it is decrypted).
                    //
                if (($s_cset = GetFilterAttrib($s_filter,"CharSet")) !== false)
                    $a_attach_spec["CharSet"] = $s_cset;
            }
    }
 
        //
        // check the need for MIME formatted mail
        //
    $b_mime_mail = (IsMailOptionSet("HTMLTemplate") || count($aFileVars) > 0 ||
                    $b_filter_attach);
 
        //
        // create the email header lines - CC, BCC, and From
        //
    $a_headers = array();
    if (!empty($s_cc))
        $a_headers['Cc'] = $s_cc;
        //
        // note that BCC is documented to not work prior to PHP 4.3
        //
    if (!empty($s_bcc))
    {
        global  $aPHPVERSION;
 
        if ($aPHPVERSION[0] < 4 || ($aPHPVERSION[0] == 4 && $aPHPVERSION[1] < 3))
            SendAlert(GetMessage(MSG_PHP_BCC,
                            array("PHPVERS"=>implode(".",$aPHPVERSION))));
        $a_headers['Bcc'] = $s_bcc;
    }
        //
        // create the From address
        //
        // Some servers won't let you set the email address to the
        // submitter of the form.  Therefore, use FromAddr if it's been
        // specified to set the sender and the "From" address.
        //
    $s_sender = GetMailOption("FromAddr");
    if (!isset($s_sender))
    {
        $s_sender = "";
        if (!empty($SPECIAL_VALUES["email"]))
            $a_headers['From'] = MakeFromLine($SPECIAL_VALUES["email"],
                                            $SPECIAL_VALUES["realname"]);
    }
    elseif ($s_sender !== "")
        $s_sender = $a_headers['From'] = UnMangle($s_sender);
 
        /* 
         * Override sender if $FIXED_SENDER is set.
         */
    if ($FIXED_SENDER !== "")
        $s_sender = $FIXED_SENDER;
 
    if ($s_sender === "")
        if (SET_SENDER_FROM_EMAIL)
            $s_sender = $SPECIAL_VALUES["email"];
 
        //
        // special case: if there is only one non-special string value, then
        // format it as an email (unless an option says not to)
        //
    $a_keys = array_keys($a_raw_fields);
    if (count($a_keys) == 1 && is_string($a_raw_fields[$a_keys[0]]) &&
        !IsMailOptionSet("AlwaysList") && !IsMailOptionSet("DupHeader"))
    {
        if (IsMailExcluded($a_keys[0]))
            SendAlert("Exclusion of single field '".$a_keys[0]."' ignored");
        $s_value = $a_raw_fields[$a_keys[0]];
            //
            // replace carriage return/linefeeds with <br>
            //
        $s_value = str_replace("\r\n",'<br />',$s_value);
            //
            // replace lone linefeeds with <br>
            //
        $s_value = str_replace("\n",'<br />',$s_value);
            //
            // remove lone carriage returns
            //
        $s_value = str_replace("\r","",$s_value);
            //
            // replace all control chars with <br>
            //
        $s_value = preg_replace('/[[:cntrl:]]+/','<br />',$s_value);
            //
            // strip HTML (note that all the <br> above will now be
            // replaced with BODY_LF)
            //
        $s_value = StripHTML($s_value,BODY_LF);
 
        if ($b_mime_mail)
        {
            if ($b_got_filter)
            {
                    //
                    // filter the whole value (ignore filter_fields for this
                    // special case) if a filter has been specified
                    //
                $s_results = Filter($s_filter,$s_value);
                if ($b_filter_attach)
                {
                    $a_attach_spec["Data"] = $s_results;
                        //
                        // KeepInLine keeps the filtered version inline as well
                        // as an attachment
                        //
                    if (!IsFilterOptionSet("KeepInLine"))
                        $s_results = "";
                    $s_filter = ""; // no more filtering
                }
            }
            else
                $s_results = $s_value;
 
                //
                // send this single value off to get formatted in a MIME
                // email
                //
            if (!MakeMimeMail($s_results,$a_headers,$a_raw_fields,
                                GetMailOption('HTMLTemplate'),
                                GetMailOption('TemplateMissing'),
                                IsMailOptionSet("NoPlain"),
                                $s_filter,$aFileVars,$a_attach_spec))
                return (false);
        }
        elseif ($b_got_filter)
                //
                // filter the whole value (ignore filter_fields for this special case)
                // if a filter has been specified
                //
            $s_results = Filter($s_filter,$s_value);
        else
            $s_results = $s_value;
    }
    else
    {
        if ($b_mime_mail)
        {
                //
                // get the plain text version of the email then send it
                // to get MIME formatted
                //
            list($s_results,$s_unfiltered_results,$s_filtered_results) =
                            MakePlainEmail($a_fld_order,$a_clean_fields,
                                $s_to,$s_cc,$s_bcc,$a_raw_fields,$s_filter,
                                $a_filter_list);
            if ($b_filter_attach)
            {
                    //
                    // attached the filtered results
                    //
                $a_attach_spec["Data"] = $s_filtered_results;
                    //
                    // KeepInLine keeps the filtered version inline as well
                    // as an attachment
                    //
                if (!IsFilterOptionSet("KeepInLine"))
                        //
                        // put the unfiltered results in the body of the message
                        //
                    $s_results = $s_unfiltered_results;
                $s_filter = ""; // no more filtering
            }
            if (!MakeMimeMail($s_results,$a_headers,$a_raw_fields,
                                GetMailOption('HTMLTemplate'),
                                GetMailOption('TemplateMissing'),
                                IsMailOptionSet("NoPlain"),
                                $s_filter,$aFileVars,$a_attach_spec))
                return (false);
        }
        else
        {
            list($s_results,$s_unfiltered_results,$s_filtered_results) =
                            MakePlainEmail($a_fld_order,$a_clean_fields,
                                $s_to,$s_cc,$s_bcc,$a_raw_fields,$s_filter,
                                $a_filter_list);
            if (!$b_got_filter && IsMailOptionSet("CharSet"))
                    //
                    // sending plain text email, and the CharSet has been
                    // specified; include a header
                    //
                $a_headers['Content-Type'] = "text/plain; charset=".GetMailOption("CharSet");
        }
    }
 
        //
        // append the environment variables report
        //
    if (isset($SPECIAL_VALUES["env_report"]))
    {
        $s_results .= BODY_LF."==================================".BODY_LF;
        $s_results .= BODY_LF.GetEnvVars(TrimArray(explode(",",$SPECIAL_VALUES["env_report"])),BODY_LF);
    }
        //
        // now save uploaded files to the repository
        //
    if (FILEUPLOADS && $FILE_REPOSITORY !== "")
        if (!SaveAllFilesToRepository())
            return (false);
 
        //
        // send the mail - assumes the email addresses have already been checked
        //
    return (SendCheckedMail($s_to,$SPECIAL_VALUES["subject"],$s_results,
                                    $s_sender,$a_headers));
}
 
    //
    // append an entry to a log file
    //
function WriteLog($log_file)
{
    global  $SPECIAL_VALUES,$php_errormsg;
 
@   $log_fp = fopen($log_file,"a");
    if ($log_fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$log_file,
                                            "TYPE"=>"log",
                                            "ERROR"=>CheckString($php_errormsg))));
        return;
    }
    $date = gmdate("H:i:s d-M-y T");
    $entry = $date.":".$SPECIAL_VALUES["email"].",".
            $SPECIAL_VALUES["realname"].",".$SPECIAL_VALUES["subject"]."\n";
    fwrite($log_fp,$entry);
    fclose($log_fp);
}
 
    //
    // write the data to a comma-separated-values file
    //
function WriteCSVFile($s_csv_file,$a_vars)
{
    global  $SPECIAL_VALUES,$CSVSEP,$CSVINTSEP,$CSVQUOTE,$CSVOPEN,$CSVLINE;
 
        //
        // create an array of column values in the order specified
        // in $SPECIAL_VALUES["csvcolumns"]
        //
    $a_column_list = $SPECIAL_VALUES["csvcolumns"];
    if (!isset($a_column_list) || empty($a_column_list) || !is_string($a_column_list))
    {
        SendAlert(GetMessage(MSG_CSVCOLUMNS,array("VALUE"=>$a_column_list)));
        return;
    }
    if (!isset($s_csv_file) || empty($s_csv_file) || !is_string($s_csv_file))
    {
        SendAlert(GetMessage(MSG_CSVFILE,array("VALUE"=>$s_csv_file)));
        return;
    }
 
@   $fp = fopen($s_csv_file,"a".$CSVOPEN);
    if ($fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$s_csv_file,
                                            "TYPE"=>"CSV",
                                            "ERROR"=>CheckString($php_errormsg))));
        return;
    }
 
        //
        // convert the column list to an array, trim the names too
        //
    $a_column_list = TrimArray(explode(",",$a_column_list));
    $n_columns = count($a_column_list);
 
        //
        // if the file is currently empty, put the column names in the first line
        //
    if (filesize($s_csv_file) == 0)
    {
        for ($ii = 0 ; $ii < $n_columns ; $ii++)
        {
            fwrite($fp,$CSVQUOTE.$a_column_list[$ii].$CSVQUOTE);
            if ($ii < $n_columns-1)
                fwrite($fp,"$CSVSEP");
        }
        fwrite($fp,$CSVLINE);
    }
 
//  $debug = "";
//  $debug .= "gpc -> ".get_magic_quotes_gpc()."\n";
//  $debug .= "runtime -> ".get_magic_quotes_runtime()."\n";
    for ($ii = 0 ; $ii < $n_columns ; $ii++)
    {
        $s_col_name = $a_column_list[$ii];
            //
            // columns can be missing from some form submission and present
            // from others
            //
        if (isset($a_vars[$s_col_name]))
            $m_value = $a_vars[$s_col_name];
        else
            $m_value = "";
 
        if (LIMITED_IMPORT)
                //
                // the target database doesn't understand escapes, so
                // remove various things, including newlines and truncate
                //
            $m_value = CleanValue($m_value,false);
        else
                //
                // the target database does understand escapes, so
                // we have to slash any slashes
                //
            $m_value = str_replace("\\","\\\\",$m_value);
            //
            // convert quotes, depending on the setting of $CSVQUOTE
            //
        switch ($CSVQUOTE)
        {
        case '"':
                    //
                    // convert double quotes in the data to single quotes
                    //
            $m_value = str_replace("\"","'",$m_value);
            break;
        case '\'':
                    //
                    // convert single quotes in the data to double quotes
                    //
            $m_value = str_replace("'","\"",$m_value);
            break;
        default:
                //
                // otherwise, leave the data unchanged
                //
            break;
        }
            //
            // we handle arrays and strings
            //
        if (is_array($m_value))
                //
                // separate the values with the internal field separator
                //
            $m_value = implode("$CSVINTSEP",$m_value);
 
//      $debug .= $a_column_list[$ii]." => ".$m_value."\n";
        fwrite($fp,$CSVQUOTE.$m_value.$CSVQUOTE);
        if ($ii < $n_columns-1)
            fwrite($fp,"$CSVSEP");
    }
    fwrite($fp,$CSVLINE);
    fclose($fp);
//  CreatePage($debug);
//  exit;
}
 
function CheckConfig()
{
    global  $TARGET_EMAIL,$CONFIG_CHECK;
 
    $a_mesgs = array();
    if (in_array("TARGET_EMAIL",$CONFIG_CHECK))
    {
            //
            // $TARGET_EMAIL values should begin with ^ and end with $
            //
        for ($ii = 0 ; $ii < count($TARGET_EMAIL) ; $ii++)
        {
            $s_pattern = $TARGET_EMAIL[$ii];
            if (substr($s_pattern,0,1) != '^')
                $a_mesgs[] = GetMessage(MSG_TARG_EMAIL_PAT_START,
                                        array("PAT"=>$s_pattern));
            if (substr($s_pattern,-1) != '$')
                $a_mesgs[] = GetMessage(MSG_TARG_EMAIL_PAT_END,
                                        array("PAT"=>$s_pattern));
        }
    }
    if (count($a_mesgs) > 0)
        SendAlert(GetMessage(MSG_CONFIG_WARN,
                        array("MESGS"=>implode("\n",$a_mesgs))),false,true);
}
 
    //
    // append an entry to the Auto Responder log file
    //
function WriteARLog($s_to,$s_subj,$s_info)
{
    global  $LOGDIR,$AUTORESPONDLOG,$aServerVars,$php_errormsg;
 
    if (!isset($LOGDIR) || !isset($AUTORESPONDLOG) ||
            empty($LOGDIR) || empty($AUTORESPONDLOG))
        return;
 
    $log_file = $LOGDIR."/".$AUTORESPONDLOG;
@   $log_fp = fopen($log_file,"a");
    if ($log_fp === false)
    {
        SendAlert(GetMessage(MSG_FILE_OPEN_ERROR,array("NAME"=>$log_file,
                                            "TYPE"=>"log",
                                            "ERROR"=>CheckString($php_errormsg))));
        return;
    }
    $a_entry = array();
    $a_entry[] = gmdate("H:i:s d-M-y T");       // date/time in GMT
    $a_entry[] = $aServerVars['REMOTE_ADDR'];   // remote IP address
    $a_entry[] = $s_to;                         // target email address
    $a_entry[] = $s_subj;                       // subject line
    $a_entry[] = $s_info;                       // information
 
    $s_log_entry = implode(",",$a_entry)."\n";
    fwrite($log_fp,$s_log_entry);
    fclose($log_fp);
}
 
    //
    // Send an email response to the user.
    //
function AutoRespond($s_to,$s_subj,$a_values)
{
    global  $aPHPVERSION,$SPECIAL_VALUES,$FROM_USER;
 
        //
        // need PHP 4.0.5 for the preg_replace_callback function
        //
    if (!IsPHPAtLeast("4.0.5"))
    {
        SendAlert(GetMessage(MSG_PHP_AUTORESP,
                        array("PHPVERS"=>implode(".",$aPHPVERSION))));
        return (false);
    }
 
    $a_headers = array();
    $s_mail_text = "";
    $s_from_addr = GetAROption("FromAddr");
 
    if (!isset($s_from_addr))
    {
        $s_from_addr = "";
        if (isset($FROM_USER) && !empty($FROM_USER))
        {
            if ($FROM_USER != "NONE")
                $s_from_addr = $FROM_USER;
        }
        else
        {
            global  $SERVER;
 
            $s_from_addr = "FormMail@".$SERVER;
        }
    }
    else
        $s_from_addr = UnMangle($s_from_addr);
 
    if (!empty($s_from_addr))
        $a_headers['From'] = $s_from_addr;
 
    if (IsAROptionSet('PlainTemplate'))
    {
        $s_template = GetAROption("PlainTemplate");
        if (!ProcessTemplate($s_template,$a_lines,$a_values,
                                    GetAROption('TemplateMissing'),
                                    'SubstituteValuePlain'))
            return (false);
        $s_mail_text = implode(BODY_LF,$a_lines);
    }
    if (IsAROptionSet("HTMLTemplate"))
    {
        if (!MakeMimeMail($s_mail_text,$a_headers,$a_values,
                            GetAROption("HTMLTemplate"),
                            GetAROption('TemplateMissing')))
            return (false);
    }
    return (SendCheckedMail($s_to,$s_subj,$s_mail_text,$s_from_addr,$a_headers));
}
 
/*
 * The main logic starts here....
 */
 
    //
    // First, a special case; if formmail.php is called like this:
    //  http://.../formmail.php?testalert=1
    // it sends a test message to the default alert address with some
    // information about your PHP version and the DOCUMENT_ROOT.
    //
if (isset($aGetVars["testalert"]) && $aGetVars["testalert"] == 1)
{
    function ShowServerVar($s_name)
    {
        global  $aServerVars;
 
        return (isset($aServerVars[$s_name]) ? $aServerVars[$s_name] : "-not set-");
    }
    $sAlert = GetMessage(MSG_ALERT,
                array("LANG"=>$sLangID,
                      "PHPVERS"=>implode(".",$aPHPVERSION),
                      "FM_VERS"=>$FM_VERS,
                      "SERVER"=>(IsServerWindows() ? "Windows" : "non-Windows"),
                      "DOCUMENT_ROOT"=>ShowServerVar('DOCUMENT_ROOT'),
                      "SCRIPT_FILENAME"=>ShowServerVar('SCRIPT_FILENAME'),
                      "PATH_TRANSLATED"=>ShowServerVar('PATH_TRANSLATED'),
                      "REAL_DOCUMENT_ROOT"=>CheckString($REAL_DOCUMENT_ROOT),
                     ));
 
    if (DEF_ALERT == "")
        echo "<p>".GetMessage(MSG_NO_DEF_ALERT)."</p>";
    elseif (SendAlert($sAlert,false,true))
        echo "<p>".GetMessage(MSG_TEST_SENT)."</p>";
    else
        echo "<p>".GetMessage(MSG_TEST_FAILED)."</p>";
    exit;
}
 
if (isset($aGetVars["testlang"]) && $aGetVars["testlang"] == 1)
{
    if (!IsPHPAtLeast("4.1.0"))
    {
    ?>
        <p>testlang feature only works with PHP version 4.1.0 or later</p>
    <?php
    }
    else
    {
        function ShowMessages()
        {
            global  $aMessages,$sLangID,$bShowMesgNumbers,$aGetVars,$sHTMLCharSet;
 
                //
                // force message numbers on unless "mnums=no"
                //
            if (isset($aGetVars["mnums"]) && $aGetVars["mnums"] == "no")
                $bShowMesgNumbers = false;
            else
                $bShowMesgNumbers = true;
 
            LoadBuiltinLanguage();
 
 
            $s_def_lang = $sLangID;
            $a_def_mesgs = $aMessages;
 
            LoadLanguageFile();
 
            $s_active_lang = $sLangID;
            $a_active_mesgs = $aMessages;
 
            $a_list = get_defined_constants();
 
            echo "<html>\n";
            echo "<head>\n";
            if (isset($sHTMLCharSet) && $sHTMLCharSet !== "")
                echo "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=$sHTMLCharSet\">\n";
            echo "</head>\n";
            echo "<body>\n";
 
            echo "<table border=\"1\" cellpadding=\"10\" width=\"95%\">\n";
            echo "<tr>\n";
            echo "<th>\n";
            echo "Message Number";
            echo "</th>\n";
            echo "<th>\n";
            echo "$s_def_lang";
            echo "</th>\n";
            echo "<th>\n";
            echo "$s_active_lang";
            echo "</th>\n";
            echo "</tr>\n";
            foreach ($a_list as $s_name=>$i_value)
            {
                if (substr($s_name,0,4) == "MSG_")
                {
                    echo "<tr>\n";
                    echo "<td valign=\"top\">\n";
                    echo "$s_name ($i_value)";
                    echo "</td>\n";
                    echo "<td valign=\"top\">\n";
                    $aMessages = $a_def_mesgs;
                    $s_def_msg = GetMessage((int) $i_value,array(),true,true);
                    echo nl2br(htmlentities($s_def_msg));
                    echo "</td>\n";
                    echo "<td valign=\"top\">\n";
                    $aMessages = $a_active_mesgs;
                    $s_act_msg = GetMessage((int) $i_value,array(),true,true);
                    if ($s_def_msg == $s_act_msg)
                        echo "<i>identical</i>\n";
                    elseif (isset($sHTMLCharSet) && $sHTMLCharSet != "")
                                //
                                // unfortunately, htmlentities get some characters
                                // wrong and converts them even when the
                                // charset is provided
                                //
                        echo nl2br(htmlspecialchars($s_act_msg,ENT_COMPAT,$sHTMLCharSet));
                    else
                        echo nl2br(htmlentities($s_act_msg));
                    echo "</td>\n";
                    echo "</tr>\n";
                }
            }
            echo "</table>\n";
 
            echo "</body>\n";
            echo "</html>\n";
        }
        ShowMessages();
    }
    exit;
}
 
    //
    // Scan the Multi form sequence values and build up the values that
    // were submitted to the given form index.
    //
function GetMultiValues($a_form_list,$i_form_index,$a_order = array(),
                                            $a_clean = array(),
                                            $a_raw_data = array(),
                                            $a_all_data = array(),
                                            $a_file_data = array())
{
    $a_ret_clean = $a_ret_raw = $a_ret_all = $a_ret_files = array();
    for ($ii = 0 ; $ii < $i_form_index ; $ii++)
    {
            //
            // only add a field to the order if it's not already there
            //
        $a_form_order = $a_form_list[$ii]["ORDER"];
        $n_order = count($a_form_order);
        for ($jj = 0 ; $jj < $n_order ; $jj++)
        {
            if (array_search($a_form_order[$jj],$a_order) === false)
                $a_order[] = $a_form_order[$jj];
        }
        $a_ret_clean = array_merge($a_ret_clean,$a_form_list[$ii]["CLEAN"]);
        $a_ret_raw = array_merge($a_ret_raw,$a_form_list[$ii]["RAWDATA"]);
        $a_ret_all = array_merge($a_ret_all,$a_form_list[$ii]["ALLDATA"]);
        $a_ret_files = array_merge($a_ret_files,$a_form_list[$ii]["FILES"]);
    }
        //
        // later values must take precedence to earlier values,
        // so merge in the passed-in data last
        //
    $a_ret_clean = array_merge($a_ret_clean,$a_clean);
    $a_ret_raw = array_merge($a_ret_raw,$a_raw_data);
    $a_ret_all = array_merge($a_ret_all,$a_all_data);
    $a_ret_files = array_merge($a_ret_files,$a_file_data);
    return (array($a_order,$a_ret_clean,$a_ret_raw,$a_ret_all,$a_ret_files));
}
 
$bMultiForm = false;
 
    //
    // Multi-page form sequencing is complicated....
    // Requirements:
    //      1. The first page in a multi-page form sequence must provide:
    //          - multi_start field set to 1
    //          - this_form field (it's own URL)
    //          - next_form field (multi-page form template name)
    //      2. Subsequent pages must provide either:
    //          next_form (the next template name in the sequence)
    //         OR
    //          good_url or good_template or neither; this terminates
    //          the multi-page processing and provides the final URL.
    // Logic:
    //      1. We create session variables to contain information about
    //         the sequence.
    //      2. On the first submission from the starting form, we record
    //         its "this_form" URL and the data submitted.
    //         We also create a URL (to FormMail) that will allow return
    //         to the *next* form in the sequence.
    //      3. On submission from other forms in the sequence, we record
    //         the data that was submitted so we can return to that
    //         form with the user's data re-filled into the form.
    //         We also create a URL (to FormMail) that will allow return
    //         to the *next* form in the sequence.
    //      4. A return URL contains "return=index" where index is the
    //         form sequence index number.  This is a URL to FormMail.
    //         FormMail gets the template name or URL (URL only for the
    //         starting form) and outputs the requested HTML form.  It also
    //         truncates the session data for forms after the returned-to
    //         one.
    //
 
    //
    // Return to a previous form in a sequence.
    //
function MultiFormReturn($i_return_to)
{
    global  $aSessionVars;
    global  $iFormIndex;
 
    if (!isset($aSessionVars["FormList"]) ||
           !isset($aSessionVars["FormIndex"]) ||
            $i_return_to < 0 ||
            $i_return_to > $aSessionVars["FormIndex"])
        Error("cannot_return",GetMessage(MSG_CANNOT_RETURN,
                                array("TO"=>$i_return_to,
                                    "TOPINDEX"=>(
                                        isset($aSessionVars["FormIndex"]) ?
                                        $aSessionVars["FormIndex"] :
                                        "<undefined>"))),
                                false,false);
    assert($i_return_to < count($aSessionVars["FormList"]));
    $a_form_def = $aSessionVars["FormList"][$i_return_to];
    $aSessionVars["FormList"] = array_slice($aSessionVars["FormList"],0,$i_return_to+1);
    $aSessionVars["FormIndex"] = $iFormIndex = $i_return_to;
    if (isset($a_form_def["FORM"]))
    {
        list(,,$a_values,,) = GetMultiValues($aSessionVars["FormList"],$i_return_to);
        $a_lines = array();
        if (ProcessMultiFormTemplate($a_form_def["FORM"],$a_values,$a_lines))
        {
            $n_lines = count($a_lines);
            $s_buf = "";
            for ($ii = 0 ; $ii < $n_lines ; $ii++)
            {
                $s_buf .= $a_lines[$ii]."\n";
                unset($a_lines[$ii]);       // free memory (hopefully)
            }
            unset($a_lines);       // free memory (hopefully)
                //
                // put in the values that the user previously submitted
                // to this form
                //
            echo SetPreviousValues($s_buf,$a_form_def["RAWDATA"]);
        }
        else
            Error("multi_form_failed",GetMessage(MSG_MULTIFORM_FAILED,
                                    array("NAME"=>$s_template)),false,false);
    }
    else
        ProcessReturnToForm($a_form_def["URL"],$a_form_def["RAWDATA"]);
    //
    // no return form this functon
    //
    //echo "Returned to $i_return_to";
}
 
    //
    // Store any data just submitted and specified as "multi_keep".
    //
function MultiKeep()
{
    global  $SPECIAL_VALUES,$aSessionVars,$aRawDataValues;
 
    if (isset($SPECIAL_VALUES["multi_keep"]) &&
        !empty($SPECIAL_VALUES["multi_keep"]))
    {
        $a_list = TrimArray(explode(",",$SPECIAL_VALUES["multi_keep"]));
        if (!isset($aSessionVars["FormKeep"]))
            $aSessionVars["FormKeep"] = array();
            //
            // For each data field specified in "multi_keep" store its
            // value in the FormKeep session variable.
            // If a field is specified and does not exist in the
            // recent submission, its value is discarded.
            //
        foreach ($a_list as $s_fld_name)
            if (!empty($s_fld_name))
                if (isset($aRawDataValues[$s_fld_name]))
                    $aSessionVars["FormKeep"][$s_fld_name] = $aRawDataValues[$s_fld_name];
                else
                    unset($aSessionVars["FormKeep"][$s_fld_name]);
    }
}
 
    //
    // Perform Logic for Multi-Page form sequences
    //
function MultiFormLogic()
{
    global  $bMultiForm,$SPECIAL_VALUES,$aSessionVars,$aServerVars,$aFileVars;
    global  $sFormMailScript,$bGotGoBack,$bGotNextForm,$iFormIndex;
    global  $aFieldOrder,$aCleanedValues,$aRawDataValues,$aAllRawValues;
 
    if ($SPECIAL_VALUES["multi_start"] == 1)
    {
        if (empty($SPECIAL_VALUES["this_form"]))
            ErrorWithIgnore("need_this_form",GetMessage(MSG_NEED_THIS_FORM),false,false);
 
        $bMultiForm = true;
            //
            // Start of multi-page form sequence
            //
        $aSessionVars["FormList"] = array();
        $aSessionVars["FormList"][0] = array("URL"=>$SPECIAL_VALUES["this_form"],
                                            "ORDER"=>$aFieldOrder,
                                            "CLEAN"=>$aCleanedValues,
                                            "RAWDATA"=>$aRawDataValues,
                                            "ALLDATA"=>$aAllRawValues,
                                            "FILES"=>$aFileVars);
        $iFormIndex = $aSessionVars["FormIndex"] = 0;   // zero is the first form, which was
                                                        // just submitted
    }
    elseif (isset($aSessionVars["FormList"]))
        $bMultiForm = true;
 
    if ($bMultiForm)
    {
        if (isset($aServerVars["PHP_SELF"]) &&
            !empty($aServerVars["PHP_SELF"]) &&
            isset($aServerVars["SERVER_NAME"]) &&
            !empty($aServerVars["SERVER_NAME"]))
        {
            if (isset($aServerVars["SERVER_PORT"]) &&
                $aServerVars["SERVER_PORT"] != 80)
            {
                if ($aServerVars["SERVER_PORT"] == 443)     // SSL port
                        //
                        // just use https prefix
                        //
                    $sFormMailScript = "https://".$aServerVars["SERVER_NAME"].
                                                $aServerVars["PHP_SELF"];
                else
                        //
                        // use http with port number
                        //
                    $sFormMailScript = "http://".$aServerVars["SERVER_NAME"].
                                        ":".$aServerVars["SERVER_PORT"].
                                        $aServerVars["PHP_SELF"];
            }
            else
                $sFormMailScript = "http://".$aServerVars["SERVER_NAME"].
                                        $aServerVars["PHP_SELF"];
            $iFormIndex = $aSessionVars["FormIndex"];
        }
        else
            Error("no_php_self",GetMessage(MSG_NO_PHP_SELF),false,false);
    }
 
        //
        // If we're going forward in a multi-page form sequence,
        // compute a URL to return to the form we're about to display.
        //
    if ($bMultiForm && !$bGotGoBack)
    {
            //
            // record the data that was just submitted by the previous form
            //
        $iFormIndex = $aSessionVars["FormIndex"];
        $aSessionVars["FormList"][$iFormIndex]["ORDER"] = $aFieldOrder;
        $aSessionVars["FormList"][$iFormIndex]["CLEAN"] = $aCleanedValues;
        $aSessionVars["FormList"][$iFormIndex]["RAWDATA"] = $aRawDataValues;
        $aSessionVars["FormList"][$iFormIndex]["ALLDATA"] = $aAllRawValues;
        if (count($aFileVars) > 0 && !FILEUPLOADS)
            SendAlert(GetMessage(MSG_FILE_UPLOAD));
        elseif (count($aFileVars) > 0 && !SaveAllUploadedFiles($aFileVars))
            Error("upload_save_failed",GetMessage(MSG_MULTI_UPLOAD),false,false);
        $aSessionVars["FormList"][$iFormIndex]["FILES"] = $aFileVars;
        $iFormIndex++;
        $s_url = GetReturnLink($sFormMailScript,$iFormIndex);
        $aSessionVars["FormList"][$iFormIndex] = array("URL"=>$s_url,
                                    "FORM"=>$SPECIAL_VALUES["next_form"],
                                    "ORDER"=>$aFieldOrder,
                                    "CLEAN"=>$aCleanedValues,
                                    "RAWDATA"=>$aRawDataValues,
                                    "ALLDATA"=>$aAllRawValues,
                                    "FILES"=>$aFileVars);
        $aSessionVars["FormIndex"] = $iFormIndex;
        MultiKeep();
    }
}
 
    //
    // Check for the MIME Attack
    //
function DetectMimeAttack($a_fields,&$s_attack,&$s_info)
{
        //
        // if any of the recipient fields contain "MIME-Version" or
        // "Content-Type" then this is the MIME attack
        // Now also checks the subject field.
        //
    $a_rec_flds = array("recipients","cc","bcc","subject");   // all these fields must be scalar (not arrays)
    foreach ($a_rec_flds as $s_fld)
        if (isset($a_fields[$s_fld]) && is_scalar($a_fields[$s_fld]))
        {
            $s_data = strtolower($a_fields[$s_fld]);
            if (($i_mime = strpos($s_data,"mime-version")) !== false ||
                ($i_cont = strpos($s_data,"content-type")) !== false)
            {
                $s_attack = "MIME";
                $s_info = GetMessage(MSG_ATTACK_MIME_INFO,
                            array("FLD"=>$s_fld,
                                  "CONTENT"=>($i_mime !== false) ?
                                                "mime-version" :
                                                "content-type"),false);
                return (true);
            }
        }
    return (false);
}
 
    //
    // Check for the duplicate data attack
    //
function DetectDupAttack($a_fields,&$s_attack,&$s_info)
{
        //
        // if any of the configured fields contain duplicate data,
        // then this lame attack has been detected
        //
    global  $ATTACK_DETECTION_DUPS;
 
    $a_data_map = array();
    foreach ($ATTACK_DETECTION_DUPS as $s_fld)
        if (isset($a_fields[$s_fld]) &&
            is_scalar($a_fields[$s_fld]) &&    // can only work with string data
            !empty($a_fields[$s_fld]))
        {
            $s_data = (string) $a_fields[$s_fld];
            if (isset($a_data_map[$s_data]))
            {
                    //
                    // duplicate found!
                    //
                $s_attack = "Duplicate Fields";
                $s_info = GetMessage(MSG_ATTACK_DUP_INFO,
                            array("FLD1"=>$a_data_map[$s_data],
                                  "FLD2"=>$s_fld),false);
                return (true);
            }
            $a_data_map[$s_data] = $s_fld;
        }
    return (false);
}
 
    //
    // Check for the email addresses in specials attack
    //
function DetectSpecialsAttack($a_fields,&$s_attack,&$s_info)
{
    global  $ATTACK_DETECTION_SPECIALS_ONLY_EMAIL,
            $ATTACK_DETECTION_SPECIALS_ANY_EMAIL;
 
        //
        // look for email addresses in whole fields
        //
    foreach ($ATTACK_DETECTION_SPECIALS_ONLY_EMAIL as $s_fld)
    {
        if (isset($a_fields[$s_fld]) &&
            is_scalar($a_fields[$s_fld]) &&    // can only work with string data
            !empty($a_fields[$s_fld]))
        {
            $s_data = $a_fields[$s_fld];
            if (preg_match("/^\b[-a-z0-9._%]+@[-.%_a-z0-9]+\.[a-z]{2,9}\b$/i",
                            $s_data) === 1)
            {
                    //
                    // email address found in wrong field
                    //
                $s_attack = "Special Fields Only";
                $s_info = GetMessage(MSG_ATTACK_SPEC_INFO,
                            array("FLD"=>$s_fld),false);
                return (true);
            }
        }
    }
        //
        // look for email addresses in any part of fields
        //
    foreach ($ATTACK_DETECTION_SPECIALS_ANY_EMAIL as $s_fld)
    {
        if (isset($a_fields[$s_fld]) &&
            is_scalar($a_fields[$s_fld]) &&    // can only work with string data
            !empty($a_fields[$s_fld]))
        {
            $s_data = $a_fields[$s_fld];
            if (preg_match("/\b[-a-z0-9._%]+@[-.%_a-z0-9]+\.[a-z]{2,9}\b/i",
                            $s_data) > 0)
            {
                    //
                    // email address found in wrong field
                    //
                $s_attack = "Special Fields Any";
                $s_info = GetMessage(MSG_ATTACK_SPEC_INFO,
                            array("FLD"=>$s_fld),false);
                return (true);
            }
        }
    }
    return (false);
}
 
    //
    // Check for "many URLs in a field" and "many fields with URLs" attacks
    //
function DetectManyURLsAttack($a_fields,&$s_attack,&$s_info)
{
    global      $ATTACK_DETECTION_URL_PATTERNS;
 
    $a_fld_names = array();
        //
        // actual URL link patterns
        //
    $s_srch = '((\bhttps{0,1}:\/\/|<\s*a\s+href=["'."'".']{0,1})[-a-z0-9.]+\b)';
 
        //
        // now add configurable patterns
        //
    if (!empty($ATTACK_DETECTION_URL_PATTERNS) &&
        is_array($ATTACK_DETECTION_URL_PATTERNS))
    {
            //
            // escape / characters and build up a string
            // of alternate patterns
            //
        foreach ($ATTACK_DETECTION_URL_PATTERNS as $s_pat)
        {
            if ($s_pat == "")
                continue;
            $s_srch .= "|".str_replace('/','\/',$s_pat);
        }
    }
 
    foreach ($a_fields as $s_fld=>$s_data)
    {
        if (IsSpecialField($s_fld) || IsSpecialMultiField($s_fld))
                //
                // skip special fields because some are supposed to
                // have URLs in them
                //
            continue;
        if (isset($s_data) &&
            is_scalar($s_data) &&    // can only work with string data
            !empty($s_data))
        {
            $n_match = preg_match_all("/$s_srch/msi",$s_data,$a_matches);
            if (!is_int($n_match))
                $n_match = 0;
            /*
             * debugging code....
             if ($n_match > 0)
                echo "Pattern is '".htmlentities($s_srch)."' with '".
                    htmlentities($s_data)."' field '$s_fld', matched=$n_match<br />";
             */
            if (ATTACK_DETECTION_MANY_URLS > 0)
                if ($n_match >= ATTACK_DETECTION_MANY_URLS)
                {
                    $s_attack = "Many URLS in a field";
                    $s_info = GetMessage(MSG_ATTACK_MANYURL_INFO,
                                array("FLD"=>$s_fld,"NUM"=>($n_match)),false);
                    return (true);
                }
            if ($n_match > 0)
                $a_fld_names[] = $s_fld;
        }
    }
    if (ATTACK_DETECTION_MANY_URL_FIELDS > 0)
        if (count($a_fld_names) >= ATTACK_DETECTION_MANY_URL_FIELDS)
        {
            $s_attack = "Many fields with URLs";
            $s_info = GetMessage(MSG_ATTACK_MANYFIELDS_INFO,
                        array("FLDS"=>implode(",",$a_fld_names),
                                "NUM"=>(count($a_fld_names))),false);
            return (true);
        }
    return (false);
}
 
    //
    // Detect annoying attacks and prevent them from sending spurious
    // alert messages.
    //
function DetectAttacks($a_fields)
{
    global      $ATTACK_DETECTION_DUPS;
 
    $s_info = $s_attack = "";
    $b_attacked = false;
    if (ATTACK_DETECTION_MIME)
        if (DetectMimeAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
    if (!$b_attacked && !empty($ATTACK_DETECTION_DUPS))
        if (DetectDupAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
    if (!$b_attacked && ATTACK_DETECTION_SPECIALS)
        if (DetectSpecialsAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
    if (!$b_attacked && (ATTACK_DETECTION_MANY_URLS ||
                        ATTACK_DETECTION_MANY_URL_FIELDS))
        if (DetectManyURLsAttack($a_fields,$s_attack,$s_info))
            $b_attacked = true;
 
    if ($b_attacked)
    {
        if (ALERT_ON_ATTACK_DETECTION)
            SendAlert(GetMessage(MSG_ATTACK_DETECTED,
                    array("ATTACK"=>$s_attack,
                          "INFO"=>$s_info,)),
                        false);
        if (ATTACK_DETECTION_URL !== "")
            Redirect(ATTACK_DETECTION_URL);
        else
            CreatePage(GetMessage(MSG_ATTACK_PAGE));
        exit;
    }
}
 
$bAdvTemplates = false;
if (ADVANCED_TEMPLATES &&
        (!empty($TEMPLATEDIR) || !empty($TEMPLATEURL) ||
        !empty($MULTIFORMDIR) || !empty($MULTIFORMURL)))
    $bAdvTemplates = true;
 
if (isset($aGetVars["return"]) && is_numeric($aGetVars["return"]))
{
        //
        // if advanced templates are in use, we will need them for
        // performing a multi-page form return
        //
    if ($bAdvTemplates)
    {
        $FMCTEMPLATE_PROC = true;
        if (!include_once("$MODULEDIR/$FMCOMPUTE"))
            Error("load_fmcompute",GetMessage(MSG_LOAD_FMCOMPUTE,
                            array("FILE"=>"$MODULEDIR/$FMCOMPUTE",
                                    "ERROR"=>$php_errormsg)),false,false);
    }
    MultiFormReturn($aGetVars["return"]);
    exit;
}
 
    //
    // Hook system: after initialization
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookpostinit.inc");
 
    //
    // check configuration values for potential security problems
    //
CheckConfig();
 
    //
    // otherwise, do the real processing of FormMail
    //
$aStrippedFormVars = $aAllRawValues = StripGPCArray($aFormVars);
 
if (ENABLE_ATTACK_DETECTION)
    DetectAttacks($aAllRawValues);
 
    //
    // process the options
    //
ProcessMailOptions($aAllRawValues);
ProcessCRMOptions($aAllRawValues);
ProcessAROptions($aAllRawValues);
ProcessFilterOptions($aAllRawValues);
 
    //
    // create any derived fields
    //
$aAllRawValues = CreateDerived($aAllRawValues);
 
list($aFieldOrder,$aCleanedValues,$aRawDataValues) = ParseInput($aAllRawValues);
 
    //
    // if we're processing multi-forms, then merge in the raw data from previous
    // forms unless this is the first page of the form sequence
    //
if (isset($aSessionVars["FormList"]) && $SPECIAL_VALUES["multi_start"] != 1)
{
    list($aFieldOrder,$aCleanedValues,
            $aRawDataValues,$aAllRawValues,$aFileVars) = GetMultiValues(
                            $aSessionVars["FormList"],
                            $aSessionVars["FormIndex"],
                            $aFieldOrder,$aCleanedValues,
                            $aRawDataValues,$aAllRawValues,
                            $aFileVars);
}
 
if ($SPECIAL_VALUES["file_names"] !== "")
    list($aFieldOrder,$aCleanedValues,$aRawDataValues,$aAllRawValues,$aFileVars) =
            SetFileNames($SPECIAL_VALUES["file_names"],$aFieldOrder,
                    $aCleanedValues,$aRawDataValues,$aAllRawValues,$aFileVars);
 
    //
    // Hook system: after loading and processing data
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookload.inc");
 
if ($FORM_INI_FILE !== "")
{
    ProcessFormIniFile($FORM_INI_FILE);
        //
        // Hook system: after processing INI file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookinifile.inc");
}
 
$bDoneSomething = false;
if (DB_SEE_INPUT)
{
    /***
    echo "<pre>";
    print_r($aFormVars);
    print_r($aServerVars);
    echo "</pre>";
    exit;
    ****/
    CreatePage(implode("\n",$FORMATTED_INPUT));
    ZapSession();
    exit;
}
 
if (!empty($SPECIAL_VALUES["fmcompute"]) || $bAdvTemplates)
{
    $FM_UserErrors = array();
        //
        // Generalized interface between FMCompute and FormMail functions
        //
    function FM_CallFunction($s_func,$a_params,&$m_return,
                                &$s_mesg,&$a_debug,&$a_alerts)
    {
        switch ($s_func)
        {
        case "FMFatalError":
            SendComputeAlerts();
            if (count($a_params) < 3)
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            else
                Error("fmcompute_error",$a_params[0],$a_params[1],$a_params[2]);
            break;
 
        case "FMFatalUserError":
            SendComputeAlerts();
            if (count($a_params) < 1)
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            else
                UserError("fmcompute_usererror",$a_params[0]);
            break;
 
        case "FMUserError":
            if (count($a_params) < 1)
            {
                SendComputeAlerts();
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            }
            else
            {
                global  $FM_UserErrors;
 
                $FM_UserErrors[] = $a_params[0];
            }
            break;
 
        case "FMSaveAllFilesToRepository":
            if (count($a_params) != 0)
            {
                SendComputeAlerts();
                Error("fmcompute_call",GetMessage(MSG_CALL_PARAM_COUNT,
                                        array("FUNC"=>$s_func,
                                            "COUNT"=>count($a_params))),
                                        false,false);
            }
            else
                $m_return = SaveAllFilesToRepository();
            break;
 
        default:
            $s_mesg = GetMessage(MSG_CALL_UNK_FUNC,array("FUNC"=>$s_func));
            return (false);
        }
        return (true);
    }
 
        //
        // register useful FormMail functions with FMCompute module
        //
    function RegisterFormMailFunctions(&$fmc)
    {
            //
            // Allows the user to call "Error" from within a computation
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","void",
                            "FMFatalError",
                            array("string","bool","bool"),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMFatalError",
                                          "ERROR"=>$s_msg)),false,false);
            //
            // Allows the user to call "UserError" from within a computation
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","void",
                            "FMFatalUserError",
                            array("string"),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMFatalUserError",
                                          "ERROR"=>$s_msg)),false,false);
 
            //
            // Allows the user to record an error to be displayed
            // from within a computation.
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","void",
                            "FMUserError",
                            array("string"),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMUserError",
                                          "ERROR"=>$s_msg)),false,false);
 
            //
            // Saves files to the repository.
            //
        if (($s_msg = $fmc->RegisterExternalFunction("PHP","bool",
                            "FMSaveAllFilesToRepository",
                            array(),
                            "FM_CallFunction")) !== true)
            Error("fmcompute_reg",GetMessage(MSG_REG_FMCOMPUTE,
                                    array("FUNC"=>"FMSaveAllFilesToRepository",
                                          "ERROR"=>$s_msg)),false,false);
 
    }
 
        //
        // load the fmcompute module
        //
    if (!empty($SPECIAL_VALUES["fmcompute"]))
    {
        $FMCOMPUTE_CLASS = true;
        $FMCOMPUTE_NODEBUG = true;
    }
    if ($bAdvTemplates)
        $FMCTEMPLATE_PROC = true;
    if (!include_once("$MODULEDIR/$FMCOMPUTE"))
        Error("load_fmcompute",GetMessage(MSG_LOAD_FMCOMPUTE,
                        array("FILE"=>"$MODULEDIR/$FMCOMPUTE",
                                "ERROR"=>$php_errormsg)),false,false);
    if (!empty($SPECIAL_VALUES["fmcompute"]))
    {
        RegisterFormMailFunctions($FMCalc);
 
            //
            // if GeoIP support is specified, load that module now
            //
        if (!empty($GEOIP_LIC))
        {
            $FMMODULE_LOAD = true;      // signal module load
            if (!include_once("$MODULEDIR/$FMGEOIP"))
                Error("load_module",GetMessage(MSG_LOAD_MODULE,
                                array("FILE"=>"$MODULEDIR/$FMGEOIP",
                                        "ERROR"=>$php_errormsg)),false,false);
                //
                // load the license and register the module
                //
            $GeoIP = new FMGeoIP($GEOIP_LIC);
            if (!$GeoIP->RegisterModule($FMCalc))
                Error("reg_module",GetMessage(MSG_REGISTER_MODULE,
                                array("NAME"=>"FMGeoIP",
                                       "ERROR"=>$GeoIP->GetError())),false,false);
        }
    }
}
 
if (isset($SPECIAL_VALUES["multi_go_back"]) && !empty($SPECIAL_VALUES["multi_go_back"]))
{
    if (!isset($aSessionVars["FormList"]) || $aSessionVars["FormIndex"] == 0)
        ErrorWithIgnore("go_back",GetMessage(MSG_GO_BACK),false,false);
    MultiKeep();        // store any "multi_keep" data just submitted
    MultiFormReturn($aSessionVars["FormIndex"]-1);
//    echo "Form index = ".$aSessionVars["FormIndex"];
    exit;
}
 
    //
    // This is the check for spiders; I can't imagine a spider will
    // ever use the POST method.
    //
if ($bIsGetMethod && count($aFormVars) == 0)
{
    CreatePage(GetMessage(MSG_NO_DATA_PAGE));
    ZapSession();
    exit;
}
 
    //
    // Hook system: before performing required and conditions etc.
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookprechecks.inc");
 
    //
    // check for required fields
    //
if (!CheckRequired($SPECIAL_VALUES["required"],$aAllRawValues,$missing,$a_missing_list))
    UserError("missing_fields",GetMessage(MSG_REQD_ERROR),$missing,$a_missing_list);
 
    //
    // check complex conditions
    //
if (!CheckConditions($SPECIAL_VALUES["conditions"],$aAllRawValues,$missing,$a_missing_list))
    UserError("failed_conditions",GetMessage(MSG_COND_ERROR),$missing,$a_missing_list);
 
    //
    // check imgverify
    //
if (isset($SPECIAL_VALUES["imgverify"]) && !empty($SPECIAL_VALUES["imgverify"]))
{
        //
        // VerifyImgString is from Tectite's simple verifyimg.php CAPTCHA
        // turing_string is from Captcha Creator
        //
    if (!isset($aSessionVars["VerifyImgString"]) &&
        !isset($aSessionVars["turing_string"]))
        ErrorWithIgnore("verify_failed",GetMessage(MSG_VERIFY_MISSING),false);
        //
        // the user's entry must match the value in the session; allow
        // spaces in the user's input
        //
    if (isset($aSessionVars["VerifyImgString"]))
    {
        if (str_replace(" ","",$SPECIAL_VALUES["imgverify"]) !==
                    $aSessionVars["VerifyImgString"])
            UserError("img_verify",GetMessage(MSG_VERIFY_MATCH));
    }
    else
    {
        if (strtoupper(str_replace(" ","",$SPECIAL_VALUES["imgverify"])) !==
                    strtoupper($aSessionVars["turing_string"]))
            UserError("img_verify",GetMessage(MSG_VERIFY_MATCH)/*,
                        "imgverify='".$SPECIAL_VALUES["imgverify"]."' ".
                        "turing_string='".$aSessionVars["turing_string"]."'"*/);
    }
}
 
    //
    // Hook system: after performing required and conditions etc.
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookchecks.inc");
 
if (!empty($SPECIAL_VALUES["fmmodules"]))
{
    $aModuleList = TrimArray(explode(",",$SPECIAL_VALUES["fmmodules"]));
    $FMMODULE_LOAD = true;      // signal module load
    foreach ($aModuleList as $sModule)
        if (!include_once("$MODULEDIR/$sModule"))
            Error("load_module",GetMessage(MSG_LOAD_MODULE,
                            array("FILE"=>"$MODULEDIR/$sModule",
                                    "ERROR"=>$php_errormsg)),false,false);
}
 
if (!empty($SPECIAL_VALUES["fmcompute"]))
{
        //
        // Callback function for preg_replace_callback to add line
        // numbers on each match
        //
    function AddLineNumbersCallback($a_matches)
    {
        global  $iAddLineNumbersCounter;
 
        return (sprintf("%d:",++$iAddLineNumbersCounter).$a_matches[0]);
    }
        //
        // Add line numbers to some code
        //
    function AddLineNumbers($s_code)
    {
        global  $iAddLineNumbersCounter;
 
        $iAddLineNumbersCounter = 0;
        return (preg_replace_callback('/^/m','AddLineNumbersCallback',$s_code));
    }
 
        //
        // Load some more code into FMCalc
        //
    function Load($s_code)
    {
        global  $FMCalc;
 
        $a_mesgs = array();
       // echo "Loading '$s_code'";
        if ($FMCalc->Parse($s_code,$a_mesgs) === false)
        {
            $s_msgs = "";
            foreach ($a_mesgs as $a_msg)
            {
                $s_msgs .= "Line ".$a_msg["LINE"];
                $s_msgs .= ", position ".$a_msg["CHAR"].": ";
                $s_msgs .= $a_msg["MSG"]."\n";
            }
            Error("fmcompute_parse",GetMessage(MSG_COMP_PARSE,
                        array("CODE"=>AddLineNumbers($s_code),
                                "ERRORS"=>$s_msgs)),false,false);
        }
    }
 
        //
        // Send any alerts found in FMCalc
        //
    function SendComputeAlerts()
    {
        global  $FMCalc;
 
        $a_alerts = $FMCalc->GetAlerts();
        if (count($a_alerts) > 0)
            SendAlert(GetMessage(MSG_COMP_ALERT,
                        array("ALERTS"=>implode("\n",$a_alerts))));
        $a_debug = $FMCalc->GetDebug();
        if (count($a_debug) > 0)
            SendAlert(GetMessage(MSG_COMP_DEBUG,
                        array("DEBUG"=>implode("\n",$a_debug))));
    }
        //
        // Perform the computations in FMCalc
        //
    function Compute(&$a_field_order,&$a_cleaned_values,&$a_raw_data_values,
                            &$a_values)
    {
        global  $FMCalc,$FM_UserErrors;
 
        $a_mesgs = array();
        $FM_UserErrors = array();
        if (($a_flds = $FMCalc->Execute($a_mesgs)) !== false)
        {
            SendComputeAlerts();
            foreach ($a_flds as $s_name=>$s_value)
            {
                $a_values[$s_name] = $s_value;
                ProcessField($s_name,$s_value,$a_field_order,
                                $a_cleaned_values,$a_raw_data_values);
            }
            if (count($FM_UserErrors) > 0)
                UserError("fmcompute_usererrors",GetMessage(MSG_USER_ERRORS),
                                "",$FM_UserErrors);
        }
        else
        {
            SendComputeAlerts();
            Error("fmcompute_exec",GetMessage(MSG_COMP_EXEC,
                        array("ERRORS"=>implode("\n",$a_mesgs))),false,false);
        }
    }
 
        //
        // Register all fields; a future improvement should use a call-back
        // function so as not to copy all the data into the FMCompute object
        //
    function RegisterData($a_form_data,$a_file_vars)
    {
        global  $FMCalc;
 
        foreach ($a_form_data as $s_name=>$s_value)
            if (isset($s_name) && isset($s_value))
                if (($s_msg = $FMCalc->RegisterExternalData("PHP","string",
                                                $s_name,"c",$s_value)) !== true)
                    Error("fmcompute_regdata",GetMessage(MSG_COMP_REG_DATA,
                                array("NAME"=>$s_name,"ERROR"=>$s_msg)),false,false);
 
        foreach ($a_file_vars as $s_fld_name=>$a_file_spec)
        {
            if (IsUploadedFile($a_file_spec))
                $s_value = $a_file_spec['name'];
            else
                $s_value = "";
            if (($s_msg = $FMCalc->RegisterExternalData("PHP","string",
                                            $s_fld_name,"c",$s_value)) !== true)
                Error("fmcompute_regdata",GetMessage(MSG_COMP_REG_DATA,
                            array("NAME"=>$s_fld_name,"ERROR"=>$s_msg)),false,false);
        }
    }
    RegisterData($aAllRawValues,$aFileVars);
        //
        // parse all fmcompute fields
        //
    if (is_array($SPECIAL_VALUES["fmcompute"]))
    {
        $nCompute = count($SPECIAL_VALUES["fmcompute"]);
        for ($iCompute = 0 ; $iCompute < $nCompute ; $iCompute++)
            Load($SPECIAL_VALUES["fmcompute"][$iCompute]);
    }
    else
        Load($SPECIAL_VALUES["fmcompute"]);
 
        //
        // run computations
        //
    Compute($aFieldOrder,$aCleanedValues,$aRawDataValues,$aAllRawValues);
        //
        // Hook system: after computations
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookcompute.inc");
}
 
$bGotGoBack = $bGotNextForm = $bGotGoodTemplate = $bGotGoodUrl = false;
if (isset($SPECIAL_VALUES["good_url"]) &&
    !empty($SPECIAL_VALUES["good_url"]))
    $bGotGoodUrl = true;
 
if (isset($SPECIAL_VALUES["good_template"]) &&
    !empty($SPECIAL_VALUES["good_template"]))
    $bGotGoodTemplate = true;
 
if (isset($SPECIAL_VALUES["next_form"]) &&
    !empty($SPECIAL_VALUES["next_form"]))
    $bGotNextForm = true;
 
if (isset($SPECIAL_VALUES["multi_go_back"]) &&
    !empty($SPECIAL_VALUES["multi_go_back"]))
    $bGotGoBack = true;
 
    //
    // it's not valid to specify "next_form" as well as "good_url" or
    // "good_template"; this is because it's ambiguous - do we go to the
    // next form or the final 'thank you' page?
    //
if ($bGotNextForm && ($bGotGoodTemplate || $bGotGoodUrl))
    ErrorWithIgnore("next_plus_good",GetMessage(MSG_NEXT_PLUS_GOOD,array("WHICH"=>
                                    ($bGotGoodUrl ? "good_url" :
                                    "good_template"))),false,false);
 
MultiFormLogic();
 
    //
    // Hook system: after multi-page form logic
    //
if ($HOOK_DIR !== "")
    @include("$HOOK_DIR/fmhookmulti.inc");
 
    //
    // write to the CSV database
    //
if (!empty($CSVDIR) && isset($SPECIAL_VALUES["csvfile"]) &&
                        !empty($SPECIAL_VALUES["csvfile"]))
{
        //
        // Hook system: before writing CSV file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookprecsv.inc");
    WriteCSVFile($CSVDIR."/".basename($SPECIAL_VALUES["csvfile"]),$aAllRawValues);
        //
        // Hook system: after writing CSV file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpostcsv.inc");
    $bDoneSomething = true;
}
 
    //
    // write to the log file
    //
if (!empty($LOGDIR) && isset($SPECIAL_VALUES["logfile"]) && !empty($SPECIAL_VALUES["logfile"]))
{
        //
        // Hook system: before writing log file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookprelog.inc");
    WriteLog($LOGDIR."/".basename($SPECIAL_VALUES["logfile"]));
        //
        // Hook system: after writing log file
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpostlog.inc");
    $bDoneSomething = true;
}
 
    //
    // send to the CRM
    //
if (isset($SPECIAL_VALUES["crm_url"]) && isset($SPECIAL_VALUES["crm_spec"]))
{
    $sCRM = GetCRMURL($SPECIAL_VALUES["crm_spec"],$aAllRawValues,$SPECIAL_VALUES["crm_url"]);
    if (!empty($sCRM))
    {
        $aCRMReturnData = array();
            //
            // Hook system: before sending to CRM
            //
        if ($HOOK_DIR !== "")
            @include("$HOOK_DIR/fmhookprecrm.inc");
        if (!SendToCRM($sCRM,$aCRMReturnData))
        {
                //
                // CRM interface failed, check if the form wants an error
                // displayed
                //
            if (IsCRMOptionSet("ErrorOnFail"))
                Error("crm_failed",GetMessage(MSG_CRM_FAILURE,
                                array("URL"=>$sCRM,
                                    "DATA"=>GetObjectAsString($aCRMReturnData))),
                                false,false);
        }
        else
                //
                // append the returned data to the raw data values of the form
                //
            $aRawDataValues = array_merge($aRawDataValues,$aCRMReturnData);
            //
            // Hook system: after sending to CRM
            //
        if ($HOOK_DIR !== "")
            @include("$HOOK_DIR/fmhookpostcrm.inc");
        $bDoneSomething = true;
    }
}
 
    //
    // Check obsolete SendMailFOption
    //
if (IsMailOptionSet("SendMailFOption"))
    SendAlert(GetMessage(MSG_FOPTION_WARN,array("LINE"=>SENDMAIL_F_OPTION_LINE)),
                false,true);
 
    //
    // send email
    //
if (!isset($SPECIAL_VALUES["recipients"]) || empty($SPECIAL_VALUES["recipients"]))
{
        //
        // No recipients - don't email anyone...
        // If nothing has been done above (CSV, logging, or CRM),
        // then report an error.
        //
    if (!$bDoneSomething)
        if (!$bGotGoBack && !$bGotNextForm)
            ErrorWithIgnore("no_recipients",GetMessage(MSG_NO_ACTIONS));
}
else
{
        //
        // Hook system: before sending emails
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpreemail.inc");
    $s_invalid = $s_invalid_cc = $s_invalid_bcc = "";
    if (!CheckEmailAddress($SPECIAL_VALUES["recipients"],$s_valid_recipients,$s_invalid))
        ErrorWithIgnore("no_valid_recipients",GetMessage(MSG_NO_RECIP));
    else
    {
        $s_valid_cc = $s_valid_bcc = "";
 
            //
            // check CC and BCC addresses
            //
        if (isset($SPECIAL_VALUES["cc"]) && !empty($SPECIAL_VALUES["cc"]))
            CheckEmailAddress($SPECIAL_VALUES["cc"],$s_valid_cc,$s_invalid_cc);
        if (isset($SPECIAL_VALUES["bcc"]) && !empty($SPECIAL_VALUES["bcc"]))
            CheckEmailAddress($SPECIAL_VALUES["bcc"],$s_valid_bcc,$s_invalid_bcc);
 
            //
            // send an alert for invalid addresses
            //
        $s_error = "";
        if (!empty($s_invalid))
            $s_error .= "recipients: $s_invalid\r\n";
        if (!empty($s_invalid_cc))
            $s_error .= "cc: $s_invalid_cc\r\n";
        if (!empty($s_invalid_bcc))
            $s_error .= "bcc: $s_invalid_bcc\r\n";
        if (!empty($s_error))
            SendAlert(GetMessage(MSG_INV_EMAIL,array("ERRORS"=>$s_error)));
 
            //
            // send the actual results
            //
        if (!SendResults($aFieldOrder,$aCleanedValues,$s_valid_recipients,$s_valid_cc,
                            $s_valid_bcc,$aRawDataValues))
            Error("mail_failed",GetMessage(MSG_FAILED_SEND));
            //
            // Hook system: after sending emails
            //
        if ($HOOK_DIR !== "")
            @include("$HOOK_DIR/fmhookpostemail.inc");
    }
}
 
    //
    // if the user didn't enter the verification code,
    // just skip the autoresponse
    //
if (isset($SPECIAL_VALUES["arverify"]) && !empty($SPECIAL_VALUES["arverify"]))
    if (IsAROptionSet('HTMLTemplate') || IsAROptionSet('PlainTemplate'))
    {
        if (!isset($SPECIAL_VALUES["email"]) || empty($SPECIAL_VALUES["email"]))
            SendAlert(GetMessage(MSG_ARESP_EMAIL));
        else
        {
                //
                // Hook system: before sending auto response
                //
            if ($HOOK_DIR !== "")
                @include("$HOOK_DIR/fmhookprearesp.inc");
            $sAutoRespTo = $SPECIAL_VALUES["email"];
            if (IsAROptionSet('Subject'))
                $sAutoRespSubj = GetAROption('Subject');
            else
                $sAutoRespSubj = GetMessage(MSG_ARESP_SUBJ,array(),false);
 
                //
                // VerifyImgString is from Tectite's simple verifyimg.php CAPTCHA
                // turing_string is from Captcha Creator
                //
            if (!isset($aSessionVars["VerifyImgString"]) &&
                !isset($aSessionVars["turing_string"]))
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                        GetMessage(MSG_LOG_NO_VERIMG,array(),false));
                ErrorWithIgnore("verify_failed",GetMessage(MSG_ARESP_NO_AUTH),true);
            }
            $bARImgMatch = false;
                //
                // the user's entry must match the value in the session; allow
                // spaces in the user's input
                //
            if (isset($aSessionVars["VerifyImgString"]))
            {
                if (str_replace(" ","",$SPECIAL_VALUES["arverify"]) ===
                            $aSessionVars["VerifyImgString"])
                    $bARImgMatch = true;
            }
            else
            {
                if (strtoupper(str_replace(" ","",$SPECIAL_VALUES["arverify"])) ===
                            strtoupper($aSessionVars["turing_string"]))
                    $bARImgMatch = true;
            }
            if (!$bARImgMatch)
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                            GetMessage(MSG_LOG_NO_MATCH,array(),false));
                UserError("ar_verify",GetMessage(MSG_ARESP_NO_MATCH));
            }
            elseif (!AutoRespond($sAutoRespTo,$sAutoRespSubj,$aRawDataValues))
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                            GetMessage(MSG_LOG_FAILED,array(),false));
                SendAlert(GetMessage(MSG_ARESP_FAILED));
            }
            else
            {
                WriteARLog($sAutoRespTo,$sAutoRespSubj,
                            GetMessage(MSG_LOG_OK,array(),false));
                    //
                    // Hook system: after sending auto response
                    //
                if ($HOOK_DIR !== "")
                    @include("$HOOK_DIR/fmhookpostaresp.inc");
            }
        }
    }
 
    //
    // multi-form processing
    //
if ($bGotNextForm)
{
    OutputMultiFormTemplate($SPECIAL_VALUES["next_form"],$aRawDataValues);
//    echo "Form index = ".$aSessionVars["FormIndex"];
}
else
{
        //
        // Hook system: before finishing
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookprefinish.inc");
        //
        // redirect to the good URL page, or create a default page;
        // we're no longer processing a multi-page form sequence
        //
    unset($aSessionVars["FormList"]);
    unset($aSessionVars["FormIndex"]);
    unset($aSessionVars["FormKeep"]);
    if (!$bGotGoodUrl)
    {
        if ($bGotGoodTemplate)
            OutputTemplate($SPECIAL_VALUES["good_template"],$aRawDataValues);
        else
            CreatePage(GetMessage(MSG_THANKS_PAGE));
    }
    else
        Redirect($SPECIAL_VALUES["good_url"]);
        //
        // Hook system: after finishing (before session is cleared)
        //
    if ($HOOK_DIR !== "")
        @include("$HOOK_DIR/fmhookpostfinish.inc");
        //
        // everything's good, so we don't need the session any more
        //
    ZapSession();
}
 
// --------------------------- INSERTION OF RECAPTCHA PART 3
 
// ending with this redirect
 
    if ($landing_page != ""){
      header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
    } else {
      header("Location: http://".$_SERVER["HTTP_HOST"]."/");
    }
  }
  else {
    # set the error code so that we can display it
    $error = $resp->error;
    $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=".$error;
    header("Location: ".$loc);
  }
}
else {
    $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=nocaptcha";
    header("Location: ".$loc);
}
 
// --------------------------- END OF INSERTION OF RECAPTCHA PART 3
 
?>
 
  <!-- notice the addition of the class="break" here to give it the extra space. -->
    </p>
 
 
 
  </div>
 
  <p class="clear">&nbsp;</p>
  </div>
 
<!-- This is the end of the template. -->
 
	</body>
</html>

                                              
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:
995:
996:
997:
998:
999:
1000:
1001:
1002:
1003:
1004:
1005:
1006:
1007:
1008:
1009:
1010:
1011:
1012:
1013:
1014:
1015:
1016:
1017:
1018:
1019:
1020:
1021:
1022:
1023:
1024:
1025:
1026:
1027:
1028:
1029:
1030:
1031:
1032:
1033:
1034:
1035:
1036:
1037:
1038:
1039:
1040:
1041:
1042:
1043:
1044:
1045:
1046:
1047:
1048:
1049:
1050:
1051:
1052:
1053:
1054:
1055:
1056:
1057:
1058:
1059:
1060:
1061:
1062:
1063:
1064:
1065:
1066:
1067:
1068:
1069:
1070:
1071:
1072:
1073:
1074:
1075:
1076:
1077:
1078:
1079:
1080:
1081:
1082:
1083:
1084:
1085:
1086:
1087:
1088:
1089:
1090:
1091:
1092:
1093:
1094:
1095:
1096:
1097:
1098:
1099:
1100:
1101:
1102:
1103:
1104:
1105:
1106:
1107:
1108:
1109:
1110:
1111:
1112:
1113:
1114:
1115:
1116:
1117:
1118:
1119:
1120:
1121:
1122:
1123:
1124:
1125:
1126:
1127:
1128:
1129:
1130:
1131:
1132:
1133:
1134:
1135:
1136:
1137:
1138:
1139:
1140:
1141:
1142:
1143:
1144:
1145:
1146:
1147:
1148:
1149:
1150:
1151:
1152:
1153:
1154:
1155:
1156:
1157:
1158:
1159:
1160:
1161:
1162:
1163:
1164:
1165:
1166:
1167:
1168:
1169:
1170:
1171:
1172:
1173:
1174:
1175:
1176:
1177:
1178:
1179:
1180:
1181:
1182:
1183:
1184:
1185:
1186:
1187:
1188:
1189:
1190:
1191:
1192:
1193:
1194:
1195:
1196:
1197:
1198:
1199:
1200:
1201:
1202:
1203:
1204:
1205:
1206:
1207:
1208:
1209:
1210:
1211:
1212:
1213:
1214:
1215:
1216:
1217:
1218:
1219:
1220:
1221:
1222:
1223:
1224:
1225:
1226:
1227:
1228:
1229:
1230:
1231:
1232:
1233:
1234:
1235:
1236:
1237:
1238:
1239:
1240:
1241:
1242:
1243:
1244:
1245:
1246:
1247:
1248:
1249:
1250:
1251:
1252:
1253:
1254:
1255:
1256:
1257:
1258:
1259:
1260:
1261:
1262:
1263:
1264:
1265:
1266:
1267:
1268:
1269:
1270:
1271:
1272:
1273:
1274:
1275:
1276:
1277:
1278:
1279:
1280:
1281:
1282:
1283:
1284:
1285:
1286:
1287:
1288:
1289:
1290:
1291:
1292:
1293:
1294:
1295:
1296:
1297:
1298:
1299:
1300:
1301:
1302:
1303:
1304:
1305:
1306:
1307:
1308:
1309:
1310:
1311:
1312:
1313:
1314:
1315:
1316:
1317:
1318:
1319:
1320:
1321:
1322:
1323:
1324:
1325:
1326:
1327:
1328:
1329:
1330:
1331:
1332:
1333:
1334:
1335:
1336:
1337:
1338:
1339:
1340:
1341:
1342:
1343:
1344:
1345:
1346:
1347:
1348:
1349:
1350:
1351:
1352:
1353:
1354:
1355:
1356:
1357:
1358:
1359:
1360:
1361:
1362:
1363:
1364:
1365:
1366:
1367:
1368:
1369:
1370:
1371:
1372:
1373:
1374:
1375:
1376:
1377:
1378:
1379:
1380:
1381:
1382:
1383:
1384:
1385:
1386:
1387:
1388:
1389:
1390:
1391:
1392:
1393:
1394:
1395:
1396:
1397:
1398:
1399:
1400:
1401:
1402:
1403:
1404:
1405:
1406:
1407:
1408:
1409:
1410:
1411:
1412:
1413:
1414:
1415:
1416:
1417:
1418:
1419:
1420:
1421:
1422:
1423:
1424:
1425:
1426:
1427:
1428:
1429:
1430:
1431:
1432:
1433:
1434:
1435:
1436:
1437:
1438:
1439:
1440:
1441:
1442:
1443:
1444:
1445:
1446:
1447:
1448:
1449:
1450:
1451:
1452:
1453:
1454:
1455:
1456:
1457:
1458:
1459:
1460:
1461:
1462:
1463:
1464:
1465:
1466:
1467:
1468:
1469:
1470:
1471:
1472:
1473:
1474:
1475:
1476:
1477:
1478:
1479:
1480:
1481:
1482:
1483:
1484:
1485:
1486:
1487:
1488:
1489:
1490:
1491:
1492:
1493:
1494:
1495:
1496:
1497:
1498:
1499:
1500:
1501:
1502:
1503:
1504:
1505:
1506:
1507:
1508:
1509:
1510:
1511:
1512:
1513:
1514:
1515:
1516:
1517:
1518:
1519:
1520:
1521:
1522:
1523:
1524:
1525:
1526:
1527:
1528:
1529:
1530:
1531:
1532:
1533:
1534:
1535:
1536:
1537:
1538:
1539:
1540:
1541:
1542:
1543:
1544:
1545:
1546:
1547:
1548:
1549:
1550:
1551:
1552:
1553:
1554:
1555:
1556:
1557:
1558:
1559:
1560:
1561:
1562:
1563:
1564:
1565:
1566:
1567:
1568:
1569:
1570:
1571:
1572:
1573:
1574:
1575:
1576:
1577:
1578:
1579:
1580:
1581:
1582:
1583:
1584:
1585:
1586:
1587:
1588:
1589:
1590:
1591:
1592:
1593:
1594:
1595:
1596:
1597:
1598:
1599:
1600:
1601:
1602:
1603:
1604:
1605:
1606:
1607:
1608:
1609:
1610:
1611:
1612:
1613:
1614:
1615:
1616:
1617:
1618:
1619:
1620:
1621:
1622:
1623:
1624:
1625:
1626:
1627:
1628:
1629:
1630:
1631:
1632:
1633:
1634:
1635:
1636:
1637:
1638:
1639:
1640:
1641:
1642:
1643:
1644:
1645:
1646:
1647:
1648:
1649:
1650:
1651:
1652:
1653:
1654:
1655:
1656:
1657:
1658:
1659:
1660:
1661:
1662:
1663:
1664:
1665:
1666:
1667:
1668:
1669:
1670:
1671:
1672:
1673:
1674:
1675:
1676:
1677:
1678:
1679:
1680:
1681:
1682:
1683:
1684:
1685:
1686:
1687:
1688:
1689:
1690:
1691:
1692:
1693:
1694:
1695:
1696:
1697:
1698:
1699:
1700:
1701:
1702:
1703:
1704:
1705:
1706:
1707:
1708:
1709:
1710:
1711:
1712:
1713:
1714:
1715:
1716:
1717:
1718:
1719:
1720:
1721:
1722:
1723:
1724:
1725:
1726:
1727:
1728:
1729:
1730:
1731:
1732:
1733:
1734:
1735:
1736:
1737:
1738:
1739:
1740:
1741:
1742:
1743:
1744:
1745:
1746:
1747:
1748:
1749:
1750:
1751:
1752:
1753:
1754:
1755:
1756:
1757:
1758:
1759:
1760:
1761:
1762:
1763:
1764:
1765:
1766:
1767:
1768:
1769:
1770:
1771:
1772:
1773:
1774:
1775:
1776:
1777:
1778:
1779:
1780:
1781:
1782:
1783:
1784:
1785:
1786:
1787:
1788:
1789:
1790:
1791:
1792:
1793:
1794:
1795:
1796:
1797:
1798:
1799:
1800:
1801:
1802:
1803:
1804:
1805:
1806:
1807:
1808:
1809:
1810:
1811:
1812:
1813:
1814:
1815:
1816:
1817:
1818:
1819:
1820:
1821:
1822:
1823:
1824:
1825:
1826:
1827:
1828:
1829:
1830:
1831:
1832:
1833:
1834:
1835:
1836:
1837:
1838:
1839:
1840:
1841:
1842:
1843:
1844:
1845:
1846:
1847:
1848:
1849:
1850:
1851:
1852:
1853:
1854:
1855:
1856:
1857:
1858:
1859:
1860:
1861:
1862:
1863:
1864:
1865:
1866:
1867:
1868:
1869:
1870:
1871:
1872:
1873:
1874:
1875:
1876:
1877:
1878:
1879:
1880:
1881:
1882:
1883:
1884:
1885:
1886:
1887:
1888:
1889:
1890:
1891:
1892:
1893:
1894:
1895:
1896:
1897:
1898:
1899:
1900:
1901:
1902:
1903:
1904:
1905:
1906:
1907:
1908:
1909:
1910:
1911:
1912:
1913:
1914:
1915:
1916:
1917:
1918:
1919:
1920:
1921:
1922:
1923:
1924:
1925:
1926:
1927:
1928:
1929:
1930:
1931:
1932:
1933:
1934:
1935:
1936:
1937:
1938:
1939:
1940:
1941:
1942:
1943:
1944:
1945:
1946:
1947:
1948:
1949:
1950:
1951:
1952:
1953:
1954:
1955:
1956:
1957:
1958:
1959:
1960:
1961:
1962:
1963:
1964:
1965:
1966:
1967:
1968:
1969:
1970:
1971:
1972:
1973:
1974:
1975:
1976:
1977:
1978:
1979:
1980:
1981:
1982:
1983:
1984:
1985:
1986:
1987:
1988:
1989:
1990:
1991:
1992:
1993:
1994:
1995:
1996:
1997:
1998:
1999:
2000:
2001:
2002:
2003:
2004:
2005:
2006:
2007:
2008:
2009:
2010:
2011:
2012:
2013:
2014:
2015:
2016:
2017:
2018:
2019:
2020:
2021:
2022:
2023:
2024:
2025:
2026:
2027:
2028:
2029:
2030:
2031:
2032:
2033:
2034:
2035:
2036:
2037:
2038:
2039:
2040:
2041:
2042:
2043:
2044:
2045:
2046:
2047:
2048:
2049:
2050:
2051:
2052:
2053:
2054:
2055:
2056:
2057:
2058:
2059:
2060:
2061:
2062:
2063:
2064:
2065:
2066:
2067:
2068:
2069:
2070:
2071:
2072:
2073:
2074:
2075:
2076:
2077:
2078:
2079:
2080:
2081:
2082:
2083:
2084:
2085:
2086:
2087:
2088:
2089:
2090:
2091:
2092:
2093:
2094:
2095:
2096:
2097:
2098:
2099:
2100:
2101:
2102:
2103:
2104:
2105:
2106:
2107:
2108:
2109:
2110:
2111:
2112:
2113:
2114:
2115:
2116:
2117:
2118:
2119:
2120:
2121:
2122:
2123:
2124:
2125:
2126:
2127:
2128:
2129:
2130:
2131:
2132:
2133:
2134:
2135:
2136:
2137:
2138:
2139:
2140:
2141:
2142:
2143:
2144:
2145:
2146:
2147:
2148:
2149:
2150:
2151:
2152:
2153:
2154:
2155:
2156:
2157:
2158:
2159:
2160:
2161:
2162:
2163:
2164:
2165:
2166:
2167:
2168:
2169:
2170:
2171:
2172:
2173:
2174:
2175:
2176:
2177:
2178:
2179:
2180:
2181:
2182:
2183:
2184:
2185:
2186:
2187:
2188:
2189:
2190:
2191:
2192:
2193:
2194:
2195:
2196:
2197:
2198:
2199:
2200:
2201:
2202:
2203:
2204:
2205:
2206:
2207:
2208:
2209:
2210:
2211:
2212:
2213:
2214:
2215:
2216:
2217:
2218:
2219:
2220:
2221:
2222:
2223:
2224:
2225:
2226:
2227:
2228:
2229:
2230:
2231:
2232:
2233:
2234:
2235:
2236:
2237:
2238:
2239:
2240:
2241:
2242:
2243:
2244:
2245:
2246:
2247:
2248:
2249:
2250:
2251:
2252:
2253:
2254:
2255:
2256:
2257:
2258:
2259:
2260:
2261:
2262:
2263:
2264:
2265:
2266:
2267:
2268:
2269:
2270:
2271:
2272:
2273:
2274:
2275:
2276:
2277:
2278:
2279:
2280:
2281:
2282:
2283:
2284:
2285:
2286:
2287:
2288:
2289:
2290:
2291:
2292:
2293:
2294:
2295:
2296:
2297:
2298:
2299:
2300:
2301:
2302:
2303:
2304:
2305:
2306:
2307:
2308:
2309:
2310:
2311:
2312:
2313:
2314:
2315:
2316:
2317:
2318:
2319:
2320:
2321:
2322:
2323:
2324:
2325:
2326:
2327:
2328:
2329:
2330:
2331:
2332:
2333:
2334:
2335:
2336:
2337:
2338:
2339:
2340:
2341:
2342:
2343:
2344:
2345:
2346:
2347:
2348:
2349:
2350:
2351:
2352:
2353:
2354:
2355:
2356:
2357:
2358:
2359:
2360:
2361:
2362:
2363:
2364:
2365:
2366:
2367:
2368:
2369:
2370:
2371:
2372:
2373:
2374:
2375:
2376:
2377:
2378:
2379:
2380:
2381:
2382:
2383:
2384:
2385:
2386:
2387:
2388:
2389:
2390:
2391:
2392:
2393:
2394:
2395:
2396:
2397:
2398:
2399:
2400:
2401:
2402:
2403:
2404:
2405:
2406:
2407:
2408:
2409:
2410:
2411:
2412:
2413:
2414:
2415:
2416:
2417:
2418:
2419:
2420:
2421:
2422:
2423:
2424:
2425:
2426:
2427:
2428:
2429:
2430:
2431:
2432:
2433:
2434:
2435:
2436:
2437:
2438:
2439:
2440:
2441:
2442:
2443:
2444:
2445:
2446:
2447:
2448:
2449:
2450:
2451:
2452:
2453:
2454:
2455:
2456:
2457:
2458:
2459:
2460:
2461:
2462:
2463:
2464:
2465:
2466:
2467:
2468:
2469:
2470:
2471:
2472:
2473:
2474:
2475:
2476:
2477:
2478:
2479:
2480:
2481:
2482:
2483:
2484:
2485:
2486:
2487:
2488:
2489:
2490:
2491:
2492:
2493:
2494:
2495:
2496:
2497:
2498:
2499:
2500:
2501:
2502:
2503:
2504:
2505:
2506:
2507:
2508:
2509:
2510:
2511:
2512:
2513:
2514:
2515:
2516:
2517:
2518:
2519:
2520:
2521:
2522:
2523:
2524:
2525:
2526:
2527:
2528:
2529:
2530:
2531:
2532:
2533:
2534:
2535:
2536:
2537:
2538:
2539:
2540:
2541:
2542:
2543:
2544:
2545:
2546:
2547:
2548:
2549:
2550:
2551:
2552:
2553:
2554:
2555:
2556:
2557:
2558:
2559:
2560:
2561:
2562:
2563:
2564:
2565:
2566:
2567:
2568:
2569:
2570:
2571:
2572:
2573:
2574:
2575:
2576:
2577:
2578:
2579:
2580:
2581:
2582:
2583:
2584:
2585:
2586:
2587:
2588:
2589:
2590:
2591:
2592:
2593:
2594:
2595:
2596:
2597:
2598:
2599:
2600:
2601:
2602:
2603:
2604:
2605:
2606:
2607:
2608:
2609:
2610:
2611:
2612:
2613:
2614:
2615:
2616:
2617:
2618:
2619:
2620:
2621:
2622:
2623:
2624:
2625:
2626:
2627:
2628:
2629:
2630:
2631:
2632:
2633:
2634:
2635:
2636:
2637:
2638:
2639:
2640:
2641:
2642:
2643:
2644:
2645:
2646:
2647:
2648:
2649:
2650:
2651:
2652:
2653:
2654:
2655:
2656:
2657:
2658:
2659:
2660:
2661:
2662:
2663:
2664:
2665:
2666:
2667:
2668:
2669:
2670:
2671:
2672:
2673:
2674:
2675:
2676:
2677:
2678:
2679:
2680:
2681:
2682:
2683:
2684:
2685:
2686:
2687:
2688:
2689:
2690:
2691:
2692:
2693:
2694:
2695:
2696:
2697:
2698:
2699:
2700:
2701:
2702:
2703:
2704:
2705:
2706:
2707:
2708:
2709:
2710:
2711:
2712:
2713:
2714:
2715:
2716:
2717:
2718:
2719:
2720:
2721:
2722:
2723:
2724:
2725:
2726:
2727:
2728:
2729:
2730:
2731:
2732:
2733:
2734:
2735:
2736:
2737:
2738:
2739:
2740:
2741:
2742:
2743:
2744:
2745:
2746:
2747:
2748:
2749:
2750:
2751:
2752:
2753:
2754:
2755:
2756:
2757:
2758:
2759:
2760:
2761:
2762:
2763:
2764:
2765:
2766:
2767:
2768:
2769:
2770:
2771:
2772:
2773:
2774:
2775:
2776:
2777:
2778:
2779:
2780:
2781:
2782:
2783:
2784:
2785:
2786:
2787:
2788:
2789:
2790:
2791:
2792:
2793:
2794:
2795:
2796:
2797:
2798:
2799:
2800:
2801:
2802:
2803:
2804:
2805:
2806:
2807:
2808:
2809:
2810:
2811:
2812:
2813:
2814:
2815:
2816:
2817:
2818:
2819:
2820:
2821:
2822:
2823:
2824:
2825:
2826:
2827:
2828:
2829:
2830:
2831:
2832:
2833:
2834:
2835:
2836:
2837:
2838:
2839:
2840:
2841:
2842:
2843:
2844:
2845:
2846:
2847:
2848:
2849:
2850:
2851:
2852:
2853:
2854:
2855:
2856:
2857:
2858:
2859:
2860:
2861:
2862:
2863:
2864:
2865:
2866:
2867:
2868:
2869:
2870:
2871:
2872:
2873:
2874:
2875:
2876:
2877:
2878:
2879:
2880:
2881:
2882:
2883:
2884:
2885:
2886:
2887:
2888:
2889:
2890:
2891:
2892:
2893:
2894:
2895:
2896:
2897:
2898:
2899:
2900:
2901:
2902:
2903:
2904:
2905:
2906:
2907:
2908:
2909:
2910:
2911:
2912:
2913:
2914:
2915:
2916:
2917:
2918:
2919:
2920:
2921:
2922:
2923:
2924:
2925:
2926:
2927:
2928:
2929:
2930:
2931:
2932:
2933:
2934:
2935:
2936:
2937:
2938:
2939:
2940:
2941:
2942:
2943:
2944:
2945:
2946:
2947:
2948:
2949:
2950:
2951:
2952:
2953:
2954:
2955:
2956:
2957:
2958:
2959:
2960:
2961:
2962:
2963:
2964:
2965:
2966:
2967:
2968:
2969:
2970:
2971:
2972:
2973:
2974:
2975:
2976:
2977:
2978:
2979:
2980:
2981:
2982:
2983:
2984:
2985:
2986:
2987:
2988:
2989:
2990:
2991:
2992:
2993:
2994:
2995:
2996:
2997:
2998:
2999:
3000:
3001:
3002:
3003:
3004:
3005:
3006:
3007:
3008:
3009:
3010:
3011:
3012:
3013:
3014:
3015:
3016:
3017:
3018:
3019:
3020:
3021:
3022:
3023:
3024:
3025:
3026:
3027:
3028:
3029:
3030:
3031:
3032:
3033:
3034:
3035:
3036:
3037:
3038:
3039:
3040:
3041:
3042:
3043:
3044:
3045:
3046:
3047:
3048:
3049:
3050:
3051:
3052:
3053:
3054:
3055:
3056:
3057:
3058:
3059:
3060:
3061:
3062:
3063:
3064:
3065:
3066:
3067:
3068:
3069:
3070:
3071:
3072:
3073:
3074:
3075:
3076:
3077:
3078:
3079:
3080:
3081:
3082:
3083:
3084:
3085:
3086:
3087:
3088:
3089:
3090:
3091:
3092:
3093:
3094:
3095:
3096:
3097:
3098:
3099:
3100:
3101:
3102:
3103:
3104:
3105:
3106:
3107:
3108:
3109:
3110:
3111:
3112:
3113:
3114:
3115:
3116:
3117:
3118:
3119:
3120:
3121:
3122:
3123:
3124:
3125:
3126:
3127:
3128:
3129:
3130:
3131:
3132:
3133:
3134:
3135:
3136:
3137:
3138:
3139:
3140:
3141:
3142:
3143:
3144:
3145:
3146:
3147:
3148:
3149:
3150:
3151:
3152:
3153:
3154:
3155:
3156:
3157:
3158:
3159:
3160:
3161:
3162:
3163:
3164:
3165:
3166:
3167:
3168:
3169:
3170:
3171:
3172:
3173:
3174:
3175:
3176:
3177:
3178:
3179:
3180:
3181:
3182:
3183:
3184:
3185:
3186:
3187:
3188:
3189:
3190:
3191:
3192:
3193:
3194:
3195:
3196:
3197:
3198:
3199:
3200:
3201:
3202:
3203:
3204:
3205:
3206:
3207:
3208:
3209:
3210:
3211:
3212:
3213:
3214:
3215:
3216:
3217:
3218:
3219:
3220:
3221:
3222:
3223:
3224:
3225:
3226:
3227:
3228:
3229:
3230:
3231:
3232:
3233:
3234:
3235:
3236:
3237:
3238:
3239:
3240:
3241:
3242:
3243:
3244:
3245:
3246:
3247:
3248:
3249:
3250:
3251:
3252:
3253:
3254:
3255:
3256:
3257:
3258:
3259:
3260:
3261:
3262:
3263:
3264:
3265:
3266:
3267:
3268:
3269:
3270:
3271:
3272:
3273:
3274:
3275:
3276:
3277:
3278:
3279:
3280:
3281:
3282:
3283:
3284:
3285:
3286:
3287:
3288:
3289:
3290:
3291:
3292:
3293:
3294:
3295:
3296:
3297:
3298:
3299:
3300:
3301:
3302:
3303:
3304:
3305:
3306:
3307:
3308:
3309:
3310:
3311:
3312:
3313:
3314:
3315:
3316:
3317:
3318:
3319:
3320:
3321:
3322:
3323:
3324:
3325:
3326:
3327:
3328:
3329:
3330:
3331:
3332:
3333:
3334:
3335:
3336:
3337:
3338:
3339:
3340:
3341:
3342:
3343:
3344:
3345:
3346:
3347:
3348:
3349:
3350:
3351:
3352:
3353:
3354:
3355:
3356:
3357:
3358:
3359:
3360:
3361:
3362:
3363:
3364:
3365:
3366:
3367:
3368:
3369:
3370:
3371:
3372:
3373:
3374:
3375:
3376:
3377:
3378:
3379:
3380:
3381:
3382:
3383:
3384:
3385:
3386:
3387:
3388:
3389:
3390:
3391:
3392:
3393:
3394:
3395:
3396:
3397:
3398:
3399:
3400:
3401:
3402:
3403:
3404:
3405:
3406:
3407:
3408:
3409:
3410:
3411:
3412:
3413:
3414:
3415:
3416:
3417:
3418:
3419:
3420:
3421:
3422:
3423:
3424:
3425:
3426:
3427:
3428:
3429:
3430:
3431:
3432:
3433:
3434:
3435:
3436:
3437:
3438:
3439:
3440:
3441:
3442:
3443:
3444:
3445:
3446:
3447:
3448:
3449:
3450:
3451:
3452:
3453:
3454:
3455:
3456:
3457:
3458:
3459:
3460:
3461:
3462:
3463:
3464:
3465:
3466:
3467:
3468:
3469:
3470:
3471:
3472:
3473:
3474:
3475:
3476:
3477:
3478:
3479:
3480:
3481:
3482:
3483:
3484:
3485:
3486:
3487:
3488:
3489:
3490:
3491:
3492:
3493:
3494:
3495:
3496:
3497:
3498:
3499:
3500:
3501:
3502:
3503:
3504:
3505:
3506:
3507:
3508:
3509:
3510:
3511:
3512:
3513:
3514:
3515:
3516:
3517:
3518:
3519:
3520:
3521:
3522:
3523:
3524:
3525:
3526:
3527:
3528:
3529:
3530:
3531:
3532:
3533:
3534:
3535:
3536:
3537:
3538:
3539:
3540:
3541:
3542:
3543:
3544:
3545:
3546:
3547:
3548:
3549:
3550:
3551:
3552:
3553:
3554:
3555:
3556:
3557:
3558:
3559:
3560:
3561:
3562:
3563:
3564:
3565:
3566:
3567:
3568:
3569:
3570:
3571:
3572:
3573:
3574:
3575:
3576:
3577:
3578:
3579:
3580:
3581:
3582:
3583:
3584:
3585:
3586:
3587:
3588:
3589:
3590:
3591:
3592:
3593:
3594:
3595:
3596:
3597:
3598:
3599:
3600:
3601:
3602:
3603:
3604:
3605:
3606:
3607:
3608:
3609:
3610:
3611:
3612:
3613:
3614:
3615:
3616:
3617:
3618:
3619:
3620:
3621:
3622:
3623:
3624:
3625:
3626:
3627:
3628:
3629:
3630:
3631:
3632:
3633:
3634:
3635:
3636:
3637:
3638:
3639:
3640:
3641:
3642:
3643:
3644:
3645:
3646:
3647:
3648:
3649:
3650:
3651:
3652:
3653:
3654:
3655:
3656:
3657:
3658:
3659:
3660:
3661:
3662:
3663:
3664:
3665:
3666:
3667:
3668:
3669:
3670:
3671:
3672:
3673:
3674:
3675:
3676:
3677:
3678:
3679:
3680:
3681:
3682:
3683:
3684:
3685:
3686:
3687:
3688:
3689:
3690:
3691:
3692:
3693:
3694:
3695:
3696:
3697:
3698:
3699:
3700:
3701:
3702:
3703:
3704:
3705:
3706:
3707:
3708:
3709:
3710:
3711:
3712:
3713:
3714:
3715:
3716:
3717:
3718:
3719:
3720:
3721:
3722:
3723:
3724:
3725:
3726:
3727:
3728:
3729:
3730:
3731:
3732:
3733:
3734:
3735:
3736:
3737:
3738:
3739:
3740:
3741:
3742:
3743:
3744:
3745:
3746:
3747:
3748:
3749:
3750:
3751:
3752:
3753:
3754:
3755:
3756:
3757:
3758:
3759:
3760:
3761:
3762:
3763:
3764:
3765:
3766:
3767:
3768:
3769:
3770:
3771:
3772:
3773:
3774:
3775:
3776:
3777:
3778:
3779:
3780:
3781:
3782:
3783:
3784:
3785:
3786:
3787:
3788:
3789:
3790:
3791:
3792:
3793:
3794:
3795:
3796:
3797:
3798:
3799:
3800:
3801:
3802:
3803:
3804:
3805:
3806:
3807:
3808:
3809:
3810:
3811:
3812:
3813:
3814:
3815:
3816:
3817:
3818:
3819:
3820:
3821:
3822:
3823:
3824:
3825:
3826:
3827:
3828:
3829:
3830:
3831:
3832:
3833:
3834:
3835:
3836:
3837:
3838:
3839:
3840:
3841:
3842:
3843:
3844:
3845:
3846:
3847:
3848:
3849:
3850:
3851:
3852:
3853:
3854:
3855:
3856:
3857:
3858:
3859:
3860:
3861:
3862:
3863:
3864:
3865:
3866:
3867:
3868:
3869:
3870:
3871:
3872:
3873:
3874:
3875:
3876:
3877:
3878:
3879:
3880:
3881:
3882:
3883:
3884:
3885:
3886:
3887:
3888:
3889:
3890:
3891:
3892:
3893:
3894:
3895:
3896:
3897:
3898:
3899:
3900:
3901:
3902:
3903:
3904:
3905:
3906:
3907:
3908:
3909:
3910:
3911:
3912:
3913:
3914:
3915:
3916:
3917:
3918:
3919:
3920:
3921:
3922:
3923:
3924:
3925:
3926:
3927:
3928:
3929:
3930:
3931:
3932:
3933:
3934:
3935:
3936:
3937:
3938:
3939:
3940:
3941:
3942:
3943:
3944:
3945:
3946:
3947:
3948:
3949:
3950:
3951:
3952:
3953:
3954:
3955:
3956:
3957:
3958:
3959:
3960:
3961:
3962:
3963:
3964:
3965:
3966:
3967:
3968:
3969:
3970:
3971:
3972:
3973:
3974:
3975:
3976:
3977:
3978:
3979:
3980:
3981:
3982:
3983:
3984:
3985:
3986:
3987:
3988:
3989:
3990:
3991:
3992:
3993:
3994:
3995:
3996:
3997:
3998:
3999:
4000:
4001:
4002:
4003:
4004:
4005:
4006:
4007:
4008:
4009:
4010:
4011:
4012:
4013:
4014:
4015:
4016:
4017:
4018:
4019:
4020:
4021:
4022:
4023:
4024:
4025:
4026:
4027:
4028:
4029:
4030:
4031:
4032:
4033:
4034:
4035:
4036:
4037:
4038:
4039:
4040:
4041:
4042:
4043:
4044:
4045:
4046:
4047:
4048:
4049:
4050:
4051:
4052:
4053:
4054:
4055:
4056:
4057:
4058:
4059:
4060:
4061:
4062:
4063:
4064:
4065:
4066:
4067:
4068:
4069:
4070:
4071:
4072:
4073:
4074:
4075:
4076:
4077:
4078:
4079:
4080:
4081:
4082:
4083:
4084:
4085:
4086:
4087:
4088:
4089:
4090:
4091:
4092:
4093:
4094:
4095:
4096:
4097:
4098:
4099:
4100:
4101:
4102:
4103:
4104:
4105:
4106:
4107:
4108:
4109:
4110:
4111:
4112:
4113:
4114:
4115:
4116:
4117:
4118:
4119:
4120:
4121:
4122:
4123:
4124:
4125:
4126:
4127:
4128:
4129:
4130:
4131:
4132:
4133:
4134:
4135:
4136:
4137:
4138:
4139:
4140:
4141:
4142:
4143:
4144:
4145:
4146:
4147:
4148:
4149:
4150:
4151:
4152:
4153:
4154:
4155:
4156:
4157:
4158:
4159:
4160:
4161:
4162:
4163:
4164:
4165:
4166:
4167:
4168:
4169:
4170:
4171:
4172:
4173:
4174:
4175:
4176:
4177:
4178:
4179:
4180:
4181:
4182:
4183:
4184:
4185:
4186:
4187:
4188:
4189:
4190:
4191:
4192:
4193:
4194:
4195:
4196:
4197:
4198:
4199:
4200:
4201:
4202:
4203:
4204:
4205:
4206:
4207:
4208:
4209:
4210:
4211:
4212:
4213:
4214:
4215:
4216:
4217:
4218:
4219:
4220:
4221:
4222:
4223:
4224:
4225:
4226:
4227:
4228:
4229:
4230:
4231:
4232:
4233:
4234:
4235:
4236:
4237:
4238:
4239:
4240:
4241:
4242:
4243:
4244:
4245:
4246:
4247:
4248:
4249:
4250:
4251:
4252:
4253:
4254:
4255:
4256:
4257:
4258:
4259:
4260:
4261:
4262:
4263:
4264:
4265:
4266:
4267:
4268:
4269:
4270:
4271:
4272:
4273:
4274:
4275:
4276:
4277:
4278:
4279:
4280:
4281:
4282:
4283:
4284:
4285:
4286:
4287:
4288:
4289:
4290:
4291:
4292:
4293:
4294:
4295:
4296:
4297:
4298:
4299:
4300:
4301:
4302:
4303:
4304:
4305:
4306:
4307:
4308:
4309:
4310:
4311:
4312:
4313:
4314:
4315:
4316:
4317:
4318:
4319:
4320:
4321:
4322:
4323:
4324:
4325:
4326:
4327:
4328:
4329:
4330:
4331:
4332:
4333:
4334:
4335:
4336:
4337:
4338:
4339:
4340:
4341:
4342:
4343:
4344:
4345:
4346:
4347:
4348:
4349:
4350:
4351:
4352:
4353:
4354:
4355:
4356:
4357:
4358:
4359:
4360:
4361:
4362:
4363:
4364:
4365:
4366:
4367:
4368:
4369:
4370:
4371:
4372:
4373:
4374:
4375:
4376:
4377:
4378:
4379:
4380:
4381:
4382:
4383:
4384:
4385:
4386:
4387:
4388:
4389:
4390:
4391:
4392:
4393:
4394:
4395:
4396:
4397:
4398:
4399:
4400:
4401:
4402:
4403:
4404:
4405:
4406:
4407:
4408:
4409:
4410:
4411:
4412:
4413:
4414:
4415:
4416:
4417:
4418:
4419:
4420:
4421:
4422:
4423:
4424:
4425:
4426:
4427:
4428:
4429:
4430:
4431:
4432:
4433:
4434:
4435:
4436:
4437:
4438:
4439:
4440:
4441:
4442:
4443:
4444:
4445:
4446:
4447:
4448:
4449:
4450:
4451:
4452:
4453:
4454:
4455:
4456:
4457:
4458:
4459:
4460:
4461:
4462:
4463:
4464:
4465:
4466:
4467:
4468:
4469:
4470:
4471:
4472:
4473:
4474:
4475:
4476:
4477:
4478:
4479:
4480:
4481:
4482:
4483:
4484:
4485:
4486:
4487:
4488:
4489:
4490:
4491:
4492:
4493:
4494:
4495:
4496:
4497:
4498:
4499:
4500:
4501:
4502:
4503:
4504:
4505:
4506:
4507:
4508:
4509:
4510:
4511:
4512:
4513:
4514:
4515:
4516:
4517:
4518:
4519:
4520:
4521:
4522:
4523:
4524:
4525:
4526:
4527:
4528:
4529:
4530:
4531:
4532:
4533:
4534:
4535:
4536:
4537:
4538:
4539:
4540:
4541:
4542:
4543:
4544:
4545:
4546:
4547:
4548:
4549:
4550:
4551:
4552:
4553:
4554:
4555:
4556:
4557:
4558:
4559:
4560:
4561:
4562:
4563:
4564:
4565:
4566:
4567:
4568:
4569:
4570:
4571:
4572:
4573:
4574:
4575:
4576:
4577:
4578:
4579:
4580:
4581:
4582:
4583:
4584:
4585:
4586:
4587:
4588:
4589:
4590:
4591:
4592:
4593:
4594:
4595:
4596:
4597:
4598:
4599:
4600:
4601:
4602:
4603:
4604:
4605:
4606:
4607:
4608:
4609:
4610:
4611:
4612:
4613:
4614:
4615:
4616:
4617:
4618:
4619:
4620:
4621:
4622:
4623:
4624:
4625:
4626:
4627:
4628:
4629:
4630:
4631:
4632:
4633:
4634:
4635:
4636:
4637:
4638:
4639:
4640:
4641:
4642:
4643:
4644:
4645:
4646:
4647:
4648:
4649:
4650:
4651:
4652:
4653:
4654:
4655:
4656:
4657:
4658:
4659:
4660:
4661:
4662:
4663:
4664:
4665:
4666:
4667:
4668:
4669:
4670:
4671:
4672:
4673:
4674:
4675:
4676:
4677:
4678:
4679:
4680:
4681:
4682:
4683:
4684:
4685:
4686:
4687:
4688:
4689:
4690:
4691:
4692:
4693:
4694:
4695:
4696:
4697:
4698:
4699:
4700:
4701:
4702:
4703:
4704:
4705:
4706:
4707:
4708:
4709:
4710:
4711:
4712:
4713:
4714:
4715:
4716:
4717:
4718:
4719:
4720:
4721:
4722:
4723:
4724:
4725:
4726:
4727:
4728:
4729:
4730:
4731:
4732:
4733:
4734:
4735:
4736:
4737:
4738:
4739:
4740:
4741:
4742:
4743:
4744:
4745:
4746:
4747:
4748:
4749:
4750:
4751:
4752:
4753:
4754:
4755:
4756:
4757:
4758:
4759:
4760:
4761:
4762:
4763:
4764:
4765:
4766:
4767:
4768:
4769:
4770:
4771:
4772:
4773:
4774:
4775:
4776:
4777:
4778:
4779:
4780:
4781:
4782:
4783:
4784:
4785:
4786:
4787:
4788:
4789:
4790:
4791:
4792:
4793:
4794:
4795:
4796:
4797:
4798:
4799:
4800:
4801:
4802:
4803:
4804:
4805:
4806:
4807:
4808:
4809:
4810:
4811:
4812:
4813:
4814:
4815:
4816:
4817:
4818:
4819:
4820:
4821:
4822:
4823:
4824:
4825:
4826:
4827:
4828:
4829:
4830:
4831:
4832:
4833:
4834:
4835:
4836:
4837:
4838:
4839:
4840:
4841:
4842:
4843:
4844:
4845:
4846:
4847:
4848:
4849:
4850:
4851:
4852:
4853:
4854:
4855:
4856:
4857:
4858:
4859:
4860:
4861:
4862:
4863:
4864:
4865:
4866:
4867:
4868:
4869:
4870:
4871:
4872:
4873:
4874:
4875:
4876:
4877:
4878:
4879:
4880:
4881:
4882:
4883:
4884:
4885:
4886:
4887:
4888:
4889:
4890:
4891:
4892:
4893:
4894:
4895:
4896:
4897:
4898:
4899:
4900:
4901:
4902:
4903:
4904:
4905:
4906:
4907:
4908:
4909:
4910:
4911:
4912:
4913:
4914:
4915:
4916:
4917:
4918:
4919:
4920:
4921:
4922:
4923:
4924:
4925:
4926:
4927:
4928:
4929:
4930:
4931:
4932:
4933:
4934:
4935:
4936:
4937:
4938:
4939:
4940:
4941:
4942:
4943:
4944:
4945:
4946:
4947:
4948:
4949:
4950:
4951:
4952:
4953:
4954:
4955:
4956:
4957:
4958:
4959:
4960:
4961:
4962:
4963:
4964:
4965:
4966:
4967:
4968:
4969:
4970:
4971:
4972:
4973:
4974:
4975:
4976:
4977:
4978:
4979:
4980:
4981:
4982:
4983:
4984:
4985:
4986:
4987:
4988:
4989:
4990:
4991:
4992:
4993:
4994:
4995:
4996:
4997:
4998:
4999:
5000:
5001:
5002:
5003:
5004:
5005:
5006:
5007:
5008:
5009:
5010:
5011:
5012:
5013:
5014:
5015:
5016:
5017:
5018:
5019:
5020:
5021:
5022:
5023:
5024:
5025:
5026:
5027:
5028:
5029:
5030:
5031:
5032:
5033:
5034:
5035:
5036:
5037:
5038:
5039:
5040:
5041:
5042:
5043:
5044:
5045:
5046:
5047:
5048:
5049:
5050:
5051:
5052:
5053:
5054:
5055:
5056:
5057:
5058:
5059:
5060:
5061:
5062:
5063:
5064:
5065:
5066:
5067:
5068:
5069:
5070:
5071:
5072:
5073:
5074:
5075:
5076:
5077:
5078:
5079:
5080:
5081:
5082:
5083:
5084:
5085:
5086:
5087:
5088:
5089:
5090:
5091:
5092:
5093:
5094:
5095:
5096:
5097:
5098:
5099:
5100:
5101:
5102:
5103:
5104:
5105:
5106:
5107:
5108:
5109:
5110:
5111:
5112:
5113:
5114:
5115:
5116:
5117:
5118:
5119:
5120:
5121:
5122:
5123:
5124:
5125:
5126:
5127:
5128:
5129:
5130:
5131:
5132:
5133:
5134:
5135:
5136:
5137:
5138:
5139:
5140:
5141:
5142:
5143:
5144:
5145:
5146:
5147:
5148:
5149:
5150:
5151:
5152:
5153:
5154:
5155:
5156:
5157:
5158:
5159:
5160:
5161:
5162:
5163:
5164:
5165:
5166:
5167:
5168:
5169:
5170:
5171:
5172:
5173:
5174:
5175:
5176:
5177:
5178:
5179:
5180:
5181:
5182:
5183:
5184:
5185:
5186:
5187:
5188:
5189:
5190:
5191:
5192:
5193:
5194:
5195:
5196:
5197:
5198:
5199:
5200:
5201:
5202:
5203:
5204:
5205:
5206:
5207:
5208:
5209:
5210:
5211:
5212:
5213:
5214:
5215:
5216:
5217:
5218:
5219:
5220:
5221:
5222:
5223:
5224:
5225:
5226:
5227:
5228:
5229:
5230:
5231:
5232:
5233:
5234:
5235:
5236:
5237:
5238:
5239:
5240:
5241:
5242:
5243:
5244:
5245:
5246:
5247:
5248:
5249:
5250:
5251:
5252:
5253:
5254:
5255:
5256:
5257:
5258:
5259:
5260:
5261:
5262:
5263:
5264:
5265:
5266:
5267:
5268:
5269:
5270:
5271:
5272:
5273:
5274:
5275:
5276:
5277:
5278:
5279:
5280:
5281:
5282:
5283:
5284:
5285:
5286:
5287:
5288:
5289:
5290:
5291:
5292:
5293:
5294:
5295:
5296:
5297:
5298:
5299:
5300:
5301:
5302:
5303:
5304:
5305:
5306:
5307:
5308:
5309:
5310:
5311:
5312:
5313:
5314:
5315:
5316:
5317:
5318:
5319:
5320:
5321:
5322:
5323:
5324:
5325:
5326:
5327:
5328:
5329:
5330:
5331:
5332:
5333:
5334:
5335:
5336:
5337:
5338:
5339:
5340:
5341:
5342:
5343:
5344:
5345:
5346:
5347:
5348:
5349:
5350:
5351:
5352:
5353:
5354:
5355:
5356:
5357:
5358:
5359:
5360:
5361:
5362:
5363:
5364:
5365:
5366:
5367:
5368:
5369:
5370:
5371:
5372:
5373:
5374:
5375:
5376:
5377:
5378:
5379:
5380:
5381:
5382:
5383:
5384:
5385:
5386:
5387:
5388:
5389:
5390:
5391:
5392:
5393:
5394:
5395:
5396:
5397:
5398:
5399:
5400:
5401:
5402:
5403:
5404:
5405:
5406:
5407:
5408:
5409:
5410:
5411:
5412:
5413:
5414:
5415:
5416:
5417:
5418:
5419:
5420:
5421:
5422:
5423:
5424:
5425:
5426:
5427:
5428:
5429:
5430:
5431:
5432:
5433:
5434:
5435:
5436:
5437:
5438:
5439:
5440:
5441:
5442:
5443:
5444:
5445:
5446:
5447:
5448:
5449:
5450:
5451:
5452:
5453:
5454:
5455:
5456:
5457:
5458:
5459:
5460:
5461:
5462:
5463:
5464:
5465:
5466:
5467:
5468:
5469:
5470:
5471:
5472:
5473:
5474:
5475:
5476:
5477:
5478:
5479:
5480:
5481:
5482:
5483:
5484:
5485:
5486:
5487:
5488:
5489:
5490:
5491:
5492:
5493:
5494:
5495:
5496:
5497:
5498:
5499:
5500:
5501:
5502:
5503:
5504:
5505:
5506:
5507:
5508:
5509:
5510:
5511:
5512:
5513:
5514:
5515:
5516:
5517:
5518:
5519:
5520:
5521:
5522:
5523:
5524:
5525:
5526:
5527:
5528:
5529:
5530:
5531:
5532:
5533:
5534:
5535:
5536:
5537:
5538:
5539:
5540:
5541:
5542:
5543:
5544:
5545:
5546:
5547:
5548:
5549:
5550:
5551:
5552:
5553:
5554:
5555:
5556:
5557:
5558:
5559:
5560:
5561:
5562:
5563:
5564:
5565:
5566:
5567:
5568:
5569:
5570:
5571:
5572:
5573:
5574:
5575:
5576:
5577:
5578:
5579:
5580:
5581:
5582:
5583:
5584:
5585:
5586:
5587:
5588:
5589:
5590:
5591:
5592:
5593:
5594:
5595:
5596:
5597:
5598:
5599:
5600:
5601:
5602:
5603:
5604:
5605:
5606:
5607:
5608:
5609:
5610:
5611:
5612:
5613:
5614:
5615:
5616:
5617:
5618:
5619:
5620:
5621:
5622:
5623:
5624:
5625:
5626:
5627:
5628:
5629:
5630:
5631:
5632:
5633:
5634:
5635:
5636:
5637:
5638:
5639:
5640:
5641:
5642:
5643:
5644:
5645:
5646:
5647:
5648:
5649:
5650:
5651:
5652:
5653:
5654:
5655:
5656:
5657:
5658:
5659:
5660:
5661:
5662:
5663:
5664:
5665:
5666:
5667:
5668:
5669:
5670:
5671:
5672:
5673:
5674:
5675:
5676:
5677:
5678:
5679:
5680:
5681:
5682:
5683:
5684:
5685:
5686:
5687:
5688:
5689:
5690:
5691:
5692:
5693:
5694:
5695:
5696:
5697:
5698:
5699:
5700:
5701:
5702:
5703:
5704:
5705:
5706:
5707:
5708:
5709:
5710:
5711:
5712:
5713:
5714:
5715:
5716:
5717:
5718:
5719:
5720:
5721:
5722:
5723:
5724:
5725:
5726:
5727:
5728:
5729:
5730:
5731:
5732:
5733:
5734:
5735:
5736:
5737:
5738:
5739:
5740:
5741:
5742:
5743:
5744:
5745:
5746:
5747:
5748:
5749:
5750:
5751:
5752:
5753:
5754:
5755:
5756:
5757:
5758:
5759:
5760:
5761:
5762:
5763:
5764:
5765:
5766:
5767:
5768:
5769:
5770:
5771:
5772:
5773:
5774:
5775:
5776:
5777:
5778:
5779:
5780:
5781:
5782:
5783:
5784:
5785:
5786:
5787:
5788:
5789:
5790:
5791:
5792:
5793:
5794:
5795:
5796:
5797:
5798:
5799:
5800:
5801:
5802:
5803:
5804:
5805:
5806:
5807:
5808:
5809:
5810:
5811:
5812:
5813:
5814:
5815:
5816:
5817:
5818:
5819:
5820:
5821:
5822:
5823:
5824:
5825:
5826:
5827:
5828:
5829:
5830:
5831:
5832:
5833:
5834:
5835:
5836:
5837:
5838:
5839:
5840:
5841:
5842:
5843:
5844:
5845:
5846:
5847:
5848:
5849:
5850:
5851:
5852:
5853:
5854:
5855:
5856:
5857:
5858:
5859:
5860:
5861:
5862:
5863:
5864:
5865:
5866:
5867:
5868:
5869:
5870:
5871:
5872:
5873:
5874:
5875:
5876:
5877:
5878:
5879:
5880:
5881:
5882:
5883:
5884:
5885:
5886:
5887:
5888:
5889:
5890:
5891:
5892:
5893:
5894:
5895:
5896:
5897:
5898:
5899:
5900:
5901:
5902:
5903:
5904:
5905:
5906:
5907:
5908:
5909:
5910:
5911:
5912:
5913:
5914:
5915:
5916:
5917:
5918:
5919:
5920:
5921:
5922:
5923:
5924:
5925:
5926:
5927:
5928:
5929:
5930:
5931:
5932:
5933:
5934:
5935:
5936:
5937:
5938:
5939:
5940:
5941:
5942:
5943:
5944:
5945:
5946:
5947:
5948:
5949:
5950:
5951:
5952:
5953:
5954:
5955:
5956:
5957:
5958:
5959:
5960:
5961:
5962:
5963:
5964:
5965:
5966:
5967:
5968:
5969:
5970:
5971:
5972:
5973:
5974:
5975:
5976:
5977:
5978:
5979:
5980:
5981:
5982:
5983:
5984:
5985:
5986:
5987:
5988:
5989:
5990:
5991:
5992:
5993:
5994:
5995:
5996:
5997:
5998:
5999:
6000:
6001:
6002:
6003:
6004:
6005:
6006:
6007:
6008:
6009:
6010:
6011:
6012:
6013:
6014:
6015:
6016:
6017:
6018:
6019:
6020:
6021:
6022:
6023:
6024:
6025:
6026:
6027:
6028:
6029:
6030:
6031:
6032:
6033:
6034:
6035:
6036:
6037:
6038:
6039:
6040:
6041:
6042:
6043:
6044:
6045:
6046:
6047:
6048:
6049:
6050:
6051:
6052:
6053:
6054:
6055:
6056:
6057:
6058:
6059:
6060:
6061:
6062:
6063:
6064:
6065:
6066:
6067:
6068:
6069:
6070:
6071:
6072:
6073:
6074:
6075:
6076:
6077:
6078:
6079:
6080:
6081:
6082:
6083:
6084:
6085:
6086:
6087:
6088:
6089:
6090:
6091:
6092:
6093:
6094:
6095:
6096:
6097:
6098:
6099:
6100:
6101:
6102:
6103:
6104:
6105:
6106:
6107:
6108:
6109:
6110:
6111:
6112:
6113:
6114:
6115:
6116:
6117:
6118:
6119:
6120:
6121:
6122:
6123:
6124:
6125:
6126:
6127:
6128:
6129:
6130:
6131:
6132:
6133:
6134:
6135:
6136:
6137:
6138:
6139:
6140:
6141:
6142:
6143:
6144:
6145:
6146:
6147:
6148:
6149:
6150:
6151:
6152:
6153:
6154:
6155:
6156:
6157:
6158:
6159:
6160:
6161:
6162:
6163:
6164:
6165:
6166:
6167:
6168:
6169:
6170:
6171:
6172:
6173:
6174:
6175:
6176:
6177:
6178:
6179:
6180:
6181:
6182:
6183:
6184:
6185:
6186:
6187:
6188:
6189:
6190:
6191:
6192:
6193:
6194:
6195:
6196:
6197:
6198:
6199:
6200:
6201:
6202:
6203:
6204:
6205:
6206:
6207:
6208:
6209:
6210:
6211:
6212:
6213:
6214:
6215:
6216:
6217:
6218:
6219:
6220:
6221:
6222:
6223:
6224:
6225:
6226:
6227:
6228:
6229:
6230:
6231:
6232:
6233:
6234:
6235:
6236:
6237:
6238:
6239:
6240:
6241:
6242:
6243:
6244:
6245:
6246:
6247:
6248:
6249:
6250:
6251:
6252:
6253:
6254:
6255:
6256:
6257:
6258:
6259:
6260:
6261:
6262:
6263:
6264:
6265:
6266:
6267:
6268:
6269:
6270:
6271:
6272:
6273:
6274:
6275:
6276:
6277:
6278:
6279:
6280:
6281:
6282:
6283:
6284:
6285:
6286:
6287:
6288:
6289:
6290:
6291:
6292:
6293:
6294:
6295:
6296:
6297:
6298:
6299:
6300:
6301:
6302:
6303:
6304:
6305:
6306:
6307:
6308:
6309:
6310:
6311:
6312:
6313:
6314:
6315:
6316:
6317:
6318:
6319:
6320:
6321:
6322:
6323:
6324:
6325:
6326:
6327:
6328:
6329:
6330:
6331:
6332:
6333:
6334:
6335:
6336:
6337:
6338:
6339:
6340:
6341:
6342:
6343:
6344:
6345:
6346:
6347:
6348:
6349:
6350:
6351:
6352:
6353:
6354:
6355:
6356:
6357:
6358:
6359:
6360:
6361:
6362:
6363:
6364:
6365:
6366:
6367:
6368:
6369:
6370:
6371:
6372:
6373:
6374:
6375:
6376:
6377:
6378:
6379:
6380:
6381:
6382:
6383:
6384:
6385:
6386:
6387:
6388:
6389:
6390:
6391:
6392:
6393:
6394:
6395:
6396:
6397:
6398:
6399:
6400:
6401:
6402:
6403:
6404:
6405:
6406:
6407:
6408:
6409:
6410:
6411:
6412:
6413:
6414:
6415:
6416:
6417:
6418:
6419:
6420:
6421:
6422:
6423:
6424:
6425:
6426:
6427:
6428:
6429:
6430:
6431:
6432:
6433:
6434:
6435:
6436:
6437:
6438:
6439:
6440:
6441:
6442:
6443:
6444:
6445:
6446:
6447:
6448:
6449:
6450:
6451:
6452:
6453:
6454:
6455:
6456:
6457:
6458:
6459:
6460:
6461:
6462:
6463:
6464:
6465:
6466:
6467:
6468:
6469:
6470:
6471:
6472:
6473:
6474:
6475:
6476:
6477:
6478:
6479:
6480:
6481:
6482:
6483:
6484:
6485:
6486:
6487:
6488:
6489:
6490:
6491:
6492:
6493:
6494:
6495:
6496:
6497:
6498:
6499:
6500:
6501:
6502:
6503:
6504:
6505:
6506:
6507:
6508:
6509:
6510:
6511:
6512:
6513:
6514:
6515:
6516:
6517:
6518:
6519:
6520:
6521:
6522:
6523:
6524:
6525:
6526:
6527:
6528:
6529:
6530:
6531:
6532:
6533:
6534:
6535:
6536:
6537:
6538:
6539:
6540:
6541:
6542:
6543:
6544:
6545:
6546:
6547:
6548:
6549:
6550:
6551:
6552:
6553:
6554:
6555:
6556:
6557:
6558:
6559:
6560:
6561:
6562:
6563:
6564:
6565:
6566:
6567:
6568:
6569:
6570:
6571:
6572:
6573:
6574:
6575:
6576:
6577:
6578:
6579:
6580:
6581:
6582:
6583:
6584:
6585:
6586:
6587:
6588:
6589:
6590:
6591:
6592:
6593:
6594:
6595:
6596:
6597:
6598:
6599:
6600:
6601:
6602:
6603:
6604:
6605:
6606:
6607:
6608:
6609:
6610:
6611:
6612:
6613:
6614:
6615:
6616:
6617:
6618:
6619:
6620:
6621:
6622:
6623:
6624:
6625:
6626:
6627:
6628:
6629:
6630:
6631:
6632:
6633:
6634:
6635:
6636:
6637:
6638:
6639:
6640:
6641:
6642:
6643:
6644:
6645:
6646:
6647:
6648:
6649:
6650:
6651:
6652:
6653:
6654:
6655:
6656:
6657:
6658:
6659:
6660:
6661:
6662:
6663:
6664:
6665:
6666:
6667:
6668:
6669:
6670:
6671:
6672:
6673:
6674:
6675:
6676:
6677:
6678:
6679:
6680:
6681:
6682:
6683:
6684:
6685:
6686:
6687:
6688:
6689:
6690:
6691:
6692:
6693:
6694:
6695:
6696:
6697:
6698:
6699:
6700:
6701:
6702:
6703:
6704:
6705:
6706:
6707:
6708:
6709:
6710:
6711:
6712:
6713:
6714:
6715:
6716:
6717:
6718:
6719:
6720:
6721:
6722:
6723:
6724:
6725:
6726:
6727:
6728:
6729:
6730:
6731:
6732:
6733:
6734:
6735:
6736:
6737:
6738:
6739:
6740:
6741:
6742:
6743:
6744:
6745:
6746:
6747:
6748:
6749:
6750:
6751:
6752:
6753:
6754:
6755:
6756:
6757:
6758:
6759:
6760:
6761:
6762:
6763:
6764:
6765:
6766:
6767:
6768:
6769:
6770:
6771:
6772:
6773:
6774:
6775:
6776:
6777:
6778:
6779:
6780:
6781:
6782:
6783:
6784:
6785:
6786:
6787:
6788:
6789:
6790:
6791:
6792:
6793:
6794:
6795:
6796:
6797:
6798:
6799:
6800:
6801:
6802:
6803:
6804:
6805:
6806:
6807:
6808:
6809:
6810:
6811:
6812:
6813:
6814:
6815:
6816:
6817:
6818:
6819:
6820:
6821:
6822:
6823:
6824:
6825:
6826:
6827:
6828:
6829:
6830:
6831:
6832:
6833:
6834:
6835:
6836:
6837:
6838:
6839:
6840:
6841:
6842:
6843:
6844:
6845:
6846:
6847:
6848:
6849:
6850:
6851:
6852:
6853:
6854:
6855:
6856:
6857:
6858:
6859:
6860:
6861:
6862:
6863:
6864:
6865:
6866:
6867:
6868:
6869:
6870:
6871:
6872:
6873:
6874:
6875:
6876:
6877:
6878:
6879:
6880:
6881:
6882:
6883:
6884:
6885:
6886:
6887:
6888:
6889:
6890:
6891:
6892:
6893:
6894:
6895:
6896:
6897:
6898:
6899:
6900:
6901:
6902:
6903:
6904:
6905:
6906:
6907:
6908:
6909:
6910:
6911:
6912:
6913:
6914:
6915:
6916:
6917:
6918:
6919:
6920:
6921:
6922:
6923:
6924:
6925:
6926:
6927:
6928:
6929:
6930:
6931:
6932:
6933:
6934:
6935:
6936:
6937:
6938:
6939:
6940:
6941:
6942:
6943:
6944:
6945:
6946:
6947:
6948:
6949:
6950:
6951:
6952:
6953:
6954:
6955:
6956:
6957:
6958:
6959:
6960:
6961:
6962:
6963:
6964:
6965:
6966:
6967:
6968:
6969:
6970:
6971:
6972:
6973:
6974:
6975:
6976:
6977:
6978:
6979:
6980:
6981:
6982:
6983:
6984:
6985:
6986:
6987:
6988:
6989:
6990:
6991:
6992:
6993:
6994:
6995:
6996:
6997:
6998:
6999:
7000:
7001:
7002:
7003:
7004:
7005:
7006:
7007:
7008:
7009:
7010:
7011:
7012:
7013:
7014:
7015:
7016:
7017:
7018:
7019:
7020:
7021:
7022:
7023:
7024:
7025:
7026:
7027:
7028:
7029:
7030:
7031:
7032:
7033:
7034:
7035:
7036:
7037:
7038:
7039:
7040:
7041:
7042:
7043:
7044:
7045:
7046:
7047:
7048:
7049:
7050:
7051:
7052:
7053:
7054:
7055:
7056:
7057:
7058:
7059:
7060:
7061:
7062:
7063:
7064:
7065:
7066:
7067:
7068:
7069:
7070:
7071:
7072:
7073:
7074:
7075:
7076:
7077:
7078:
7079:
7080:
7081:
7082:
7083:
7084:
7085:
7086:
7087:
7088:
7089:
7090:
7091:
7092:
7093:
7094:
7095:
7096:
7097:
7098:
7099:
7100:
7101:
7102:
7103:
7104:
7105:
7106:
7107:
7108:
7109:
7110:
7111:
7112:
7113:
7114:
7115:
7116:
7117:
7118:
7119:
7120:
7121:
7122:
7123:
7124:
7125:
7126:
7127:
7128:
7129:
7130:
7131:
7132:
7133:
7134:
7135:
7136:
7137:
7138:
7139:
7140:
7141:
7142:
7143:
7144:
7145:
7146:
7147:
7148:
7149:
7150:
7151:
7152:
7153:
7154:
7155:
7156:
7157:
7158:
7159:
7160:
7161:
7162:
7163:
7164:
7165:
7166:
7167:
7168:
7169:
7170:
7171:
7172:
7173:
7174:
7175:
7176:
7177:
7178:
7179:
7180:
7181:
7182:
7183:
7184:
7185:
7186:
7187:
7188:
7189:
7190:
7191:
7192:
7193:
7194:
7195:
7196:
7197:
7198:
7199:
7200:
7201:
7202:
7203:
7204:
7205:
7206:
7207:
7208:
7209:
7210:
7211:
7212:
7213:
7214:
7215:
7216:
7217:
7218:
7219:
7220:
7221:
7222:
7223:
7224:
7225:
7226:
7227:
7228:
7229:
7230:
7231:
7232:
7233:
7234:
7235:
7236:
7237:
7238:
7239:
7240:
7241:
7242:
7243:
7244:
7245:
7246:
7247:
7248:
7249:
7250:
7251:
7252:
7253:
7254:
7255:
7256:
7257:
7258:
7259:
7260:
7261:
7262:
7263:
7264:
7265:
7266:
7267:
7268:
7269:
7270:
7271:
7272:
7273:
7274:
7275:
7276:
7277:
7278:
7279:
7280:
7281:
7282:
7283:
7284:
7285:
7286:
7287:
7288:
7289:
7290:
7291:
7292:
7293:
7294:
7295:
7296:
7297:
7298:
7299:
7300:
7301:
7302:
7303:
7304:
7305:
7306:
7307:
7308:
7309:
7310:
7311:
7312:
7313:
7314:
7315:
7316:
7317:
7318:
7319:
7320:
7321:
7322:
7323:
7324:
7325:
7326:
7327:
7328:
7329:
7330:
7331:
7332:
7333:
7334:
7335:
7336:
7337:
7338:
7339:
7340:
7341:
7342:
7343:
7344:
7345:
7346:
7347:
7348:
7349:
7350:
7351:
7352:
7353:
7354:
7355:
7356:
7357:
7358:
7359:
7360:
7361:
7362:
7363:
7364:
7365:
7366:
7367:
7368:
7369:
7370:
7371:
7372:
7373:
7374:
7375:
7376:
7377:
7378:
7379:
7380:
7381:
7382:
7383:
7384:
7385:
7386:
7387:
7388:
7389:
7390:
7391:
7392:
7393:
7394:
7395:
7396:
7397:
7398:
7399:
7400:
7401:
7402:
7403:
7404:
7405:
7406:
7407:
7408:
7409:
7410:
7411:
7412:
7413:
7414:
7415:
7416:
7417:
7418:
7419:
7420:
7421:
7422:
7423:
7424:
7425:
7426:
7427:
7428:
7429:
7430:
7431:
7432:
7433:
7434:
7435:
7436:
7437:
7438:
7439:
7440:
7441:
7442:
7443:
7444:
7445:
7446:
7447:
7448:
7449:
7450:
7451:
7452:
7453:
7454:
7455:
7456:
7457:
7458:
7459:
7460:
7461:
7462:
7463:
7464:
7465:
7466:
7467:
7468:
7469:
7470:
7471:
7472:
7473:
7474:
7475:
7476:
7477:
7478:
7479:
7480:
7481:
7482:
7483:
7484:
7485:
7486:
7487:
7488:
7489:
7490:
7491:
7492:
7493:
7494:
7495:
7496:
7497:
7498:
7499:
7500:
7501:
7502:
7503:
7504:
7505:
7506:
7507:
7508:
7509:
7510:
7511:
7512:
7513:
7514:
7515:
7516:
7517:
7518:
7519:
7520:
7521:
7522:
7523:
7524:
7525:
7526:
7527:
7528:
7529:
7530:
7531:
7532:
7533:
7534:
7535:
7536:
7537:
7538:
7539:
7540:
7541:
7542:
7543:
7544:
7545:
7546:
7547:
7548:
7549:
7550:
7551:
7552:
7553:
7554:
7555:
7556:
7557:
7558:
7559:
7560:
7561:
7562:
7563:
7564:
7565:
7566:
7567:
7568:
7569:
7570:
7571:
7572:
7573:
7574:
7575:
7576:
7577:
7578:
7579:
7580:
7581:
7582:
7583:
7584:
7585:
7586:
7587:
7588:
7589:
7590:
7591:
7592:
7593:
7594:
7595:
7596:
7597:
7598:
7599:
7600:
7601:
7602:
7603:
7604:
7605:
7606:
7607:
7608:
7609:
7610:
7611:
7612:
7613:
7614:
7615:
7616:
7617:
7618:
7619:
7620:
7621:
7622:
7623:
7624:
7625:
7626:
7627:
7628:
7629:
7630:
7631:
7632:
7633:
7634:
7635:
7636:
7637:
7638:
7639:
7640:
7641:
7642:
7643:
7644:
7645:
7646:
7647:
7648:
7649:
7650:
7651:
7652:
7653:
7654:
7655:
7656:
7657:
7658:
7659:
7660:
7661:
7662:
7663:
7664:
7665:
7666:
7667:
7668:
7669:
7670:
7671:
7672:
7673:
7674:
7675:
7676:
7677:
7678:
7679:
7680:
7681:
7682:
7683:
7684:
7685:
7686:
7687:
7688:
7689:
7690:
7691:
7692:
7693:
7694:
7695:
7696:
7697:
7698:
7699:
7700:
7701:
7702:
7703:
7704:
7705:
7706:
7707:
7708:
7709:
7710:
7711:
7712:
7713:
7714:
7715:
7716:
7717:
7718:
7719:
7720:
7721:
7722:
7723:
7724:
7725:
7726:
7727:
7728:
7729:
7730:
7731:
7732:
7733:
7734:
7735:
7736:
7737:
7738:
7739:
7740:
7741:
7742:
7743:
7744:
7745:
7746:
7747:
7748:
7749:
7750:
7751:
7752:
7753:
7754:
7755:
7756:
7757:
7758:
7759:
7760:
7761:
7762:
7763:
7764:
7765:
7766:
7767:
7768:
7769:
7770:
7771:
7772:
7773:
7774:
7775:
7776:
7777:
7778:
7779:
7780:
7781:
7782:
7783:
7784:
7785:
7786:
7787:
7788:
7789:
7790:
7791:
7792:
7793:
7794:
7795:
7796:
7797:
7798:
7799:
7800:
7801:
7802:
7803:
7804:
7805:
7806:
7807:
7808:
7809:
7810:
7811:
7812:
7813:
7814:
7815:
7816:
7817:
7818:
7819:
7820:
7821:
7822:
7823:
7824:
7825:
7826:
7827:
7828:
7829:
7830:
7831:
7832:
7833:
7834:
7835:
7836:
7837:
7838:
7839:
7840:
7841:
7842:
7843:
7844:
7845:
7846:
7847:
7848:
7849:
7850:
7851:
7852:
7853:
7854:
7855:
7856:
7857:
7858:
7859:
7860:
7861:
7862:
7863:
7864:
7865:
7866:
7867:
7868:
7869:
7870:
7871:
7872:
7873:
7874:
7875:
7876:
7877:
7878:
7879:
7880:
7881:
7882:
7883:
7884:
7885:
7886:
7887:
7888:
7889:
7890:
7891:
7892:
7893:
7894:
7895:
7896:
7897:
7898:
7899:
7900:
7901:
7902:
7903:
7904:
7905:
7906:
7907:
7908:
7909:
7910:
7911:
7912:
7913:
7914:
7915:
7916:
7917:
7918:
7919:
7920:
7921:
7922:
7923:
7924:
7925:
7926:
7927:
7928:
7929:
7930:
7931:
7932:
7933:
7934:
7935:
7936:
7937:
7938:
7939:
7940:
7941:
7942:
7943:
7944:
7945:
7946:
7947:
7948:
7949:
7950:
7951:
7952:
7953:
7954:
7955:
7956:
7957:
7958:
7959:
7960:
7961:
7962:
7963:
7964:
7965:
7966:
7967:
7968:
7969:
7970:
7971:
7972:
7973:
7974:
7975:
7976:
7977:
7978:
7979:
7980:
7981:
7982:
7983:
7984:
7985:
7986:
7987:
7988:
7989:
7990:
7991:
7992:
7993:
7994:
7995:
7996:
7997:
7998:
7999:
8000:
8001:
8002:
8003:
8004:
8005:
8006:
8007:
8008:
8009:
8010:
8011:
8012:
8013:
8014:
8015:
8016:
8017:
8018:
8019:
8020:
8021:
8022:
8023:
8024:
8025:
8026:
8027:
8028:
8029:
8030:
8031:
8032:
8033:
8034:
8035:
8036:
8037:
8038:
8039:
8040:
8041:
8042:
8043:
8044:
8045:
8046:
8047:
8048:
8049:
8050:
8051:
8052:
8053:
8054:
8055:
8056:
8057:
8058:
8059:
8060:
8061:
8062:
8063:
8064:
8065:
8066:
8067:
8068:
8069:
8070:
8071:
8072:
8073:
8074:
8075:
8076:
8077:
8078:
8079:
8080:
8081:
8082:
8083:
8084:
8085:
8086:
8087:
8088:
8089:
8090:
8091:
8092:
8093:
8094:
8095:
8096:
8097:
8098:
8099:
8100:
8101:
8102:
8103:
8104:
8105:
8106:
8107:
8108:
8109:
8110:
8111:
8112:
8113:
8114:
8115:
8116:
8117:
8118:
8119:
8120:
8121:
8122:
8123:
8124:
8125:
8126:
8127:
8128:
8129:
8130:
8131:
8132:
8133:
8134:
8135:
8136:
8137:
8138:
8139:
8140:
8141:
8142:
8143:
8144:
8145:
8146:
8147:
8148:
8149:
8150:
8151:
8152:
8153:
8154:
8155:
8156:
8157:
8158:
8159:
8160:
8161:
8162:
8163:
8164:
8165:
8166:
8167:
8168:
8169:
8170:
8171:
8172:
8173:
8174:
8175:
8176:
8177:
8178:
8179:
8180:
8181:
8182:
8183:
8184:
8185:
8186:
8187:
8188:
8189:
8190:
8191:
8192:
8193:
8194:
8195:
8196:
8197:
8198:
8199:
8200:
8201:
8202:
8203:
8204:
8205:
8206:
8207:
8208:
8209:
8210:
8211:
8212:
8213:
8214:
8215:
8216:
8217:
8218:
8219:
8220:
8221:
8222:
8223:
8224:
8225:
8226:
8227:
8228:
8229:
8230:
8231:
8232:
8233:
8234:
8235:
8236:
8237:
8238:
8239:
8240:
8241:
8242:
8243:
8244:
8245:
8246:
8247:
8248:
8249:
8250:
8251:
8252:
8253:
8254:
8255:
8256:
8257:
8258:
8259:
8260:
8261:
8262:
8263:
8264:
8265:
8266:
8267:
8268:
8269:
8270:
8271:
8272:
8273:
8274:
8275:
8276:
8277:
8278:
8279:
8280:
8281:
8282:
8283:
8284:
8285:
8286:
8287:
8288:
8289:
8290:
8291:
8292:
8293:
8294:
8295:
8296:
8297:
8298:
8299:
8300:
8301:
8302:
8303:
8304:
8305:
8306:
8307:
8308:
8309:
8310:
8311:
8312:
8313:
8314:
8315:
8316:
8317:
8318:
8319:
8320:
8321:
8322:
8323:
8324:
8325:
8326:
8327:
8328:
8329:
8330:
8331:
8332:
8333:
8334:
8335:
8336:
8337:
8338:
8339:
8340:
8341:
8342:
8343:
8344:
8345:
8346:
8347:
8348:
8349:
8350:
8351:
8352:
8353:
8354:
8355:
8356:
8357:
8358:
8359:
8360:
8361:
8362:
8363:
8364:
8365:
8366:
8367:
8368:
8369:
8370:
8371:
8372:
8373:
8374:
8375:
8376:
8377:
8378:
8379:
8380:
8381:
8382:
8383:
8384:
8385:
8386:
8387:
8388:
8389:
8390:
8391:
8392:
8393:
8394:
8395:
8396:
8397:
8398:
8399:
8400:
8401:
8402:
8403:
8404:
8405:
8406:
8407:
8408:
8409:
8410:
8411:
8412:
8413:
8414:
8415:
8416:
8417:
8418:
8419:
8420:
8421:
8422:
8423:
8424:
8425:
8426:
8427:
8428:
8429:
8430:
8431:
8432:
8433:
8434:
8435:
8436:
8437:
8438:
8439:
8440:
8441:
8442:
8443:
8444:
8445:
8446:
8447:
8448:
8449:
8450:
8451:
8452:
8453:
8454:
8455:
8456:
8457:
8458:
8459:
8460:
8461:
8462:
8463:
8464:
8465:
8466:
8467:
8468:
8469:
8470:
8471:
8472:
8473:
8474:
8475:
8476:
8477:
8478:
8479:
8480:
8481:
8482:
8483:
8484:
8485:
8486:
8487:
8488:
8489:
8490:
8491:
8492:
8493:
8494:
8495:
8496:
8497:
8498:
8499:
8500:
8501:
8502:
8503:
8504:
8505:
8506:
8507:
8508:
8509:
8510:
8511:
8512:
8513:
8514:
8515:
8516:
8517:
8518:
8519:
8520:
8521:
8522:
8523:
8524:
8525:
8526:
8527:
8528:
8529:
8530:
8531:
8532:
8533:
8534:
8535:
8536:
8537:
8538:
8539:
8540:
8541:
8542:
8543:
8544:
8545:
8546:
8547:
8548:
8549:
8550:
8551:
8552:
8553:
8554:
8555:
8556:
8557:
8558:
8559:
8560:
8561:
8562:
8563:
8564:
8565:
8566:
8567:
8568:
8569:
8570:
8571:
8572:
8573:
8574:
8575:
8576:
8577:
8578:
8579:
8580:
8581:
8582:
8583:
8584:
8585:
8586:
8587:
8588:
8589:
8590:
8591:
8592:
8593:
8594:
8595:
8596:
8597:
8598:
8599:
8600:
8601:
8602:
8603:
8604:
8605:
8606:
8607:
8608:
8609:
8610:
8611:
8612:
8613:
8614:
8615:
8616:
8617:
8618:
8619:
8620:
8621:
8622:
8623:
8624:
8625:
8626:
8627:
8628:
8629:
8630:
8631:
8632:
8633:
8634:
8635:
8636:
8637:
8638:
8639:
8640:
8641:
8642:
8643:
8644:
8645:
8646:
8647:
8648:
8649:
8650:
8651:
8652:
8653:
8654:
8655:
8656:
8657:
8658:
8659:
8660:
8661:
8662:
8663:
8664:
8665:
8666:
8667:
8668:
8669:
8670:
8671:
8672:
8673:
8674:
8675:
8676:
8677:
8678:
8679:
8680:
8681:
8682:
8683:
8684:
8685:
8686:
8687:
8688:
8689:
8690:
8691:
8692:
8693:
8694:
8695:
8696:
8697:
8698:
8699:
8700:
8701:
8702:
8703:
8704:
8705:
8706:
8707:
8708:
8709:
8710:
8711:
8712:
8713:
8714:
8715:
8716:
8717:
8718:
8719:
8720:
8721:
8722:
8723:
8724:
8725:
8726:
8727:
8728:
8729:
8730:
8731:
8732:
8733:
8734:
8735:
8736:
8737:
8738:
8739:
8740:
8741:
8742:
8743:
8744:
8745:
8746:
8747:
8748:
8749:
8750:
8751:
8752:
8753:
8754:
8755:
8756:
8757:
8758:
8759:
8760:
8761:
8762:
8763:
8764:
8765:
8766:
8767:
8768:
8769:
8770:
8771:
8772:
8773:
8774:
8775:
8776:
8777:
8778:
8779:
8780:
8781:
8782:
8783:
8784:
8785:
8786:
8787:
8788:
8789:
8790:
8791:
8792:
8793:
8794:
8795:
8796:
8797:
8798:
8799:
8800:
8801:
8802:
8803:
8804:
8805:
8806:
8807:
8808:
8809:
8810:
8811:
8812:
8813:
8814:
8815:
8816:
8817:
8818:
8819:
8820:
8821:
8822:
8823:
8824:
8825:
8826:
8827:
8828:
8829:
8830:
8831:
8832:
8833:
8834:
8835:
8836:
8837:
8838:
8839:
8840:
8841:
8842:
8843:
8844:
8845:
8846:
8847:
8848:
8849:
8850:
8851:
8852:
8853:
8854:
8855:
8856:
8857:
8858:
8859:
8860:
8861:
8862:
8863:
8864:
8865:
8866:
8867:
8868:
8869:
8870:
8871:
8872:
8873:
8874:
8875:
8876:
8877:
8878:
8879:
8880:
8881:
8882:
8883:
8884:
8885:
8886:
8887:
8888:
8889:
8890:
8891:
8892:
8893:
8894:
8895:
8896:
8897:
8898:
8899:
8900:
8901:
8902:
8903:
8904:
8905:
8906:
8907:
8908:
8909:
8910:
8911:
8912:
8913:
8914:
8915:
8916:
8917:
8918:
8919:
8920:
8921:
8922:
8923:
8924:
8925:
8926:
8927:
8928:
8929:
8930:
8931:
8932:
8933:
8934:
8935:
8936:
8937:
8938:
8939:
8940:
8941:
8942:
8943:
8944:
8945:
8946:
8947:
8948:
8949:
8950:
8951:
8952:
8953:
8954:
8955:
8956:
8957:
8958:
8959:
8960:
8961:
8962:
8963:
8964:
8965:
8966:
8967:
8968:
8969:
8970:
8971:
8972:
8973:
8974:
8975:
8976:
8977:
8978:
8979:
8980:
8981:
8982:
8983:
8984:
8985:
8986:
8987:
8988:
8989:
8990:
8991:
8992:
8993:
8994:
8995:
8996:
8997:
8998:
8999:
9000:
9001:
9002:
9003:
9004:
9005:
9006:
9007:
9008:
9009:
9010:
9011:
9012:
9013:
9014:
9015:
9016:
9017:
9018:
9019:
9020:
9021:
9022:
9023:
9024:
9025:
9026:
9027:
9028:
9029:
9030:
9031:
9032:
9033:
9034:
9035:
9036:
9037:
9038:
9039:
9040:
9041:
9042:
9043:
9044:
9045:
9046:
9047:
9048:
9049:
9050:
9051:
9052:
9053:
9054:
9055:
9056:
9057:
9058:
9059:
9060:
9061:
9062:
9063:
9064:
9065:
9066:
9067:
9068:
9069:
9070:
9071:
9072:
9073:
9074:
9075:
9076:
9077:
9078:
9079:
9080:
9081:
9082:
9083:
9084:
9085:
9086:
9087:
9088:
9089:
9090:
9091:
9092:
9093:
9094:
9095:
9096:
9097:
9098:
9099:
9100:
9101:
9102:
9103:
9104:
9105:
9106:
9107:
9108:
9109:
9110:
9111:
9112:
9113:
9114:
9115:
9116:
9117:
9118:
9119:
9120:
9121:
9122:
9123:
9124:
9125:
9126:
9127:
9128:
9129:
9130:
9131:
9132:
9133:
9134:
9135:
9136:
9137:
9138:
9139:
9140:
9141:
9142:
9143:
9144:
9145:
9146:
9147:
9148:
9149:
9150:
9151:
9152:
9153:
9154:
9155:
9156:
9157:
9158:
9159:
9160:
9161:
9162:
9163:
9164:
9165:
9166:
9167:
9168:
9169:
9170:
9171:
9172:
9173:
9174:
9175:
9176:
9177:
9178:
9179:
9180:
9181:
9182:
9183:
9184:
9185:
9186:
9187:
9188:
9189:
9190:
9191:
9192:
9193:
9194:
9195:
9196:
9197:
9198:
9199:
9200:
9201:
9202:
9203:
9204:
9205:
9206:
9207:
9208:
9209:
9210:
9211:
9212:
9213:
9214:
9215:
9216:
9217:
9218:
9219:
9220:
9221:
9222:
9223:
9224:
9225:
9226:
9227:
9228:
9229:
9230:
9231:
9232:
9233:
9234:
9235:
9236:
9237:
9238:
9239:
9240:
9241:
9242:
9243:
9244:
9245:
9246:
9247:
9248:
9249:
9250:
9251:
9252:
9253:
9254:
9255:
9256:
9257:
9258:
9259:
9260:
9261:
9262:
9263:
9264:
9265:
9266:
9267:
9268:
9269:
9270:
9271:
9272:
9273:
9274:
9275:
9276:
9277:
9278:
9279:
9280:
9281:
9282:
9283:
9284:
9285:
9286:
9287:
9288:
9289:
9290:
9291:
9292:
9293:
9294:
9295:
9296:
9297:
9298:
9299:
9300:
9301:
9302:
9303:
9304:
9305:
9306:
9307:
9308:
9309:
9310:
9311:
9312:
9313:
9314:
9315:
9316:
9317:
9318:
9319:
9320:
9321:
9322:
9323:
9324:
9325:
9326:
9327:
9328:
9329:
9330:
9331:
9332:
9333:
9334:
9335:
9336:
9337:
9338:
9339:
9340:
9341:
9342:
9343:
9344:
9345:
9346:
9347:
9348:
9349:
9350:
9351:
9352:
9353:
9354:
9355:
9356:
9357:
9358:
9359:
9360:
9361:
9362:
9363:
9364:
9365:
9366:
9367:
9368:
9369:
9370:
9371:
9372:
9373:
9374:
9375:
9376:
9377:
9378:
9379:
9380:
9381:
9382:
9383:
9384:
9385:
9386:
9387:
9388:
9389:
9390:
9391:
9392:
9393:
9394:
9395:
9396:
9397:
9398:
9399:
9400:
9401:
9402:
9403:
9404:
9405:
9406:
9407:
9408:
9409:
9410:
9411:
9412:
9413:
9414:
9415:
9416:
9417:
9418:
9419:
9420:
9421:
9422:
9423:
9424:
9425:
9426:
9427:
9428:
9429:
9430:
9431:
9432:
9433:
9434:
9435:
9436:
9437:
9438:
9439:
9440:
9441:
9442:
9443:
9444:
9445:
9446:
9447:
9448:
9449:
9450:
9451:
9452:
9453:
9454:
9455:
9456:
9457:
9458:
9459:
9460:
9461:
9462:
9463:
9464:
9465:
9466:
9467:
9468:
9469:
9470:
9471:
9472:
9473:
9474:
9475:
9476:
9477:
9478:
9479:
9480:
9481:
9482:
9483:
9484:
9485:
9486:
9487:
9488:
9489:
9490:
9491:
9492:
9493:
9494:
9495:
9496:
9497:
9498:
9499:
9500:
9501:
9502:
9503:
9504:
9505:
9506:
9507:
9508:
9509:
9510:
9511:
9512:
9513:
9514:
9515:
9516:
9517:
9518:
9519:
9520:
9521:
9522:
9523:
9524:
9525:
9526:
9527:
9528:
9529:
9530:
9531:
9532:
9533:
9534:
9535:
9536:
9537:
9538:
9539:
9540:
9541:
9542:
9543:
9544:
9545:
9546:
9547:
9548:
9549:
9550:
9551:
9552:
9553:
9554:
9555:
9556:
9557:
9558:
9559:
9560:
9561:
9562:
9563:
9564:
9565:
9566:
9567:
9568:
9569:
9570:
9571:
9572:
9573:
9574:
9575:
9576:
9577:
9578:
9579:
9580:
9581:
9582:
9583:
9584:
9585:
9586:
9587:
9588:
9589:
9590:
9591:
9592:
9593:
9594:
9595:
9596:
9597:
9598:
9599:
9600:
9601:
9602:
9603:
9604:
9605:
9606:
9607:
9608:
9609:
9610:
9611:
9612:
9613:
9614:
9615:
9616:
9617:
9618:
9619:
9620:
9621:
9622:
9623:
9624:
9625:
9626:
9627:
9628:
9629:
9630:
9631:
9632:
9633:
9634:
9635:
9636:
9637:
9638:
9639:
9640:
9641:
9642:
9643:
9644:
9645:
9646:
9647:
9648:
9649:
9650:
9651:
9652:
9653:
9654:
9655:
9656:
9657:
9658:
9659:
9660:
9661:
9662:
9663:
9664:
9665:
9666:
9667:
9668:
9669:
9670:
9671:
9672:
9673:
9674:
9675:
9676:
9677:
9678:
9679:
9680:
9681:
9682:
9683:
9684:
9685:
9686:
9687:
9688:
9689:
9690:
9691:
9692:
9693:
9694:
9695:
9696:
9697:
9698:
9699:
9700:
9701:
9702:
9703:
9704:
9705:
9706:
9707:
9708:
9709:
9710:
9711:
9712:
9713:
9714:
9715:
9716:
9717:
9718:
9719:
9720:
9721:
9722:
9723:
9724:
9725:
9726:
9727:
9728:
9729:
9730:
9731:
9732:
9733:
9734:
9735:
9736:
9737:
9738:
9739:
9740:
9741:
9742:
9743:
9744:
9745:
9746:
9747:
9748:
9749:
9750:
9751:
9752:
9753:
9754:
9755:
9756:
9757:
9758:
9759:
9760:
9761:
9762:
9763:
9764:
9765:
9766:
9767:
9768:
9769:
9770:
9771:
9772:
9773:
9774:
9775:
9776:
9777:
9778:
9779:
9780:
9781:
9782:
9783:
9784:
9785:
9786:
9787:
9788:
9789:
9790:
9791:
9792:
9793:
9794:
9795:
9796:
9797:
9798:
9799:
9800:
9801:
9802:
9803:
9804:
9805:
9806:
9807:
9808:
9809:
9810:
9811:
9812:
9813:
9814:
9815:
9816:
9817:
9818:
9819:
9820:
9821:
9822:
9823:
9824:
9825:
9826:
9827:
9828:
9829:
9830:
9831:
9832:
9833:
9834:
9835:
9836:
9837:
9838:
9839:
9840:
9841:
9842:
9843:
9844:
9845:
9846:
9847:
9848:
9849:
9850:
9851:
9852:
9853:
9854:
9855:
9856:
9857:
9858:
9859:
9860:
9861:
9862:
9863:
9864:
9865:
9866:
9867:
9868:
9869:
9870:
9871:
9872:
9873:
9874:
9875:
9876:
9877:
9878:
9879:
9880:
9881:
9882:
9883:
9884:
9885:
9886:
9887:
9888:
9889:
9890:
9891:
9892:
9893:
9894:
9895:
9896:
9897:
9898:
9899:
9900:
9901:
9902:
9903:
9904:
9905:
9906:
9907:
9908:
9909:
9910:
9911:
9912:
9913:
9914:
9915:
9916:
9917:
9918:
9919:
9920:
9921:
9922:
9923:
9924:
9925:
9926:
9927:
9928:
9929:
9930:
9931:
9932:
9933:
9934:
9935:
9936:
9937:
9938:
9939:
9940:
9941:
9942:
9943:
9944:
9945:
9946:
9947:
9948:
9949:
9950:
9951:
9952:
9953:
9954:
9955:
9956:
9957:
9958:
9959:
9960:
9961:
9962:
9963:
9964:
9965:
9966:
9967:
9968:
9969:
9970:
9971:
9972:
9973:
9974:
9975:
9976:
9977:
9978:
9979:
9980:
9981:
9982:
9983:
9984:
9985:
9986:
9987:
9988:
9989:
9990:
9991:
9992:
9993:
9994:
9995:
9996:
9997:
9998:
9999:
10000:
10001:
10002:
10003:
10004:
10005:
10006:
10007:
10008:
10009:
10010:
10011:
10012:
10013:
10014:
10015:
10016:
10017:
10018:
10019:
10020:
10021:
10022:
10023:
10024:
10025:
10026:
10027:
10028:
10029:
10030:
10031:
10032:
10033:
10034:
10035:
10036:
10037:
10038:
10039:
10040:
10041:
10042:
10043:
10044:
10045:
10046:
10047:
10048:
10049:
10050:
10051:
10052:
10053:
10054:
10055:
10056:
10057:
10058:
10059:
10060:
10061:
10062:
10063:
10064:
10065:
10066:
10067:
10068:
10069:
10070:
10071:
10072:
10073:
10074:
10075:
10076:
10077:
10078:
10079:
10080:
10081:
10082:
10083:
10084:
10085:
10086:
10087:
10088:
10089:
10090:
10091:
10092:
10093:
10094:
10095:
10096:
10097:
10098:
10099:
10100:
10101:
10102:
10103:
10104:
10105:
10106:
10107:
10108:
10109:
10110:
10111:
10112:
10113:
10114:
10115:
10116:
10117:
10118:
10119:
10120:
10121:
10122:
10123:
10124:
10125:
10126:
10127:
10128:
10129:
10130:
10131:
10132:
10133:
10134:
10135:
10136:
10137:
10138:
10139:
10140:
10141:
10142:
10143:
10144:
10145:
10146:
10147:
10148:
10149:
10150:
10151:
10152:
10153:
10154:
10155:
10156:
10157:
10158:
10159:
10160:
10161:
10162:
10163:
10164:
10165:
10166:
10167:
10168:
10169:
10170:
10171:
10172:
10173:
10174:
10175:
10176:
10177:
10178:
10179:
10180:
10181:
10182:
10183:
10184:
10185:
10186:
10187:
10188:
10189:
10190:
10191:
10192:
10193:
10194:
10195:
10196:
10197:
10198:
10199:
10200:
10201:
10202:
10203:
10204:
10205:
10206:
10207:
10208:
10209:
10210:
10211:
10212:
10213:
10214:
10215:
10216:
10217:
10218:
10219:
10220:
10221:
10222:
10223:
10224:
10225:
10226:
10227:
10228:
10229:
10230:
10231:
10232:
10233:
10234:
10235:
10236:
10237:
10238:
10239:
10240:
10241:
10242:
10243:
10244:
10245:
10246:
10247:
10248:
10249:
10250:
10251:
10252:
10253:
10254:
10255:
10256:
10257:
10258:
10259:
10260:
10261:
10262:
10263:
10264:
10265:
10266:
10267:
10268:
10269:
10270:
10271:
10272:
10273:
10274:
10275:
10276:
10277:
10278:
10279:
10280:
10281:
10282:
10283:
10284:
10285:
10286:
10287:
10288:
10289:
10290:
10291:
10292:
10293:
10294:
10295:
10296:
10297:
10298:
10299:
10300:
10301:
10302:
10303:
10304:
10305:
10306:
10307:
10308:
10309:
10310:
10311:
10312:
10313:
10314:
10315:
10316:
10317:
10318:
10319:
10320:
10321:
10322:
10323:
10324:
10325:
10326:
10327:
10328:
10329:
10330:
10331:
10332:
10333:
10334:
10335:
10336:
10337:
10338:
10339:
10340:
10341:
10342:
10343:
10344:
10345:
10346:
10347:
10348:
10349:
10350:
10351:
10352:
10353:
10354:
10355:
10356:
10357:
10358:
10359:
10360:
10361:
10362:
10363:
10364:
10365:
10366:
10367:
10368:
10369:
10370:
10371:
10372:
10373:
10374:
10375:
10376:
10377:
10378:
10379:
10380:
10381:
10382:
10383:
10384:
10385:
10386:
10387:
10388:
10389:
10390:
10391:
10392:
10393:
10394:
10395:
10396:
10397:
10398:
10399:
10400:
10401:
10402:
10403:
10404:
10405:
10406:
10407:
10408:
10409:
10410:
10411:
10412:
10413:
10414:
10415:
10416:
10417:
10418:
10419:
10420:
10421:
10422:
10423:
10424:
10425:
10426:
10427:
10428:
10429:
10430:
10431:
10432:
10433:
10434:
10435:
10436:
10437:
10438:
10439:
10440:
10441:
10442:
10443:
10444:
10445:
10446:
10447:
10448:
10449:
10450:
10451:
10452:
10453:
10454:
10455:
10456:
10457:
10458:
10459:
10460:
10461:
10462:
10463:
10464:
10465:
10466:
10467:

Select allOpen in new window

 

by: sobeservices2Posted on 2009-08-13 at 07:11:34ID: 25088400

I'am a little confused in your directions.

You want me to add this to the contact form

$publickey = "PUBKEY";
$privatekey = "PRIV_KEY";
.
.
.
.
   # set the error code so that we can display it
   $error = $resp->error;
   $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=".$error;
   header("Location: ".$loc);
 }
}
else {
   $loc = "http://".$_SERVER["HTTP_HOST"]."/pagewithemailform.php?error=nocaptcha";
   header("Location: ".$loc);
}

?>

 

by: mplungjanPosted on 2009-08-13 at 07:28:17ID: 25088608

No

I want you to save your current page and REPLACE the page with what is in the snippet under my last post
Then make sure the parts of that snippet I have mentioned IN the post have been changed to reflect your system, e.g. pagewithemailform.php is changed to whatever you called your page - also put the javascript into that email page so it can handle the error message

 

by: sobeservices2Posted on 2009-08-13 at 08:07:09ID: 25089176

I received this message

"Fatal error: Call to undefined function isoldversion() in /home/bcpba/public_html/test.html on line 303"

// --------------------------- INSERTION OF RECAPTCHA PART 3
 
// ending with this redirect
 
    if ($landing_page != ""){
      header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
    } else {
      header("Location: http://".$_SERVER["HTTP_HOST"]."/");
    }
  }
  else {
    # set the error code so that we can display it
    $error = $resp->error;
    $loc = "http://".$_SERVER["HTTP_HOST"]."/formmail.php?error=".$error;
    header("Location: ".$loc);
  }
}
else {
    $loc = "http://".$_SERVER["HTTP_HOST"]."/formmail.php?error=nocaptcha";
    header("Location: ".$loc);
}
 

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: mplungjanPosted on 2009-08-13 at 23:03:48ID: 25095543

I have uppercase Is
$bUseOldVars = IsOldVersion($aPHPVERSION);

and I find it...

Perhaps time to call in the cavalry.

 

by: mplungjanPosted on 2009-08-14 at 01:04:07ID: 25095968

Sorry. I do not do IM

I have requested attention from PHP

 

by: b0lsc0ttPosted on 2009-08-14 at 16:56:46ID: 25103292

What happened after you corrected the typo?  The function does indeed start with a captial I in Mplungjan's code so that should get rid of the error you got.  PHP is case sensitive.

bol

 

by: sobeservices2Posted on 2009-08-19 at 10:29:34ID: 31617751

The reason I am closing this is that I ended up using a script that implemented iframe and it was confusing to get this project completed with what I was given. No easy solution . The solution I came was really a work around and to use an existing form generator that already had the rechaputre in it

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...