Location: PHPKode > projects > FiForms Framework > FiForms/scripts/designform.php
<?php
/**
*******************************************************************************

    FiForms -- A collection of PHP classes designed 
    to facilitate rapid development of web-database software

    Copyright (C) 2003-2008  Daniel McFeeters

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


    The original author of this library can be contacted at the following 
    address:

    Daniel McFeeters
    182 Baker Rd.
    Faubush, KY 42544-6526
    email:databases [at] fiforms [dot] org
    http://www.fiforms.org/

Project Started May 4, 2003
*******************************************************************************
designform.php

Note: Although this program is licensed under the GPL, certain specified templates contained in this program, and the output of this program which
reflects the contents of the specified template, are specifically released 
into the public domain by the authors of this program. Such templates will
be clearly marked in this source code by a notice similar to the following:

       * The following template is released into the public domain *

*******************************************************************************
**/
require_once('localconfig.php');
$checkpass = true;
require_once("authenticate.php");
require_once($FIFORMS_CONFIG['INCLUDE_PATH'].'FiConnect_MySQL.inc.php');
require_once($FIFORMS_CONFIG['AUTH_MODULE']);
//print_r($FIFORMS_CONFIG);die();
$con = new FiConnect_MySQL();
$con->server = $FIFORMS_CONFIG['DEFAULT_SERVER'];
$con->auth = new FiFormsAuth();

$database = $_POST['database'];
if($database == "**Select a Database**")
{
    $database = "";
}
if(!$database)
{
    $database = $FIFORMS_CONFIG['AVAILABLE_APP_INFO'][$_GET['app']]['appdatabase'];
}
$con->default_db = $database;
$con->list_dbs();
$dbList =  $con->formatResult("<option>**Select a Database**</option>","<option>%Database%</option>","");
$dbList = str_replace("<option>$database</option>","<option selected=\"selected\">$database</option>",$dbList);
$app = htmlentities($_GET['app']);

