options = $_options; if(isset($_REQUEST['sppl_field_id'])){ $this->field_id = (int)$_REQUEST['sppl_field_id']; } else { if(isset($_GET['field_id'])){ $this->field_id = (int)$_GET['field_id']; } else { $this->field_id = 0; } } //If form_id is missing and we have a field_id, get form_id from field if($this->field_id && !$options['form_id']){ $form_id = $wpdb->get_var("SELECT form_id FROM " .SUPPLEFIELDSTABLE." WHERE field_id = ".$this->field_id); } //Save options if Options form submitted if(isset($_POST['saveSuppleFormSettings'])){ $this->saveFormOptions($this->options); } //Save fields if(isset($_POST['saveSuppleField'])){ $this->saveFields($this->options); } //Delete field if(isset($_POST['deleteSuppleField'])){ $this->deleteField($this->options); } //Generate Custom Table if(isset($_POST['generateSuppleTable'])){ $this->generateCustomTable($this->options); } } // Generate the CUSTOM TABLE // - will update any changes to fields // - does not delete fields that are dropped from field list // - will create a new table if you change the Custom Table Name // - does not drop orphaned tables or delete their contents function generateCustomTable($options) { //Make sure user wants to do custom table if($options['use_custom_fields'] == 1){ $this->message .= "

Table not generated. Custom fields is selected in General Settings page.

"; $this->msgclass = 'error'; return false; } //Make sure a custom table name was specified if(!trim($options['custom_tablename'])){ $this->message .= "

Table not generated. Custom fields is selected in General Settings page.

"; $this->msgclass = 'error'; return false; } //Create or update the Custom Table global $wpdb; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); // the magic file containing dbDelta() //Get the field data $results = $wpdb->get_results("SELECT * FROM ".SUPPLEFIELDSTABLE." WHERE form_id = ".(int)$options['form_id']." ORDER BY seq;"); //Error out if there are no fields if(!$results || $wpdb->num_rows == 0){ $this->message .= "

Table generation failed. No fields to create.

"; $this->msgclass = 'error'; return false; } //Here's our Custom Table Name...Supple Forms prepends with $wpdb->prefix + sppl_ $table_name = SUPPLETABLEPREFIX.$options['custom_tablename']; /* //Drop the post_id index if already exists...else it will keep duplicating it if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name) { $sql = "ALTER TABLE ".$table_name." DROP INDEX post_id"; $wpdb->query($sql); } */ //SQL for table creation & updating $sql = "CREATE TABLE " . $table_name . " ( id INT(11) NOT NULL AUTO_INCREMENT, post_id INT(11) NOT NULL, supple_status TINYINT(1) NOT NULL default '0' "; foreach($results as $row) { if(!$row->multi_val){ $ret = $this->getFieldSQL($row); if($ret){ $sql .= $ret; } } else { //we're going to display this list so user is aware that he had multi value fields that didn't generate $multifields[] = $row->field_name; } } $sql .= " , PRIMARY KEY (id) ) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"; //Here we go....make the table.....NOW! $ret = dbDelta($sql); $this->message = "

Table created: ".$table_name; //$this->message .= "

$sql

"; if(count($multifields) > 0){ $m = implode(", ",$multifields); $this->message .= "

Fields set to multiple values (not included in table): ".$m."

