JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Fix db_get_value after mysql->mysqli upgrade
[wfpl.git] / metaform.php
1 <?php
2
3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
7
8
9 # This file writes the code for you (sql, php, html, email) to handle a form.
10
11 require_once(__DIR__.'/'.'template.php');
12 require_once(__DIR__.'/'.'http.php');
13 require_once(__DIR__.'/'.'tar.php');
14 require_once(__DIR__.'/'.'format.php');
15
16 # see wfpl/metaform/template.html for the html templates for these elements
17 $GLOBALS['types'] = array(
18 #    type                  input          format        sql     
19         'varname' =>    array('textbox',     'varname',    'varchar(50) binary'),
20         'name' =>       array('textbox',     'oneline',    'varchar(200) binary'),
21         'textbox' =>    array('textbox',     'oneline',    'varchar(200) binary'),
22         'int' =>        array('textbox',     'int',        'int'),
23         'decimal' =>    array('textbox',     'decimal',    'decimal(12,2)'),
24         'bigint' =>     array('textbox',     'int',        'varchar(100) binary'), # up to 100 digits, stored as a string
25         'zip' =>        array('textbox',     'zip',        'varchar(20) binary'),
26         'email' =>      array('email',       'email',      'varchar(100) binary'),
27         'search' =>     array('search',      'oneline',    'varchar(200) binary'),
28         'phone' =>      array('textbox',     'phone',      'varchar(32) binary'),
29         'state' =>      array('states',      'oneline',    'varchar(2) binary'),
30         'money' =>      array('textbox',     'money',      'varchar(32) binary'),
31         'date' =>       array('date',        'mdy_to_ymd', 'char(10) binary'),
32         'dollars' =>    array('textbox',     'dollars',    'varchar(32) binary'),
33         'url' =>        array('textbox',     'url',        'varchar(200) binary'),
34         'hidden' =>     array('hidden',      'unix',       'varchar(200) binary'),
35         'password' =>   array('password',    'oneline',    'varchar(200) binary'),
36         'textarea' =>   array('textarea',    'unix',       'text binary'),
37         'html' =>       array('html',        'unix',       'mediumtext binary'),
38         'pulldown' =>   array('pulldown',    'options',    'varchar(100) binary'),
39         'radio' =>      array('radio',       'options',    'varchar(100) binary'),
40         'checkbox' =>   array('checkbox',    'bool',       'int(1)'),
41         'yesno' =>      array('checkbox',    'yesno',      'varchar(3) binary'),
42         'delete' =>     array('checkbox',    'yesno',      'n/a'),
43         'image' =>      array('image',       'oneline',    'varchar(120) binary'),
44         'thumb' =>      array('image',       'oneline',    'varchar(240) binary'),
45         'file' =>       array('file',        'oneline',    'varchar(100) binary'),
46         'submit' =>     array('submit',      'n/a',        'n/a'),
47         '{' =>          array('fieldset',    'n/a',        'n/a'),
48         '}' =>          array('end_fieldset','n/a',        'n/a')
49 );
50
51 function list_available_types() {
52         ksort($GLOBALS['types']);
53         foreach($GLOBALS['types'] as $key => $value) {
54                 tem_set('type', $key);
55                 tem_show('types');
56                 tem_show('types_sep');
57         }
58 }
59
60
61 function tem_set_globals(&$tem) {
62         $vars = array(
63                 'file_name',
64                 'public_file_name',
65                 'table_name',
66                 'plural',
67                 'singular');
68         foreach($vars as $var) {
69                 $tem->set($var, $GLOBALS[$var]);
70         }
71
72         $bools = array(
73                 'opt_email',
74                 'opt_db',
75                 'opt_listing',
76                 'opt_display',
77                 'opt_pass',
78                 'opt_public_form',
79                 'opt_public_display',
80                 'opt_public_something');
81         foreach($bools as $bool) {
82                 if(isset($GLOBALS[$bool]) && $GLOBALS[$bool]) {
83                         $tem->set($bool);
84                 }
85         }
86 }
87
88 function metaform_main() {
89         if(isset($_REQUEST['singular'])) {
90                 $GLOBALS['file_name'] = format_varname(_REQUEST_cut('file_name'));
91                 $GLOBALS['table_name'] = format_varname(_REQUEST_cut('table_name'));
92                 $GLOBALS['plural'] = format_oneline(_REQUEST_cut('plural'));
93                 # backwards compatibility:
94                 if(isset($_REQUEST['form_name'])) {
95                         $GLOBALS['file_name'] = $GLOBALS['table_name'] = $GLOBALS['plural'] = format_varname(_REQUEST_cut('form_name'));
96                 }
97
98                 $GLOBALS['singular'] = format_oneline(_REQUEST_cut('singular'));
99                 $GLOBALS['opt_email'] = format_bool(_REQUEST_cut('opt_email'));
100                 $GLOBALS['opt_db'] = format_bool(_REQUEST_cut('opt_db'));
101                 $GLOBALS['opt_listing'] = format_bool(_REQUEST_cut('opt_listing'));
102                 $GLOBALS['opt_display'] = format_bool(_REQUEST_cut('opt_display'));
103                 $GLOBALS['opt_pass'] = format_bool(_REQUEST_cut('opt_pass'));
104                 $GLOBALS['opt_public_form'] = format_bool(_REQUEST_cut('opt_public_form'));
105                 $GLOBALS['opt_public_display'] = format_bool(_REQUEST_cut('opt_public_display'));
106
107                 $GLOBALS['public_file_name'] = $GLOBALS['file_name'];
108                 if($GLOBALS['opt_public_form'] || $GLOBALS['opt_public_display']) {
109                         $GLOBALS['opt_public_something'] = 1;
110                         $GLOBALS['file_name'] = $GLOBALS['file_name'] . _admin;
111                 } else {
112                         $GLOBALS['opt_public_something'] = 0;
113                 }
114
115                 tem_init();
116                 tem_set_globals($GLOBALS['wfpl_template']);
117         }
118
119         if(isset($_REQUEST['fields'])) {
120                 if(isset($_REQUEST['view_sql'])) {
121                         view_sql();
122                         exit();
123                 } elseif(isset($_REQUEST['view_php'])) {
124                         view_php();
125                         exit();
126                 } elseif(isset($_REQUEST['view_html'])) {
127                         view_html();
128                         exit();
129                 } elseif(isset($_REQUEST['view_email'])) {
130                         view_email();
131                         exit();
132                 } elseif(isset($_REQUEST['download_tar'])) {
133                         download_tar();
134                         exit();
135                 } elseif(isset($_REQUEST['preview'])) {
136                         preview();
137                         exit();
138                 } elseif(isset($_REQUEST['edit'])) {
139                         tem_set('fields', $_REQUEST['fields']);
140                         # fall through
141                 } else {
142                         die("Sorry... couldn't tell which button you pressed");
143                 }
144         }
145
146
147         set_form_action();
148         tem_load(__DIR__.'/'.'metaform/main.html');
149         list_available_types();
150         tem_output();
151         exit(); # in case we're being called by wfpl_main or something
152 }
153
154
155 function field_input($type)  { return $GLOBALS['types'][$type][0]; }
156 function field_format($type) { return $GLOBALS['types'][$type][1]; }
157 function field_sql($type)    { return $GLOBALS['types'][$type][2]; }
158
159 function get_fields() {
160         # no sense in doing all this so many times
161         if(isset($GLOBALS['gotten_fields'])) {
162                 return $GLOBALS['gotten_fields'];
163         }
164
165         $fields_str = unix_newlines($_REQUEST['fields']);
166         $GLOBALS['gotten_fields'] = array();
167         $fields_str = rtrim($fields_str);
168         $fields = explode("\n", $fields_str);
169         foreach($fields as $field) {
170                 $first_char = substr($field, 0, 1);
171                 $field = trim($field);
172                 if ($first_char === ' ' || $first_char === "\t") {
173                         $i = count($GLOBALS['gotten_fields']);
174                         if($i > 0) {
175                                 $i -= 1;
176                                 if (!$GLOBALS['gotten_fields'][$i]['options']) {
177                                         $GLOBALS['gotten_fields'][$i]['options'] = array();
178                                 }
179                                 $GLOBALS['gotten_fields'][$i]['options'][] = $field;
180                                 continue;
181                         }
182                 }
183                 if(substr($field, -1) == '{') {
184                         $caption = trim(substr($field, 0, -1));
185                         $name = format_varname($caption);
186                         $type = '{';
187                         $options = null;
188                 } else {
189                         $options = null;
190                         $type = null;
191                         $div = strpos($field, ' ');
192                         if ($div === false) {
193                                 $div = strpos($field, "\t");
194                         }
195                         if ($div === false) {
196                                 if (isset($GLOBALS['types'][$field])) {
197                                         # if just one word, and it's a type, use it as name/caption and type
198                                         $type = $field;
199                                 }
200                         } else {
201                                 $first_word = trim(substr($field, 0, $div));
202                                 if (isset($GLOBALS['types'][$first_word])) {
203                                         # if the first word (of multiple) is a type, remove it from the name/caption
204                                         $type = $first_word;
205                                         $field = trim(substr($field, $div + 1));
206                                 }
207                         }
208                         # see if there's an explicit name/caption splitter
209                         $div = strpos($field, '|');
210                         if ($div !== false) {
211                                 $name = trim(substr($field, 0, $div));
212                                 $caption = trim(substr($field, $div + 1));
213                                 if (isset($GLOBALS['types'][$name])) {
214                                         $type = $name;
215                                 } elseif (isset($GLOBALS['types'][strtolower($caption)])) {
216                                         $type = strtolower($caption);
217                                 }
218                         } else {
219                                 $name = format_varname($field);
220                                 $caption = format_caption($field);
221                         }
222
223                         if ($type === null) {
224                                 $type = 'textbox';
225                         }
226                 }
227                 $input = field_input($type);
228                 $format = field_format($type);
229                 $sql = field_sql($type);
230                 $GLOBALS['gotten_fields'][] = array(
231                         'caption' => $caption,
232                         'name' => $name,
233                         'type' => $type,
234                         'input' => $input,
235                         'format' => $format,
236                         'sql' => $sql,
237                         'options' => $options
238                 );
239         }
240
241         return $GLOBALS['gotten_fields'];
242 }
243
244 # this one, that you're using to create forms
245 function set_form_action() {
246         $action = preg_replace('|.*/|', '', $_SERVER['REQUEST_URI']);
247         if($action == '') $action = './';
248         tem_set('form_action', $action);
249 }
250
251 # perfect HTTP headers for viewing created files
252 function view_headers() {
253         header('Content-type: text/plain');
254 }
255         
256
257
258
259 function make_sql() {
260         $tem = new tem();
261         $tem->load(__DIR__.'/'.'metaform/template.sql');
262         tem_set_globals($tem);
263         $fields = get_fields();
264         foreach($fields as $field) {
265                 if($field['sql'] != 'n/a') {
266                         $tem->set('name', $field['name']);
267                         $tem->set('type', $field['sql']);
268                         if(substr($field['sql'], 0, 3) == 'int' || substr($field['sql'], 0, 7) == 'decimal') {
269                                 $tem->set('default', '0');
270                         } elseif($field['format'] == 'yesno') {
271                                 $tem->set('default', '"No"');
272                         } else {
273                                 $tem->set('default', '""');
274                         }
275                         $tem->show('column');
276                 }
277         }
278         view_headers();
279         return $tem->run();
280 }
281
282 function view_sql() {
283         view_headers();
284         echo make_sql();
285 }
286
287 # always_field is a form field that always submits (unlike say, checkboxes). It's used to detect if the form has submitted or not.
288 function find_always_field(&$fields) {
289         foreach($fields as $field) {
290                 if($field['input'] != 'submit' && $field['input'] != 'image' && $field['input'] != 'file' && $field['input'] != 'checkbox' && $field['input'] != 'radio' && $field['type'] != '{' && $field['type'] != '}') {
291                         return $field['name'];
292                 }
293         }
294
295         return 'FIXME';
296 }
297         
298         
299
300 # pass false if you want to exclude the <head> and <body> tag etc.
301 function make_html($whole_file = true) {
302         $has_html_editors = false;
303         $tem = new tem();
304         $tem->load(__DIR__.'/'.'metaform/template.html');
305         tem_set_globals($tem);
306         $fields = get_fields();
307         $tem->set('always_field', find_always_field($fields));
308         $hidden_fields = array();
309         $visible_fields = array();
310         $display_fields = array();
311         $listing_headers = array();
312         $listing_fields = array();
313         foreach($fields as $field) {
314                 if($field['input'] == 'hidden') {
315                         $hidden_fields[] = array('name' => $field['name']);
316                 } else {
317                         $visible_fields[] = array(
318                                 $field['input'] => array(
319                                         'name' => $field['name'],
320                                         'caption' => $field['caption']
321                                 )
322                         );
323                         if($field['type'] == 'radio') {
324                                 $i = 0;
325                                 $opts = array();
326                                 foreach ($field['options'] as $row) {
327                                         if (is_array($row)) {
328                                                 $cap = $row[1];
329                                         } else {
330                                                 $cap = $row;
331                                         }
332                                         $opts[] = array('i' => $i, 'option_caption' => $cap);
333                                         $i += 1;
334                                 }
335                                 $visible_fields[count($visible_fields) - 1]['options'] = $opts;
336                         }
337                 }
338
339                 if($field['input'] == 'image' || $field['input'] == 'file') {
340                         $tem->set('uploads');
341                         $tem->set('enctype_attr', '" enctype="multipart/form-data');
342                 } elseif($field['input'] == 'html') {
343                         $has_html_editors = true;
344                         $tem->set('html_field_name', $field['name']);
345                         $tem->set('replace_textarea');
346                 }
347
348                 switch($field['input']) {
349                         case 'image':
350                         case 'checkbox':
351                         case 'date':
352                         case 'textarea':
353                         case 'html':
354                                 $display_type = $field['input'];
355                         break;
356                         default:
357                                 $display_type = 'short';
358                 }
359                 if($field['format'] != 'n/a') {
360                         $display_fields[] = array($display_type => array(
361                                 'name' => $field['name'], 'caption' => $field['caption']));
362                 }
363
364                 if(show_in_listing($field['type'], $field['input'], $field['format'], $field['sql'])) {
365                         $listing_headers[] = array(
366                                 'caption' => $field['caption'],
367                                 'name' => $field['name']
368                         );
369                         $listing_field = array(
370                                 'name' => $field['name']
371                         );
372                         if($field['format'] == 'bool' || $field['format'] == 'yesno') {
373                                 $listing_field['enc'] = 'yesno';
374                         } elseif($field['input'] == 'date') {
375                                 $listing_field['enc'] = 'mmddyyyy';
376                         } elseif($field['type'] == 'thumb') {
377                                 $listing_field['thumb'] = true;
378                         } else {
379                                 $listing_field['enc'] = 'html';
380                         }
381                         $listing_fields[] = $listing_field;
382                 }
383         }
384
385         # Submit/Send button
386         if($GLOBALS['opt_email'] == 'Yes' && !$GLOBALS['opt_db']) {
387                 $visible_fields[] = array('submit' => array(
388                         'name' => 'send',
389                         'caption' => 'Send'));
390         } else {
391                 $visible_fields[] = array('submit' => array(
392                         'name' => 'save',
393                         'caption' => 'Save'));
394         }
395
396         $form_fields = array();
397         $form_fields['visible_fields'] = $visible_fields;
398         if($hidden_fields) {
399                 $form_fields['hidden_fields'] = $hidden_fields;
400         }
401         $tem->set('form', $form_fields);
402
403         # opt_display and opt_listing control whether these are actually displayed
404         $tem->set('display_fields', $display_fields);
405         $tem->set('listing_headers', $listing_headers);
406         $tem->set('listing_fields', $listing_fields);
407
408
409         if($has_html_editors) {
410                 $tem->set('html_editor_headers');
411         }
412
413         if($whole_file) {
414                 return $tem->run();
415         } else {
416                 $tem2 = new tem();
417                 $tem2->load_str('<!--~form~-->');
418                 $tem2->merge($tem);
419                 return $tem2->run();
420         }
421 }
422
423 function view_html() {
424         view_headers();
425         echo make_html();
426 }
427
428 function show_in_listing($type, $input, $format, $sql) {
429         switch($input) {
430                 case 'submit':
431                 case 'hidden':
432                 case 'password':
433                 case 'textarea':
434                 case 'html':
435                 case 'fieldset':
436                 case 'end_fieldset':
437                         return false;
438         }
439         if($type == 'image') {
440                 return false;
441         }
442
443         return true;
444 }
445
446 function pulldown_options_array($options) {
447         if($options) {
448                 $pulldown_options = array();
449                 foreach($options as $option) {
450                         $option = preg_replace("/['\\\\]/", '\\\\$0', $option);
451                         $pulldown_options[] = "'$option'";
452                 }
453                 $pulldown_options = 'array(' . join(', ', $pulldown_options) . ')';
454         } else {
455                 $pulldown_options = "array(array('op1', 'Option One'), array('op2', 'Option Two'), 'n/a')";
456         }
457
458         return $pulldown_options;
459 }
460
461 function make_php() {
462         $has_html_editors = false;
463         $tem = new tem();
464         $tem->load(__DIR__.'/'.'metaform/template.php');
465         tem_set_globals($tem);
466         $fields = get_fields();
467         $db_fields = '';
468         $always_field = find_always_field($fields);
469         $image_included_yet = false;
470         $name_to_caption = array();
471         $has_uploads = false;
472         foreach($fields as $field) {
473                 $name_to_caption[] = array('name' => $field['name'], 'caption' => $field['caption']);
474                 if($field['input'] != 'submit') {
475                         $tem->set('format', $field['format']);
476                         $tem->set('name', $field['name']);
477                         $tem->set('db_field', ''); # we don't want to use the value from last time
478                         if($field['sql'] != 'n/a') {
479                                 if($db_fields != '') $db_fields .= ',';
480                                 $db_fields .= $field['name'];
481                         }
482                         if($field['input'] == 'image') {
483                                 if($field['type'] == 'thumb') {
484                                         $tem->show('thumb_settings');
485                                         $tem->show('thumb_upload_params');
486                                         $tem->show('thumb_w_h');
487                                 }
488                                 $tem->show('image_settings');
489                                 $tem->show('image_upload');
490                                 $has_uploads = true;
491                         } else if($field['input'] == 'file') {
492                                 $tem->show('file_settings');
493                                 $tem->show('file_upload');
494                                 $has_uploads = true;
495                         } else {
496                                 if($field['input'] == 'html') {
497                                         $has_html_editors = true;
498                                 } elseif($field['input'] == 'pulldown' || $field['input'] == 'radio') {
499                                         $pulldown_options = pulldown_options_array($field['options']);
500                                         $tem->set('pulldown_options', $pulldown_options);
501                                         $tem->set('has_pulldowns');
502                                         $tem->show('pulldowns');
503                                         $tem->show('pulldown_format_extra');
504                                 }
505                                 if($field['format'] != 'n/a') {
506                                         $tem->show('formats');
507                                 }
508                         }
509                 }
510
511                 if($GLOBALS['opt_listing']) {
512                         if(show_in_listing($field['type'], $field['input'], $field['format'], $field['sql'])) {
513                                 $tem->show('listing_fields_1');
514                                 $tem->show('listing_fields_2');
515                         }
516                 }
517         }
518
519         $tem->set('name_to_caption', $name_to_caption);
520
521         if($has_uploads) {
522                 $tem->show('uploads_include');
523                 $tem->show('upload_max');
524                 $tem->show('upload_settings');
525                 $image_included_yet = true;
526         }
527
528         if($has_html_editors) {
529                 $tem->show('show_extra_headers');
530         }
531
532         $tem->set('always_field', $always_field);
533         $tem->set('db_fields', $db_fields);
534         $tem->set('metaform_url', edit_url());
535         if($GLOBALS['opt_email']) {
536                 $this_domain = $_SERVER['HTTP_HOST'];
537                 if(substr($this_domain, -2) == '.l') {
538                         $this_domain = substr($this_domain, 0, -1) . 'com';
539                 }
540                 $tem->set('this_domain', $this_domain);
541         }
542         return $tem->run();
543 }
544
545 # make a URL for the edit page with all the fields filled in
546 function edit_url() {
547         $url = this_url();
548         $url = preg_replace('|view_php=[^&]*|', 'edit=yes', $url);
549         $url = preg_replace('|download_tar=[^&]*|', 'edit=yes', $url);
550         $url = preg_replace('|/[a-z0-9_.]*\?|', '/?', $url);
551         return $url;
552 }
553
554 function view_php() {
555         view_headers();
556         echo make_php();
557 }
558
559 function make_email() {
560         $tem = new tem();
561         $tem->load(__DIR__.'/'.'metaform/template.email.txt');
562         tem_set_globals($tem);
563         $fields = get_fields();
564         foreach($fields as $field) {
565                 $tem->set('name', $field['name']);
566                 $tem->set('caption', $field['caption']);
567                 if($field['type'] == 'textarea') {
568                         $tem->show('multi_line');
569                 } elseif($field['type'] == 'checkbox') {
570                         $tem->show('checkbox');
571                 } else {
572                         $tem->show('normal');
573                 }
574                 $tem->show('fields');
575         }
576         return $tem->run();
577 }
578
579 function make_htaccess() {
580         $tem = new tem();
581         $tem->set('form', $GLOBALS['file_name']);
582         return $tem->run(__DIR__.'/'.'metaform/htaccess');
583 }
584
585 function view_email() {
586         view_headers();
587         echo make_email();
588 }
589
590 function preview() {
591         tem_load(__DIR__.'/'.'metaform/preview.html');
592         tem_set_globals($GLOBALS['wfpl_template']);
593         tem_set('fields', $_REQUEST['fields']);
594         $preview_tem = new tem();
595         $preview_tem->load_str(make_html(false));
596         if($GLOBALS['opt_db']) {
597                 $preview_tem->show('new_msg');
598         }
599         $fields = get_fields();
600         foreach($fields as $field) {
601                 if($field['type'] == 'pulldown' || $field['type'] == 'radio') {
602                         pulldown($field['name'], eval('return ' . pulldown_options_array($field['options']) . ';'));
603                 }
604         }
605         $preview = $preview_tem->run();
606         unset($preview_tem);
607         $preview = preg_replace('|type="submit"|', 'type="submit" disabled="disabled"', $preview);
608         tem_set('preview', $preview);
609         tem_show('hiddens');
610         set_form_action();
611         tem_output();
612 }
613
614 function download_tar() {
615         $admin_name = $GLOBALS['file_name'];
616         $nice_name = $GLOBALS['public_file_name'];
617         $files = array(
618                 "README" => "These files are meant to work with wfpl.\n\nSee: http://sametwice.com/wfpl\n",
619                 ".htaccess" => make_htaccess(),
620                 "config.php" => "<?php\n\n# put your site-wide configuration here\n",
621                 "wfpl_main.php" => read_whole_file(__DIR__.'/'.'metaform/wfpl_main.php'),
622                 "styl.styl" => read_whole_file(__DIR__.'/'.'metaform/styl.styl'),
623                 "template.html" => read_whole_file(__DIR__.'/'.'metaform/site-template.html'),
624                 "$admin_name.html" => make_html(),
625                 "$admin_name.php" => make_php());
626         if($GLOBALS['opt_public_something']) {
627                 $files["$nice_name.html ->"] = "$admin_name.html";
628                 $files["$nice_name.php ->"] = "$admin_name.php";
629         }
630         if($GLOBALS['opt_db']) {
631                 $files["$nice_name.sql"] = make_sql();
632         }
633         if($GLOBALS['opt_email']) {
634                 $files["$nice_name.email.txt"] = make_email();
635         }
636         make_tar($nice_name, $files);
637 }