if(!$database)
{
promptPage("Select Database",<<<EOD
    <form action="designform.php?app=$app" method="post">
    <fieldset>
    <input type="hidden" name="password" value="$_POST[password]" />
    Select a database: 
    <select name="database" id="database">
    $dbList
    </select>
    <br />
    <input type="submit" value="Next -&gt;" />
    </fieldset>
    </form>
EOD
,"2%","2%","98%");
die();
}
else if(!$_POST['table'] || $_POST['table'] == '**Select a Table**')
{
        $con->query("SHOW TABLES");
        $tableList =  $con->formatResult("<select name=\"table\" id=\"table\"
         onchange=\"document.forms[0].filename.value = this.value + '.xml';\"><option>**Select a Table**</option>","<option>%Tables_in_".$database."%</option>","</select>");

        $menuList = "<select name=\"menu\">";
        // get directory listing of all menu xml files
        $dir = $FIFORMS_CONFIG['MENU_PATH'];
        if (is_dir($dir)) 
        {
            if ($dh = opendir($dir)) 
            {
                while (($file = readdir($dh)) !== false) 
                {
                    if(strpos($file,'.xml'))
                    {
                        $sel = ($file == 'main.xml') ? ' selected="selected"':'';
                        $menuList .= "<option$sel>$file</option>";
                    }
                }
                closedir($dh);
            }
        }

        $menuList .= "<option value=\"\">{none}</option></select>";
promptPage("Create Form",<<<EOD
    <form action="designform.php?app=$app" method="post" id="paramform">
    <input type="hidden" name="password" value="$_POST[password]" />
    <input type="hidden" name="database" value="$_POST[database]" />
    <table>
    <tr><th>
    Choose Database:</th><td>
        <select name="database" id="database"  onchange="document.getElementById('table').value = '**Select a Table**';document.getElementById('paramform').submit();">
     $dbList 
    </select>
    </td></tr>
    <tr><th>Select a table:</th><td> $tableList </td></tr>
    <tr><th>&nbsp;</th><td>Note: FiForms will use the field comment for the field caption if one is specified in the database.</td></tr>
    <tr><th>Filename to save form as:</th><td>
    $FIFORMS_CONFIG[XML_PATH]
    <input name="filename" />
    </td></tr><tr><th>
    Namespace Prefix:</th>
    <td><select name="prefix" id="prefix">
      <option value="fiform">fiform:</option>
      <option value="" selected="selected">{none}</option>
    </select></td></tr>
    <tr><th>Add to Menu:</th><td>$menuList</td>
    </tr>
    <tr><td>&nbsp;</td><td>
    <input type="submit" value="Create Form" />
    </td>
    </tr>
    </table>
    </form>
    </body>
</html>
EOD
,"2%","2%","98%");
die();

}
else
{
    $con->query("SHOW FULL COLUMNS FROM ".$_POST['table'].";");
    $server = $FIFORMS_CONFIG['DEFAULT_SERVER'];
    $db = $database;
    $filename = $_POST['filename'];
    $formtitle = str_replace('.xml','',$filename).' Form';
    $dbOptions = 
        ($database != $FIFORMS_CONFIG['AVAILABLE_APP_INFO'][$app]['appdatabase']) 
        ? ('db="'.$database.'" ') : '';
    $table = $_POST['table'];
    $prefix = $_POST['prefix'];
    $date = date('l, F j, Y \a\t h:i A');
    $dtd = ($prefix == "") ? "fi.dtd" : "FiForm.dtd";
    $xmlversion = $FIFORMS_CONFIG['XML_VERSION'];
    $stripversion = str_replace('.','',$xmlversion);
    $doctype = ($prefix == "") ? "fiform" : "fiform:fiform";
    $xmlns = ($prefix == "") ? 
'xmlns="http://xml.fiforms.org/FiForms/"' 
  : 
'xmlns="http://www.w3.org/1999/xhtml" xmlns:'.$prefix.'="http://xml.fiforms.org/FiForms/"';
    $dtddeclare = <<<EOD
<!DOCTYPE $doctype PUBLIC "-//FIFORMS//DTD FIFORMDEF $xmlversion//EN" "http://xml.fiforms.org/dtd/$stripversion/$dtd">

EOD;

    /* The following template is released into the public domain */
    $form = <<<EOD
<?xml version="1.0" encoding="ISO-8859-1"?>
$dtddeclare
<$prefix:fiform $xmlns version="$xmlversion"
        window="$table" 
        width="500" 
        height="400" 
        location="no" 
        menubar="no" 
        resizable="yes" 
        scrollbars="yes" 
        toolbar="no" 
        whichControls="all" 
        ctlPosition="bottom" 
        svctlPosition="right" 
        viewsAllowed="both" 
        defaultView="sheet"
        allowInsert="yes" 
        insert="current"
        recordLimit="20" >
<$prefix:title>$formtitle</$prefix:title>
<$prefix:summary>Form to edit $table table. Created $date.</$prefix:summary>
<$prefix:connect update="$table" $dbOptions/>


EOD;
        
        while($arr = $con->fetch_array())
       {
           $digits = 0;
           $decimals = 0;
           if(strpos($arr['Type'],'('))
           {
               $shortType = substr($arr['Type'],0,strpos($arr['Type'],'('));
               $digits = (int)substr($arr['Type'],strpos($arr['Type'],'(')+1);
               $decimals = (int)substr($arr['Type'],strpos($arr['Type'],',')+1);
           }
           else
           {
               $shortType = $arr['Type'];
           }
           $field = $arr['Field'];
           $caption = $arr['Comment'];
           if(!$caption)
           {
               $caption = $arr['Field'];
           }
           switch($shortType)
           {
               case "date":
                   $form .= "        <$prefix:iDateText caption=\"$caption\" field=\"$field\" />\n";
                   break;
               case "datetime":
               case "timestamp":
                   $form .= "        <$prefix:iDateTime caption=\"$caption\" field=\"$field\" />\n";
                   break;
               case "enum":
                   $form .= "        <$prefix:iDBSelect caption=\"$caption\" field=\"$field\">\n";
                   $enumOptions = explode("','",substr($arr['Type'],strpos($arr['Type'],'(')));
                   foreach($enumOptions as $option)
                   {
                       $optValue = str_replace(array("'",")","("),'',$option);
                       $form .= "          <$prefix:option>$optValue</$prefix:option>\n";
                   }
                   $form .= "        </$prefix:iDBSelect>\n";
                   break;
               case "text":
                   $form .= "        <$prefix:iTextArea caption=\"$caption\" field=\"$field\" rows=\"8\" cols=\"40\" />\n";
                   break;
               case "decimal":
               case "int":
                   if($digits == 0)
                    {
                        $digits = 11;
                    }
                   $form .= "        <$prefix:iNumber caption=\"$caption\" field=\"$field\" digits=\"$digits\" decimals=\"$decimals\" />\n";
                   break;
               case "tinyint":
                   $form .= "        <$prefix:iCheck caption=\"$caption\" field=\"$field\" />\n";
                   break;
               case "varchar":
               default:
                   $maxlength = $digits;
                   $size = $maxlength*2;
                   if($size > 80)
                   {
                        $size = 80;
                   }
                   $maxlengthtag = $maxlength ? ("maxlength=\"$maxlength\" ") : ("");
                   $form .= "        <$prefix:iText caption=\"$caption\" field=\"$field\" size=\"$size\" $maxlengthtag/>\n";
           }
       }
                $form .= "\n</$prefix:fiform>";
           // get rid of colon if there's no prefix
           if($prefix === "")
           {
               $form = str_replace("<:","<",$form);
               $form = str_replace("</:","</",$form);
}
            $app = htmlentities($_GET['app']);
$pwhash = sha1($_POST['password']);
$optionList = <<<EOD
          <ul>
          <li><a href="viewform.php?app=$app&amp;formname=$filename" target="_blank">Open the Form $filename to view and enter data</a></li>
          <li><a href="javascript:document.getElementById('designformform').submit()">Create Another Form</a></li>
          <li><a href="list.php?app=$app&amp;index=maintenance.xml">Return to Maintenance Menu</a></li>
          </ul>
          <form action="editform.php?app=$app&amp;form=$filename" method="post" id="editformform">
          <input type="hidden" name="pwhash" value="$pwhash" />
          </form>
          <form action="designform.php?app=$app" method="post" id="designformform">
          <input type="hidden" name="password" value="$_POST[password]" />
          </form>
EOD;
       if(@file_put_contents($FIFORMS_CONFIG['XML_PATH'].$filename,$form))
       {
            if($_POST['menu'] && file_exists($FIFORMS_CONFIG['MENU_PATH'].$_POST['menu']) && preg_match('/^[a-zA-Z0-9_]+\.xml$/',$_POST['menu']))
            {
                $doc = new DOMDocument();
                $doc->load($FIFORMS_CONFIG['MENU_PATH'].$_POST['menu']);
                $listelement = $doc->getElementsByTagName('reports')->item(0);
                $formlist = $doc->getElementsByTagName('form');
                $lastform = $formlist->item($formlist->length - 1);
                $newEntry = $doc->createElement('form');
                $newEntry->setAttribute('href',$filename);
                if($lastform && $lastform->nextSibling)
                {
                    $listelement->insertBefore($newEntry,$lastform->nextSibling);
                }
                elseif($lastform)
                {
                    $listelement->appendChild($newEntry);
                }
                elseif($listelement->firstChild)
                {
                    $firstLink = $listelement->firstChild;
                    $done = false;
                    while($firstLink->tagName != 'rpt' && $firstLink->tagName != 'list' && $firstLink->tagName != 'link')
                    {

                        if($firstLink->nextSibling)
                        {
                            $firstLink = $firstLink->nextSibling;
                        }
                        else
                        {
                            $listelement->appendChild($newEntry);
                            $done = true;
                            break;
                        }
                    }
                    if(!$done)
                    {
                        $listelement->insertBefore($newEntry,$firstLink);
                    }
                }
                else
                {
                    $listelement->appendChild($newEntry);
                }
                file_put_contents($FIFORMS_CONFIG['MENU_PATH'].$_POST['menu'],$doc->saveXML());
                //echo $doc->saveXML();
            }
            $app = htmlentities($_GET['app']);
            promptPage("Form Saved",<<<EOD
          <p>Form successfully created and saved to:<br /><b>
            $FIFORMS_CONFIG[XML_PATH]$_POST[filename]</b></p>
          <p>Please use your favorite text editor to customize this form for your application. Specifically, you likely need to remove the element if you use auto-generate primary keys and add the iDBSelect elements for all foreign key relationships.</p>
            $optionList
EOD
,"2%","2%","96%");
       }
       else
       {
            $code = htmlentities($form);
            promptPage("Displaying Form Code",<<<EOD
          <p>The webserver process could not write to the file:<br /><b>
            $FIFORMS_CONFIG[XML_PATH]$_POST[filename]</b><br /><br /> It is likely that the webserver does not have permissions to write to this path, or that the path does not exist. <br /><br /><b>Please create the file specified above with the text editor of your choice</b>, and copy and paste the following code into it:</p>
            <pre style="background-color: #ffffff; border-color: #000000; border-width: 1px; border-style: solid; color: #000088; margin: 30px;">
$code
</pre>
            $optionList
EOD
,"2%","2%","96%");
       }

}
 ?>
Return current item: FiForms Framework