"; } //Set fields to show that they have been generated $wpdb->query("UPDATE ".SUPPLEFIELDSTABLE." SET status = 1 WHERE form_id = ".(int)$options['form_id']); return true; } //return the sql for a field for the table generator function getFieldSQL($row){ switch ($row->type) { case 0 : if($row->numeric_field == 1){ $type = "DOUBLE"; } else { $type = "VARCHAR(255)"; } break; case 1 : $type = "MEDIUMTEXT"; break; case 2 : $type = "VARCHAR(255)"; break; case 3 : $type = "VARCHAR(255)"; break; case 4 : $type = "VARCHAR(255)"; break; case 5 : $type = "DATETIME"; break; case 6 : $type = "TEXT"; break; } $ret = ", ".$row->field_name." ".$type." "; return $ret; } function showMetaBoxSettings() { //Display the Admin Page form $this->printAdminPage($this->options); } function showFieldEditor() { //Display the Field Editor form $this->printEditFieldsPage($this->options, $this->field_id); } //Returns the Supple Forms - Form Settings function getFormSettings($form_id) { global $wpdb; $form_id = (int)$form_id; $options = $wpdb->get_row("SELECT * FROM ".SUPPLEFORMSTABLE ." WHERE form_id = ".$form_id, ARRAY_A); if(!$options) { $options = $this->getFormSettingsDefaults(); } return $options; } function getFormSettingsDefaults() { //defaults if nothing is in the database return array( 'form_id' => 0, 'form_title' => '', 'placement' => 'normal-sortables', 'use_custom_fields' => 1, 'custom_tablename' => '', 'post_related' => 1, 'write_page' => 1, 'hide_wp_customfields' => 1, 'seq' => 0, 'status' => 1 ); } function checkDuplicateTableName($tablename) { global $wpdb; if($wpdb->get_var($wpdb->prepare('SELECT custom_tablename FROM '.SUPPLEFORMSTABLE .' WHERE custom_tablename = %s',$tablename))){ return false;} return true; } function checkName($text) { $regex = "/^([A-Za-z0-9_]+)$/"; if (preg_match($regex, $text)) { return TRUE; } else { return FALSE; } } //Checks to see if we're saving options function saveFormOptions(&$options){ global $wpdb; //This section Saves the overall Supple Forms defaults check_admin_referer( 'update-suppleforms'); $data['form_id'] = 1; $data['form_title'] = $_POST['sppl_form_title']; $data['placement'] = (int)$_POST['sppl_placement']; $data['use_custom_fields'] = (int)($_POST['sppl_use_custom_fields']); if($data['use_custom_fields'] == 0 ){ $data['custom_tablename'] = $_POST['sppl_custom_tablename']; if(!$this->checkName($data['custom_tablename'])){ $this->message .= "

Update failed. Invalid Custom Table Name: ". $data['custom_tablename']."

"; $this->msgclass = 'error'; $this->options = $this->getFormSettings($options['form_id']); return false; } if(!$this->checkDuplicateTableName($tablename)){ $this->message .= "

Table name already exists: " .$tablename. ". Update failed.

"; $this->msgclass = 'error'; $this->options = $this->getFormSettings($options['form_id']); return false; } } $data['post_related'] = isset($_POST['sppl_post_related']) ? 1 : 0; $data['write_page'] = isset($_POST['sppl_write_page']) ? 1 : 0; $data['hide_wp_customfields'] = isset($_POST['sppl_hide_wp_customfields']) ? 1 : 0; //Update the Defaults $where = array('form_id' => $options['form_id']); $ret = $wpdb->update(SUPPLEFORMSTABLE, $data, $where); if(!$ret){ if($wpdb->insert(SUPPLEFORMSTABLE, $data)){ $options['form_id'] = $wpdb->insert_id; } else { if(!$wpdb->get_var("SELECT form_id FROM " .SUPPLEFORMSTABLE." WHERE form_id = " .$options['form_id'])){ $this->message .= "

Inserting form data failed.

"; $this->msgclass = 'error'; } return false; } } $this->options = $this->getFormSettings($options['form_id']); $this->message ="Supple Forms settings updated..."; } function deleteField($options) { global $wpdb; //This section deletes Field settings check_admin_referer( 'update-suppleforms'); $ret = $wpdb->query("DELETE FROM ".SUPPLEFIELDSTABLE." WHERE field_id=" .(int)$this->field_id." LIMIT 1" ); if($ret){$this->message = "Field deleted...";} return; } function saveFields($options) { global $wpdb; //This section saves Field settings check_admin_referer( 'update-suppleforms'); $field_id = (int)$_POST['sppl_field_id']; $d['field_name'] = $_POST['sppl_field_name']; if(!$this->checkName($d['field_name'])){ $this->message .= "

Invalid field name: " .htmlentities($d['field_name'], ENT_QUOTES).". Use only letters, numbers, and underscore (_).

"; $this->msgclass = 'error'; return false; } $d['label'] = $_POST['sppl_label']; $d['type'] = (int)$_POST['sppl_type']; $d['numeric_field'] = isset($_POST['sppl_numeric_field']) ? 1 : 0; $d['multi_val'] = isset($_POST['sppl_multi_val']) ? 1 : 0; //Only allow multiple values for Textboxes, checkboxes, and Date Pickers if($d['multi_val'] == 1 ){ if($d['type'] == 1 || $d['type'] == 2 || $d['type'] == 3 ){ $d['multi_val'] = 0; } } else { if($d['type'] == 4){$d['multi_val'] = 1;} } if($d['type'] == 0 || $d['type'] == 1){ $d['html_filter'] = (int)$_POST['sppl_html_filter']; } else { $d['html_filter'] = 0; } $d['default_val'] = $_POST['sppl_default_val']; $d['seq'] = (int)(trim($_POST['sppl_seq'])); $d['form_id'] = $options['form_id']; $d['status'] = 0; if($field_id == 0){ $nametest = $wpdb->get_var($wpdb->prepare('SELECT field_name FROM ' .SUPPLEFIELDSTABLE.' WHERE field_name = %s AND form_id = %d',$d['field_name'], $d['form_id'])); if($nametest){ $this->message = "

Duplicate field name: ".$d['field_name']. " - Field not added.

"; return false; } if($wpdb->insert(SUPPLEFIELDSTABLE,$d)){ $insert_id = $wpdb->insert_id; $this->message = "Field Added -> ".$d['field_name']; } else { $this->message = "

FAILED...field failed to insert:

".$d['field_name']; } }else{ $where['field_id'] = $field_id; $wpdb->update( SUPPLEFIELDSTABLE, $d, $where); $this->message = "Field updated: ".$d['field_name'].""; } switch ($d['type']){ case 0: break; case 1: break; case 5: break; case 6: break; default : if($insert_id){ $ret = $this->insertListValues($insert_id); }else{ $ret = $this->insertListValues($field_id); } if($ret){ $this->message .= "  |  ".$ret." list values added."; } else { $this->message .= "
List values missing. Radio buttons, Checkboxes, and Dropdowns require list values. Please add.
"; } break; } } //Insert List Values for multiple selection controls: DropDown List, checkboxes, radio buttons function insertListValues($field_id) { $field_id = (int)$field_id; if(!$field_id){ return false; } //Get the list of values from POST $val = trim($_POST['sppl_valuelist']); if(!$val){ return false;} //Replace funky line breaks to \n $val = str_replace("\r\n","\n",$val); $val = str_replace("\r","\n",$val); //Explode into an array of rows based on \n $rows = explode("\n", $val); //Delete pre-existing values for field_id global $wpdb; $sql = "DELETE FROM " . SUPPLELOOKUPTABLE ." WHERE field_id = ".$field_id; $wpdb->query($sql); //Walk through rows and insert values foreach($rows as $row) { if(trim($row)){ //Get Value and Label...create label from value if not exists...comma separated $s = explode(",", $row); if(count($s) < 2){ $s[1] = $s[0]; } $data = array( 'field_id' => $field_id, 'value' => htmlentities(trim($s[0]), ENT_QUOTES), 'label' => htmlentities(trim($s[1]), ENT_QUOTES), 'seq' => $icnt++ ); $inserts += $wpdb->insert( SUPPLELOOKUPTABLE, $data); } } return $inserts; } //Get the list values for multiple selection controls to disply in the Field Edit screen function getListValuesForEditor($field_id) { global $wpdb; ; $sql = $wpdb->prepare("SELECT value, label FROM ".SUPPLELOOKUPTABLE." WHERE field_id = %d ORDER BY seq", $field_id); $query = $wpdb->get_results($sql,ARRAY_A); if( $query && $wpdb->num_rows > 0){ foreach($query as $row) { $ret[] = implode(', ', $row); } $ret = implode("\n",$ret); return $ret; } return false; } // *************************** ADD / EDIT FIELDS **************************** //Disply the Add/Edit Fields Page function printEditFieldsPage($options, $field_id){ global $wpdb; $fieldsDDL = $this->getFieldsDDL($options['form_id'], $field_id); if($field_id){ $fieldOptions = $wpdb->get_row($wpdb->prepare('SELECT * FROM '.SUPPLEFIELDSTABLE.' WHERE field_id = %d',$field_id), ARRAY_A); $multivalues = trim($this->getListValuesForEditor($field_id)); //Alert the user if they are doing a checkbox, radio, or dropdown and don't have any values saved. switch ($fieldOptions['type']){ case 0: break; case 1: break; case 5: break; case 6: break; default : if(!$multivalues) { if(!strstr($this->message,"List values missing")){ $this->message .= "
List values missing. Radio buttons, Checkboxes, and Dropdowns require list values. Please add.
"; } } break; } } ?>
">

Supple Forms -> Add/Edit Fields

getTableOfFields($options['form_id']); if($this->ungeneratedfields) {$this->message .= "

Custom table may be out of date. Generate when finished adding/editing fields.

";} if($this->message){ echo '

'.$this->message.'

'; } ?>

Add/Edit Fields - No form selected';?>

Select form: getFormsDDL($options['form_id']);?> 
options['use_custom_fields'] == 0){ ?> After all fields are added/changed, generate custom table.
Select field to edit: 
Database field name: '/>
Use letters, numbers, and underscore ( _ ) only
Label: '/>
Order: getNextSeq($options['form_id']); if( $fieldOptions['seq'] === null) {$seq = $nextseq;}else{$seq = (int)$fieldOptions['seq'];} ?> Next sequence #:
Type: >Textbox  ->  Numeric? >
>Multi-line Textbox
>Dropdown List
>Radio Buttons
>Checkboxes
>Date Picker (uses jQuery UI DatePicker)
>Hidden
*/ ?>
Allow multiple values: >
Fields allowing multiple values will use WP Custom Fields
even if Custom Table is selected in 'Where to store data'
in the General Settings page. Other fields will use
Custom Table as directed.

Only available for: Textboxes, Checkboxes, & Dates
HTML filtering: >Filter all html
>Allow formatting tags (b, strong, em, code)
>Allow formatting & links & lists
>No filtering
Uses WordPress HTML filtering functionality (wp_kses)
Default value: '/>
List of values: Enter as: value, display label [new line (\n)]

Required for: checkboxes, radio buttons, and dropdown lists
options['use_custom_fields'] == 0){ ?> After all fields are added/changed, generate custom table.

No fields added yet..."; } ?>
get_results($wpdb->prepare($sql, $form_id)); if($this->options['use_custom_fields'] == 0 ){ $ct = 'Generated'; $b = true; } if($query){ foreach($query as $row) { if($b){ $gen = $row->status == 1 ? "generated" : "not generated"; $gen = "".$gen.""; if(!$row->status){$this->ungeneratedfields++;} } $multi = $row->multi_val == 0 ? 'No' : 'Yes'; $nbr = $row->numeric_field == 0 ? 'No' : 'Yes'; $def = $row->default_val ? $row->default_val : ' '; $ret .= "".$row->seq ." - " .$row->field_name."" ."".$row->label."" ."".$this->getControlType($row->type)."" ."".$nbr."" ."".$multi."" ."".$def."" .$gen." "; } } return ' '.$ct.' '.$ret.'
Field name Label Type Nbr Multi-value Default value
'; } function getControlType($type) { switch ($type) { case 0: return "Textbox"; break; case 1: return "Multi-line"; break; case 2: return "Dropdown List"; break; case 3: return "Radio buttons"; break; case 4: return "Checkboxes"; break; case 5: return "Date Picker"; break; case 6: return "Hidden"; break; } } //Disply the Admin Options Page function printAdminPage($options){ global $wpdb; ?>
">

Supple Forms -> Form Settings

message){ echo '

'.$this->message.'

'; } ?>

Form Settings

Add/Edit Fields";} else { echo ' ';}?>
Select form to edit: getFormsDDL($options['form_id']);?> 
Form Title: '/>
Post related form: > (If selected, post IDs will be stored with records)
Show on Write Post page: > (Allows editable forms in blog pages, not just Write Post)
Hide WP custom fields: > (Remove Supple Forms custom fields from the WP custom fields edit box)
Placement on Write Post page:
Where to Store Data:
Custom Fields or Custom Table
> WP Custom Fields
> Custom Table
WP Custom Fields will always be used for
for fields that allow multiple entries.
Custom Table Name: '/>
- Only used if 'Custom Table' is selected above.
- Supple Forms will prepend 'prefix;?>supple_' to table name. - Custom Table not selected. Will not be used."; }else { if($options['custom_tablename']){ ?>

Custom table name (use for sql calls in your code):
prefix . 'supple_'.$options['custom_tablename'];?> No custom table name given."; } } ?>
Add/Edit Fields";} else { echo ' ';}?>
get_var($sql); $var++; return $var; } //Returns markup for a DropDown List of existing fields function getFieldsDDL($form_id, $selectedField = 0) { global $wpdb; $ret = ""; } } $ret =""; return $ret; } function getFormsDDL($selectedForm = 0) { global $wpdb; $ret = ""; } } $ret =""; return $ret; } } //closes out the class if ( !function_exists('wp_nonce_field') ) { function bwbsppl_nonce_field($action = -1) { return; } $bwbsppl_plugin_nonce = -1; } else { function bwbsppl_nonce_field($action = -1) { return wp_nonce_field($action); } } ?>