/**
  * Shortcode callback for writing the table of form data. Can be put in a page or post to show that data.
  * Shortcode options:
  * [cfdb-table form="your-form"]                             (shows the whole table with default options)
  * Controlling the Display: Apply your CSS to the table; set the table's 'class' or 'id' attribute:
  * [cfdb-table form="your-form" class="css_class"]           (outputs <table class="css_class"> (default: class="cf7-db-table")
  * [cfdb-table form="your-form" id="css_id"]                 (outputs <table id="css_id"> (no default id)
  * [cfdb-table form="your-form" id="css_id" class="css_class"] (outputs <table id="css_id" class="css_class">
  * Filtering Columns:
  * [cfdb-table form="your-form" show="field1,field2,field3"] (optionally show selected fields)
  * [cfdb-table form="your-form" hide="field1,field2,field3"] (optionally hide selected fields)
  * [cfdb-table form="your-form" show="f1,f2,f3" hide="f1"]   (hide trumps show)
  * Filtering Rows:
  * [cfdb-table form="your-form" filter="field1=value1"]      (show only rows where field1=value1)
  * [cfdb-table form="your-form" filter="field1!=value1"]      (show only rows where field1!=value1)
  * [cfdb-table form="your-form" filter="field1=value1&&field2!=value2"] (Logical AND the filters using '&&')
  * [cfdb-table form="your-form" filter="field1=value1||field2!=value2"] (Logical OR the filters using '||')
  * [cfdb-table form="your-form" filter="field1=value1&&field2!=value2||field3=value3&&field4=value4"] (Mixed &&, ||)
  * @param  $atts array of short code attributes
  * @return HTML output of shortcode
  */
 public function handleShortcode($atts)
 {
     if (isset($atts['form'])) {
         $atts['canDelete'] = false;
         $atts['fromshortcode'] = true;
         require_once 'ExportToHtmlTable.php';
         $export = new ExportToHtmlTable();
         return $export->export($atts['form'], $atts);
     }
 }
 /**
  * Shortcode callback for writing the table of form data. Can be put in a page or post to show that data.
  * Shortcode options:
  * [cfdb-table form="your-form"]                             (shows the whole table with default options)
  * Controlling the Display: Apply your CSS to the table; set the table's 'class' or 'id' attribute:
  * [cfdb-table form="your-form" class="css_class"]           (outputs <table class="css_class"> (default: class="cf7-db-table")
  * [cfdb-table form="your-form" id="css_id"]                 (outputs <table id="css_id"> (no default id)
  * [cfdb-table form="your-form" id="css_id" class="css_class"] (outputs <table id="css_id" class="css_class">
  * Filtering Columns:
  * [cfdb-table form="your-form" show="field1,field2,field3"] (optionally show selected fields)
  * [cfdb-table form="your-form" hide="field1,field2,field3"] (optionally hide selected fields)
  * [cfdb-table form="your-form" show="f1,f2,f3" hide="f1"]   (hide trumps show)
  * Filtering Rows:
  * [cfdb-table form="your-form" filter="field1=value1"]      (show only rows where field1=value1)
  * [cfdb-table form="your-form" filter="field1!=value1"]      (show only rows where field1!=value1)
  * [cfdb-table form="your-form" filter="field1=value1&&field2!=value2"] (Logical AND the filters using '&&')
  * [cfdb-table form="your-form" filter="field1=value1||field2!=value2"] (Logical OR the filters using '||')
  * [cfdb-table form="your-form" filter="field1=value1&&field2!=value2||field3=value3&&field4=value4"] (Mixed &&, ||)
  * @param $atts array of short code attributes
  * @param $content string inner content of short code
  * @return string HTML output of shortcode
  */
 public function handleShortcode($atts, $content = null)
 {
     if (isset($atts['form'])) {
         $atts = $this->decodeAttributes($atts);
         $atts['content'] = $content;
         $atts['canDelete'] = false;
         $atts['fromshortcode'] = true;
         require_once 'ExportToHtmlTable.php';
         $export = new ExportToHtmlTable();
         return $export->export($atts['form'], $atts);
     }
     return '';
 }
    function display(&$plugin)
    {
        if ($plugin == null) {
            $plugin = new CF7DBPlugin();
        }
        $canEdit = $plugin->canUserDoRoleOption('CanChangeSubmitData');
        $this->pageHeader($plugin);
        global $wpdb;
        $tableName = $plugin->getSubmitsTableName();
        $useDataTables = $plugin->getOption('UseDataTablesJS', 'true', true) == 'true';
        $tableHtmlId = 'cf2dbtable';
        // Identify which forms have data in the database
        $formsList = $plugin->getForms();
        if (count($formsList) == 0) {
            echo htmlspecialchars(__('No form submissions in the database', 'contact-form-7-to-database-extension'));
            return;
        }
        $page = 1;
        if (isset($_REQUEST['dbpage'])) {
            $page = $this->getRequestParam('dbpage');
        }
        $currSelection = null;
        if (isset($_REQUEST['form_name'])) {
            $currSelection = $this->getRequestParam('form_name');
        } else {
            if (isset($_REQUEST['form'])) {
                $currSelection = $this->getRequestParam('form');
            }
        }
        if ($currSelection) {
            $currSelection = stripslashes($currSelection);
            $currSelection = html_entity_decode($currSelection);
        }
        $currSelectionEscaped = htmlentities($currSelection, null, 'UTF-8');
        // If there is only one form in the DB, select that by default
        if (!$currSelection && count($formsList) == 1) {
            $currSelection = $formsList[0];
            // Bug fix: Need to set this so the Editor plugin can reference it
            $_REQUEST['form_name'] = $formsList[0];
        }
        if ($currSelection) {
            // Check for delete operation
            if (isset($_POST['cfdbdel']) && $canEdit && wp_verify_nonce($_REQUEST['_wpnonce'])) {
                if (isset($_POST['submit_time'])) {
                    $submitTime = $_POST['submit_time'];
                    $wpdb->query($wpdb->prepare("delete from `{$tableName}` where `form_name` = '%s' and `submit_time` = %F", $currSelection, $submitTime));
                } else {
                    if (isset($_POST['all'])) {
                        $wpdb->query($wpdb->prepare("delete from `{$tableName}` where `form_name` = '%s'", $currSelection));
                    } else {
                        foreach ($_POST as $name => $value) {
                            // checkboxes
                            if ($value == 'row') {
                                // Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].
                                // http://www.php.net/manual/en/language.variables.external.php
                                // We are expecting a time value like '1300728460.6626' but will instead get '1300728460_6626'
                                // so we need to put the '.' back in before going to the DB.
                                $name = str_replace('_', '.', $name);
                                $wpdb->query($wpdb->prepare("delete from `{$tableName}` where `form_name` = '%s' and `submit_time` = %F", $currSelection, $name));
                            }
                        }
                    }
                }
            } else {
                if (isset($_POST['delete_wpcf7']) && $canEdit && wp_verify_nonce($_REQUEST['_wpnonce'])) {
                    $plugin->delete_wpcf7_fields($currSelection);
                    $plugin->add_wpcf7_noSaveFields();
                }
            }
        }
        // Form selection drop-down list
        $pluginDirUrl = $plugin->getPluginDirUrl();
        ?>
    <table width="100%" cellspacing="20">
        <tr>
            <td align="left" valign="top">
                <form method="get" action="<?php 
        echo $_SERVER['REQUEST_URI'];
        ?>
" name="displayform" id="displayform">
                    <input type="hidden" name="page" value="<?php 
        echo htmlspecialchars($this->getRequestParam('page'));
        ?>
"/>
                    <select name="form_name" id="form_name" onchange="this.form.submit();">
                        <option value=""><?php 
        echo htmlspecialchars(__('* Select a form *', 'contact-form-7-to-database-extension'));
        ?>
</option>
                        <?php 
        foreach ($formsList as $formName) {
            $selected = $formName == $currSelection ? "selected" : "";
            $formNameEscaped = htmlentities($formName, null, 'UTF-8');
            ?>
                        <option value="<?php 
            echo $formNameEscaped;
            ?>
" <?php 
            echo $selected;
            ?>
><?php 
            echo $formNameEscaped;
            ?>
</option>
                        <?php 
        }
        ?>
                    </select>
                </form>
            </td>
            <td align="center" valign="top">
                <?php 
        if ($currSelection) {
            ?>
                <script type="text/javascript" language="Javascript">
                    function changeDbPage(page) {
                        var newdiv = document.createElement('div');
                        newdiv.innerHTML = "<input id='dbpage' name='dbpage' type='hidden' value='" + page + "'>";
                        var dispForm = document.forms['displayform'];
                        dispForm.appendChild(newdiv);
                        dispForm.submit();
                    }
                    function getSearchFieldValue() {
                        var searchVal = '';
                        if (typeof jQuery == 'function') {
                            try {
                                searchVal = jQuery('#<?php 
            echo $tableHtmlId;
            ?>
_filter input').val();
                            }
                            catch (e) {
                            }
                        }
                        return searchVal;
                    }
                    function exportData(encSelect) {
                        var enc = encSelect.options[encSelect.selectedIndex].value;
                        var url;
                        if (enc == 'GSS') {
                            if (typeof jQuery == 'function') {
                                try {
                                    jQuery("#GoogleCredentialsDialog").dialog({ autoOpen: false, title: '<?php 
            echo htmlspecialchars(__("Google Login for Upload", 'contact-form-7-to-database-extension'));
            ?>
' });
                                    jQuery("#GoogleCredentialsDialog").dialog('open');
                                    jQuery("#guser").focus();
                                }
                                catch (e) {
                                    alert('Error: ' + e.message);
                                }
                            }
                            else {
                                alert("<?php 
            echo htmlspecialchars(__('Cannot perform operation because jQuery is not loaded in this page', 'contact-form-7-to-database-extension'));
            ?>
");
                            }
                        }
                        else if (enc == 'GLD') {
                            alert("<?php 
            echo htmlspecialchars(__('You will now be navigated to the builder page where it will generate a function to place in your Google Spreadsheet', 'contact-form-7-to-database-extension'));
            ?>
");
                            url = '<?php 
            echo $plugin->getAdminUrlPrefix('admin.php');
            ?>
page=CF7DBPluginShortCodeBuilder&form=<?php 
            echo urlencode($currSelection);
            ?>
&enc=' + enc;
                            location.href = url;
                        }
                        else {
                            url = '<?php 
            echo $plugin->getAdminUrlPrefix('admin-ajax.php');
            ?>
action=cfdb-export&form=<?php 
            echo urlencode($currSelection);
            ?>
&enc=' + enc;
                            var searchVal = getSearchFieldValue();
                            if (searchVal != null && searchVal != "") {
                                url += '&search=' + encodeURIComponent(searchVal);
                            }
                            location.href = url;
                        }
                    }
                    function uploadGoogleSS() {
                        var key = '3fde789a';
                        var guser = printHex(des(key, jQuery('#guser').attr('value'), 1));
                        var gpwd = printHex(des(key, jQuery('#gpwd').attr('value'), 1));
                        jQuery("#GoogleCredentialsDialog").dialog('close');
                        var form = document.createElement("form");
                        form.setAttribute("method", 'POST');
                        var url = '<?php 
            echo $pluginDirUrl;
            ?>
export.php?form=<?php 
            echo urlencode($currSelection);
            ?>
&enc=GSS';
                        var searchVal = getSearchFieldValue();
                        if (searchVal != null && searchVal != "") {
                            url += '&search=' + encodeURI(searchVal);
                        }
                        form.setAttribute("action", url);
                        var params = {guser: encodeURI(guser), gpwd: encodeURI(gpwd)};
                        for (var pkey in params) {
                            var hiddenField = document.createElement("input");
                            hiddenField.setAttribute("type", "hidden");
                            hiddenField.setAttribute("name", pkey);
                            hiddenField.setAttribute("value", params[pkey]);
                            form.appendChild(hiddenField);
                        }
                        document.body.appendChild(form);
                        form.submit();
                    }
                </script>
                <form name="exportcsv" action="<?php 
            echo $_SERVER['REQUEST_URI'];
            ?>
">
                    <input type="hidden" name="unbuffered" value="true"/>
                    <select size="1" name="enc">
                        <option id="IQY" value="IQY">
                            <?php 
            echo htmlspecialchars(__('Excel Internet Query', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="CSVUTF8BOM" value="CSVUTF8BOM">
                            <?php 
            echo htmlspecialchars(__('Excel CSV (UTF8-BOM)', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="TSVUTF16LEBOM" value="TSVUTF16LEBOM">
                            <?php 
            echo htmlspecialchars(__('Excel TSV (UTF16LE-BOM)', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="CSVUTF8" value="CSVUTF8">
                            <?php 
            echo htmlspecialchars(__('Plain CSV (UTF-8)', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="CSVSJIS" value="CSVSJIS">
                            <?php 
            echo htmlspecialchars(__('Excel CSV for Japanese (Shift-JIS)', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="GSS" value="GSS">
                            <?php 
            echo htmlspecialchars(__('Google Spreadsheet', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="GLD" value="GLD">
                            <?php 
            echo htmlspecialchars(__('Google Spreadsheet Live Data', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="HTML" value="HTML">
                            <?php 
            echo htmlspecialchars(__('HTML', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                        <option id="JSON" value="JSON">
                            <?php 
            echo htmlspecialchars(__('JSON', 'contact-form-7-to-database-extension'));
            ?>
                        </option>
                    </select>
                    <input name="exportButton" type="button"
                           value="<?php 
            echo htmlspecialchars(__('Export', 'contact-form-7-to-database-extension'));
            ?>
"
                           onclick="exportData(this.form.elements['enc'])"/>
                    <span style="font-size: x-small;"><br /><?php 
            echo '<a href="admin.php?page=' . $plugin->getShortCodeBuilderPageSlug() . '">' . __('Advanced Export', 'contact-form-7-to-database-extension') . '</a>';
            ?>
                </form>
                <?php 
        }
        ?>
            </td>
            <td align="right" valign="top">
                <?php 
        if ($currSelection && $canEdit) {
            ?>
                <form action="<?php 
            echo $_SERVER['REQUEST_URI'];
            ?>
" method="post">
                    <input name="form_name" type="hidden" value="<?php 
            echo $currSelectionEscaped;
            ?>
"/>
                    <input name="all" type="hidden" value="y"/>
                    <?php 
            wp_nonce_field();
            ?>
                    <input name="cfdbdel" type="submit"
                           value="<?php 
            echo htmlspecialchars(__('Delete All This Form\'s Records', 'contact-form-7-to-database-extension'));
            ?>
"
                           onclick="return confirm('<?php 
            echo htmlspecialchars(__('Are you sure you want to delete all the data for this form?', 'contact-form-7-to-database-extension'));
            ?>
')"/>
                </form>
                <br/>
                    <form action="<?php 
            echo $_SERVER['REQUEST_URI'];
            ?>
" method="post">
                        <input name="form_name" type="hidden" value="<?php 
            echo $currSelectionEscaped;
            ?>
"/>
                        <?php 
            wp_nonce_field();
            ?>
                        <input name="delete_wpcf7" type="submit"
                               value="<?php 
            echo htmlspecialchars(__('Remove _wpcf7 columns', 'contact-form-7-to-database-extension'));
            ?>
"/>
                    </form>
                <?php 
        }
        ?>
            </td>
        </tr>
        <?php 
        if ($currSelection && $canEdit && $useDataTables) {
            ?>
        <tr>
            <td align="left" colspan="3">
                <span id="edit_controls">
                    <a href="http://cfdbplugin.com/?page_id=459" target="_cfdbedit"><?php 
            echo htmlspecialchars(__('Edit Data Mode', 'contact-form-7-to-database-extension'));
            ?>
</a>
                </span>
            </td>
        </tr>
        <?php 
        }
        ?>
    </table>


    <?php 
        if ($currSelection) {
            // Show table of form data
            if ($useDataTables) {
                $i18nUrl = $plugin->getDataTableTranslationUrl();
                // Work out the datatable menu for number or rows shown
                $maxVisible = $plugin->getOption('MaxVisibleRows', -1);
                if (!is_numeric($maxVisible)) {
                    $maxVisible = -1;
                }
                $menuJS = $this->createDatatableLengthMenuJavascriptString($maxVisible);
                $sScrollX = $plugin->getOption('HorizontalScroll', 'true', true) == 'true' ? '"100%"' : '""';
                ?>
            <script type="text/javascript" language="Javascript">
                var oTable;
                jQuery(document).ready(function() {
                    oTable = jQuery('#<?php 
                echo $tableHtmlId;
                ?>
').dataTable({ <?php 
                // "sDom": 'Rlfrtip', // ColReorder
                ?>
                        "bJQueryUI": true,
                        "aaSorting": [],
                        //"sScrollY": "400",
                        "bScrollCollapse": true,
                        "sScrollX": <?php 
                echo $sScrollX;
                ?>
,
                        "iDisplayLength": <?php 
                echo $maxVisible;
                ?>
,
                        "aLengthMenu": <?php 
                echo $menuJS;
                ?>
                        <?php 
                if ($i18nUrl) {
                    echo ", \"oLanguage\": { \"sUrl\":  \"{$i18nUrl}\" }";
                }
                if ($canEdit) {
                    do_action_ref_array('cfdb_edit_fnDrawCallbackJSON', array($tableHtmlId));
                }
                ?>
                    });
                    jQuery('th[id="delete_th"]').unbind('click'); <?php 
                // Don't sort delete column
                ?>
                });

            </script>
            <?php 
            }
            if ($canEdit) {
                ?>
        <form action="<?php 
                echo $_SERVER['REQUEST_URI'];
                ?>
" method="post">
            <input name="form_name" type="hidden" value="<?php 
                echo $currSelectionEscaped;
                ?>
"/>
                <input name="cfdbdel" type="hidden" value="rows"/>
                <?php 
                wp_nonce_field();
                ?>
                <?php 
            }
            ?>
            <?php 
            $exporter = new ExportToHtmlTable();
            $dbRowCount = $exporter->getDBRowCount($currSelection);
            $maxRows = $plugin->getOption('MaxRows', '100', true);
            $startRow = $this->paginationDiv($plugin, $dbRowCount, $maxRows, $page);
            ?>
            <div <?php 
            if (!$useDataTables) {
                echo 'style="overflow:auto; max-height:500px; max-width:500px; min-width:75px"';
            }
            ?>
>
            <?php 
            // Pick up any options that the user enters in the URL.
            // This will include extraneous "form_name" and "page" GET params which are in the URL
            // for this admin page
            $options = array_merge($_POST, $_GET);
            $options['canDelete'] = $canEdit;
            if ($maxRows) {
                $options['limit'] = $startRow - 1 . ',' . $maxRows;
            }
            if ($useDataTables) {
                $options['id'] = $tableHtmlId;
                $options['class'] = '';
                $options['style'] = "#{$tableHtmlId} {padding:0;} #{$tableHtmlId} td > div { max-height: 100px;  min-width:75px; overflow: auto; font-size: small;}";
                // don't let cells get too tall
            }
            $exporter->export($currSelection, $options);
            ?>
            </div>
            <?php 
            if ($canEdit) {
                ?>
            </form>
        <?php 
            }
        }
        ?>
        <script type="text/javascript">
            (function ($) {
                var url = "admin.php?page=<?php 
        echo $plugin->getDBPageSlug();
        ?>
&form_name=<?php 
        echo urlencode($currSelection);
        ?>
&submit_time=";
                $('td[title="Submitted"] div').each(
                        function () {
                            var submitTime = $(this).attr('id').split(",");
                            $(this).html('<a target="_cfdb_entry" href="' + url + submitTime[0] + '">' + $(this).html() + '</a>');
                        })
            })(jQuery);
        </script>
        <div style="margin-top:1em"> <?php 
        // Footer
        ?>
        <table style="width:100%;">
            <tbody>
            <tr>
                <td align="center" colspan="4">
                    <span style="font-size:x-small; font-style: italic;">
                        <?php 
        echo htmlspecialchars(__('Did you know: This plugin captures data from these plugins:', 'contact-form-7-to-database-extension'));
        ?>
                        <br/>
                        <a target="_cf7" href="https://wordpress.org/plugins/contact-form-7/">Contact Form 7</a>,
                        <a target="_fscf" href="https://wordpress.org/plugins/si-contact-form/">Fast Secure Contact Form</a>,
                        <a target="_jetpack" href="https://wordpress.org/plugins/jetpack/">JetPack Contact Form</a>,
                        <a target="_gravityforms" href="http://www.gravityforms.com">Gravity Forms</a>,
                        <a target="_wr" href="https://wordpress.org/plugins/wr-contactform/">WR ContactForm</a>,
                        <a target="_formidable" href="https://wordpress.org/plugins/formidable/">Formidable Forms (BETA)</a>,
                        <a target="_quform" href="http://codecanyon.net/item/quform-wordpress-form-builder/706149/">Quform (BETA)</a>,
                        <a target="_ninjaforms" href="https://wordpress.org/plugins/ninja-forms/">Ninja Forms (BETA)</a>,
                        <a target="_caldera" href="https://wordpress.org/plugins/caldera-forms/">Caldera Forms (BETA)</a>
                        <a target="_cf2" href="https://wordpress.org/plugins/cforms2/">CFormsII Forms (BETA)</a>
                    </span>
                </td>
            </tr>
            <tr>
                <td align="center" colspan="4">
                    <span style="font-size:x-small; font-style: italic;">
                    <?php 
        echo htmlspecialchars(__('Did you know: You can add this data to your posts and pages using these shortcodes:', 'contact-form-7-to-database-extension'));
        ?>
                        <br/>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=284">[cfdb-html]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=91">[cfdb-datatable]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=93">[cfdb-table]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=98">[cfdb-value]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=278">[cfdb-count]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=96">[cfdb-json]</a>
                    </span>
                </td>
            </tr>
            <tr>
                <td align="center" colspan="4">
                        <span style="font-size:x-small; font-style: italic;">
                            <?php 
        echo htmlspecialchars(__('Would you like to help translate this plugin into your language?', 'contact-form-7-to-database-extension'));
        ?>
                            <a target="_i18n"
                               href="http://cfdbplugin.com/?page_id=7"><?php 
        echo htmlspecialchars(__('How to create a translation', 'contact-form-7-to-database-extension'));
        ?>
</a>
                        </span>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <?php 
        if ($currSelection && 'true' == $plugin->getOption('ShowQuery', 'false', true)) {
            ?>
        <div id="query" style="margin: 20px; border: dotted #d3d3d3 1pt;">
            <strong><?php 
            echo htmlspecialchars(__('Query:', 'contact-form-7-to-database-extension'));
            ?>
</strong><br/>
            <pre><?php 
            echo $exporter->getPivotQuery($currSelection);
            ?>
</pre>
        </div>
        <?php 
        }
        if ($currSelection) {
            ?>
        <div id="GoogleCredentialsDialog" style="display:none; background-color:#EEEEEE;">
            <table>
                <tbody>
                <tr>
                    <td><label for="guser">User</label></td>
                    <td><input id="guser" type="text" size="25" value="@gmail.com"/></td>
                </tr>
                <tr>
                    <td><label for="gpwd">Password</label></td>
                    <td><input id="gpwd" type="password" size="25" value=""/></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="button" value="<?php 
            echo htmlspecialchars(__('Cancel', 'contact-form-7-to-database-extension'));
            ?>
"
                               onclick="jQuery('#GoogleCredentialsDialog').dialog('close');"/>
                        <input type="button" value="<?php 
            echo htmlspecialchars(__('Upload', 'contact-form-7-to-database-extension'));
            ?>
"
                               onclick="uploadGoogleSS()"/>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <script type="text/javascript" language="Javascript">
            var addColumnLabelText = '<?php 
            echo htmlspecialchars(__('Add Column', 'contact-form-7-to-database-extension'));
            ?>
';
            var deleteColumnLabelText = '<?php 
            echo htmlspecialchars(__('Delete Column', 'contact-form-7-to-database-extension'));
            ?>
';
        </script>
        <?php 
            do_action_ref_array('cfdb_edit_setup', array($plugin));
        }
    }
Example #4
0
 static function export($formName, $encoding, $options)
 {
     switch ($encoding) {
         case 'HTML':
             require_once 'ExportToHtmlTable.php';
             $exporter = new ExportToHtmlTable();
             $exporter->export($formName, $options);
             break;
         case 'HTMLBOM':
             // IQY callback
             require_once 'ExportToHtmlTable.php';
             $exporter = new ExportToHtmlTable();
             $exporter->setUseBom(true);
             $exporter->export($formName, $options);
             break;
         case 'DT':
             require_once 'ExportToHtmlTable.php';
             if (!is_array($options)) {
                 $options = array();
             }
             $options['useDT'] = true;
             if (!isset($options['printScripts'])) {
                 $options['printScripts'] = true;
             }
             if (!isset($options['printStyles'])) {
                 $options['printStyles'] = 'true';
             }
             $exporter = new ExportToHtmlTable();
             $exporter->export($formName, $options);
             break;
         case 'HTMLTemplate':
             require_once 'ExportToHtmlTemplate.php';
             $exporter = new ExportToHtmlTemplate();
             $exporter->export($formName, $options);
             break;
         case 'IQY':
             require_once 'ExportToIqy.php';
             $exporter = new ExportToIqy();
             $exporter->export($formName, $options);
             break;
         case 'CSVUTF8BOM':
             $options['unbuffered'] = 'true';
             require_once 'ExportToCsvUtf8.php';
             $exporter = new ExportToCsvUtf8();
             $exporter->setUseBom(true);
             $exporter->export($formName, $options);
             break;
         case 'TSVUTF16LEBOM':
             $options['unbuffered'] = 'true';
             require_once 'ExportToCsvUtf16le.php';
             $exporter = new ExportToCsvUtf16le();
             $exporter->export($formName, $options);
             break;
         case 'GLD':
             require_once 'ExportToGoogleLiveData.php';
             $exporter = new ExportToGoogleLiveData();
             $exporter->export($formName, $options);
             break;
         case 'GSS':
             $options['unbuffered'] = 'true';
             require_once 'ExportToGoogleSS.php';
             $exporter = new ExportToGoogleSS();
             $exporter->export($formName, $options);
             break;
         case 'JSON':
             require_once 'ExportToJson.php';
             $exporter = new ExportToJson();
             $exporter->export($formName, $options);
             break;
         case 'VALUE':
             require_once 'ExportToValue.php';
             $exporter = new ExportToValue();
             $exporter->export($formName, $options);
             break;
         case 'COUNT':
             require_once 'ExportToValue.php';
             if (!is_array($options)) {
                 $options = array();
             }
             $options['function'] = 'count';
             unset($options['show']);
             unset($options['hide']);
             $exporter = new ExportToValue();
             $exporter->export($formName, $options);
             break;
         case 'CSVSJIS':
             require_once 'ExportToCsvUtf8.php';
             $exporter = new ExportToCsvUtf8();
             $exporter->setUseBom(false);
             $exporter->setUseShiftJIS(true);
             $exporter->export($formName, $options);
             break;
         case 'RSS':
             require_once 'ExportToRSS.php';
             $exporter = new ExportToRSS();
             $exporter->export($formName, $options);
             break;
         case 'ENTRY':
             require_once 'ExportEntry.php';
             $exporter = new ExportEntry();
             $exporter->export($formName, $options);
             break;
         case 'CSVUTF8':
         default:
             require_once 'ExportToCsvUtf8.php';
             $exporter = new ExportToCsvUtf8();
             $exporter->setUseBom(false);
             $exporter->export($formName, $options);
             break;
     }
 }
    function display(&$plugin)
    {
        if ($plugin == null) {
            $plugin = new CF7DBPlugin();
        }
        $canEdit = $plugin->canUserDoRoleOption('CanChangeSubmitData');
        $this->pageHeader($plugin);
        global $wpdb;
        $tableName = $plugin->getSubmitsTableName();
        $useDataTables = $plugin->getOption('UseDataTablesJS', 'true') == 'true';
        $tableHtmlId = 'cf2dbtable';
        // Identify which forms have data in the database
        $rows = $wpdb->get_results("select distinct `form_name` from `{$tableName}` order by `form_name`");
        if ($rows == null || count($rows) == 0) {
            _e('No form submissions in the database', 'contact-form-7-to-database-extension');
            return;
        }
        $page = 1;
        if (isset($_REQUEST['dbpage'])) {
            $page = $_REQUEST['dbpage'];
        } else {
            if (isset($_GET['dbpage'])) {
                $page = $_GET['dbpage'];
            }
        }
        $currSelection = null;
        //$rows[0]->form_name;
        if (isset($_REQUEST['form_name'])) {
            $currSelection = $_REQUEST['form_name'];
        } else {
            if (isset($_GET['form_name'])) {
                $currSelection = $_GET['form_name'];
            }
        }
        if ($currSelection) {
            // Check for delete operation
            if (isset($_POST['delete']) && $canEdit) {
                if (isset($_POST['submit_time'])) {
                    $submitTime = $_POST['submit_time'];
                    $wpdb->query($wpdb->prepare("delete from `{$tableName}` where `form_name` = '%s' and `submit_time` = %F", $currSelection, $submitTime));
                } else {
                    if (isset($_POST['all'])) {
                        $wpdb->query($wpdb->prepare("delete from `{$tableName}` where `form_name` = '%s'", $currSelection));
                    } else {
                        foreach ($_POST as $name => $value) {
                            // checkboxes
                            if ($value == 'row') {
                                // Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].
                                // http://www.php.net/manual/en/language.variables.external.php
                                // We are expecting a time value like '1300728460.6626' but will instead get '1300728460_6626'
                                // so we need to put the '.' back in before going to the DB.
                                $name = str_replace('_', '.', $name);
                                $wpdb->query($wpdb->prepare("delete from `{$tableName}` where `form_name` = '%s' and `submit_time` = %F", $currSelection, $name));
                            }
                        }
                    }
                }
            }
        }
        // Form selection drop-down list
        $pluginDirUrl = $plugin->getPluginDirUrl();
        ?>
    <table width="100%" cellspacing="20">
        <tr>
            <td align="left" valign="top">
                <form method="get" action="" name="displayform" id="displayform">
                    <input type="hidden" name="page" value="<?php 
        echo $_REQUEST['page'];
        ?>
"/>
                    <select name="form_name" id="form_name" onchange="this.form.submit();">
                        <option value=""><?php 
        _e('* Select a form *', 'contact-form-7-to-database-extension');
        ?>
</option>
                        <?php 
        foreach ($rows as $aRow) {
            $formName = $aRow->form_name;
            $selected = $formName == $currSelection ? "selected" : "";
            ?>
                        <option value="<?php 
            echo $formName;
            ?>
" <?php 
            echo $selected;
            ?>
><?php 
            echo $formName;
            ?>
</option>
                        <?php 
        }
        ?>
                    </select>
                </form>
            </td>
            <td align="center" valign="top">
                <?php 
        if ($currSelection) {
            ?>
                <script type="text/javascript" language="Javascript">
                    function changeDbPage(page) {
                        var newdiv = document.createElement('div');
                        newdiv.innerHTML = "<input id='dbpage' name='dbpage' type='hidden' value='" + page + "'>";
                        var dispForm = document.forms['displayform'];
                        dispForm.appendChild(newdiv);
                        dispForm.submit();
                    }
                    function getSearchFieldValue() {
                        var searchVal = '';
                        if (typeof jQuery == 'function') {
                            try {
                                searchVal = jQuery('#<?php 
            echo $tableHtmlId;
            ?>
_filter input').val();
                            }
                            catch (e) {
                            }
                        }
                        return searchVal;
                    }
                    function exportData(encSelect) {
                        var enc = encSelect.options[encSelect.selectedIndex].value;
                        if (enc == 'GSS') {
                            if (typeof jQuery == 'function') {
                                try {
                                    jQuery("#GoogleCredentialsDialog").dialog({ autoOpen: false, title: '<?php 
            _e("Google Login for Upload", 'contact-form-7-to-database-extension');
            ?>
' });
                                    jQuery("#GoogleCredentialsDialog").dialog('open');
                                    jQuery("#guser").focus();
                                }
                                catch (e) {
                                    alert('Error: ' + e.message);
                                }
                            }
                            else {
                                alert("<?php 
            _e('Cannot perform operation because jQuery is not loaded in this page', 'contact-form-7-to-database-extension');
            ?>
");
                            }
                        }
                        else {
                            var url = '<?php 
            echo admin_url('admin-ajax.php');
            ?>
?action=cfdb-export&form=<?php 
            echo urlencode($currSelection);
            ?>
&enc=' + enc;
                            var searchVal = getSearchFieldValue();
                            if (searchVal != null && searchVal != "") {
                                url += '&search=' + encodeURIComponent(searchVal);
                            }
                            location.href = url;
                        }
                    }
                    function uploadGoogleSS() {
                        var key = '3fde789a';
                        var guser = printHex(des(key, jQuery('#guser').attr('value'), 1));
                        var gpwd = printHex(des(key, jQuery('#gpwd').attr('value'), 1));
                        jQuery("#GoogleCredentialsDialog").dialog('close');
                        var form = document.createElement("form");
                        form.setAttribute("method", 'POST');
                        var url = '<?php 
            echo $pluginDirUrl;
            ?>
export.php?form=<?php 
            echo urlencode($currSelection);
            ?>
&enc=GSS';
                        var searchVal = getSearchFieldValue();
                        if (searchVal != null && searchVal != "") {
                            url += '&search=' + encodeURI(searchVal);
                        }
                        form.setAttribute("action", url);
                        var params = {guser: encodeURI(guser), gpwd: encodeURI(gpwd)};
                        for (var pkey in params) {
                            var hiddenField = document.createElement("input");
                            hiddenField.setAttribute("type", "hidden");
                            hiddenField.setAttribute("name", pkey);
                            hiddenField.setAttribute("value", params[pkey]);
                            form.appendChild(hiddenField);
                        }
                        document.body.appendChild(form);
                        form.submit();
                    }
                </script>
                <form name="exportcsv" action="">
                    <select size="1" name="enc">
                        <option id="IQY" value="IQY">
                            <?php 
            _e('Excel Internet Query', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="CSVUTF8BOM" value="CSVUTF8BOM">
                            <?php 
            _e('Excel CSV (UTF8-BOM)', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="TSVUTF16LEBOM" value="TSVUTF16LEBOM">
                            <?php 
            _e('Excel TSV (UTF16LE-BOM)', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="CSVUTF8" value="CSVUTF8">
                            <?php 
            _e('Plain CSV (UTF-8)', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="GSS" value="GSS">
                            <?php 
            _e('Google Spreadsheet', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="GLD" value="GLD">
                            <?php 
            _e('Google Spreadsheet Live Data', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="HTML" value="HTML">
                            <?php 
            _e('HTML', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                        <option id="JSON" value="JSON">
                            <?php 
            _e('JSON', 'contact-form-7-to-database-extension');
            ?>
                        </option>
                    </select>
                    <input name="exportButton" type="button"
                           value="<?php 
            _e('Export', 'contact-form-7-to-database-extension');
            ?>
"
                           onclick="exportData(this.form.elements['enc'])"/>
                    <span style="font-size: x-small;"><br /><?php 
            echo '<a href="admin.php?page=' . $plugin->getSortCodeBuilderPageSlug() . '">' . __('Advanced Export', 'contact-form-7-to-database-extension') . '</a>';
            ?>
                </form>
                <?php 
        }
        ?>
            </td>
            <td align="right" valign="top">
                <?php 
        if ($currSelection && $canEdit) {
            ?>
                <form action="" method="post">
                    <input name="form_name" type="hidden" value="<?php 
            echo $currSelection;
            ?>
"/>
                    <input name="all" type="hidden" value="y"/>
                    <input name="delete" type="submit"
                           value="<?php 
            _e('Delete All This Form\'s Records', 'contact-form-7-to-database-extension');
            ?>
"
                           onclick="return confirm('Are you sure you want to delete all the data for this form?')"/>
                </form>
                <?php 
        }
        ?>
            </td>
        </tr>
        <?php 
        if ($currSelection && $canEdit && $useDataTables) {
            ?>
        <tr>
            <td align="left" colspan="3">
                <span id="edit_controls">
                    <a href="http://cfdbplugin.com/?page_id=459" target="_cfdbedit"><?php 
            _e('Edit Data Mode', 'contact-form-7-to-database-extension');
            ?>
</a>
                </span>
            </td>
        </tr>
        <?php 
        }
        ?>
    </table>


    <?php 
        if ($currSelection) {
            // Show table of form data
            if ($useDataTables) {
                $i18nUrl = $plugin->getDataTableTranslationUrl();
                ?>
            <script type="text/javascript" language="Javascript">
                var oTable;
                jQuery(document).ready(function() {
                    oTable = jQuery('#<?php 
                echo $tableHtmlId;
                ?>
').dataTable({ <?php 
                // "sDom": 'Rlfrtip', // ColReorder
                ?>
                    "bJQueryUI": true,
                    "aaSorting": [],
                    "bScrollCollapse": true
                        <?php 
                if ($i18nUrl) {
                    echo ", \"oLanguage\": { \"sUrl\":  \"{$i18nUrl}\" }";
                }
                if ($canEdit) {
                    do_action_ref_array('cfdb_edit_fnDrawCallbackJSON', array($tableHtmlId));
                }
                ?>
                    });
                });

            </script>
            <?php 
            }
            if ($canEdit) {
                ?>
        <form action="" method="post">
            <input name="form_name" type="hidden" value="<?php 
                echo $currSelection;
                ?>
"/>
                <input name="delete" type="hidden" value="rows"/>
                <?php 
            }
            ?>
            <?php 
            $exporter = new ExportToHtmlTable();
            $dbRowCount = $exporter->getDBRowCount($currSelection);
            $maxRows = $plugin->getOption('MaxRows', '100');
            $startRow = $this->paginationDiv($plugin, $dbRowCount, $maxRows, $page);
            ?>
            <div <?php 
            if (!$useDataTables) {
                echo 'style="overflow:auto; max-height:500px; max-width:500px; min-width:75px"';
            }
            ?>
>
            <?php 
            // Pick up any options that the user enters in the URL.
            // This will include extraneous "form_name" and "page" GET params which are in the URL
            // for this admin page
            $options = array_merge($_POST, $_GET);
            $options['canDelete'] = $canEdit;
            if ($maxRows) {
                $options['limit'] = $startRow - 1 . ',' . $maxRows;
            }
            if ($useDataTables) {
                $options['id'] = $tableHtmlId;
                $options['class'] = '';
                $options['style'] = "#{$tableHtmlId} td > div { max-height: 100px;  min-width:75px; overflow: auto; font-size: small; }";
                // don't let cells get too tall
            }
            $exporter->export($currSelection, $options);
            ?>
            </div>
            <?php 
            if ($canEdit) {
                ?>
            </form>
        <?php 
            }
        }
        ?>
    <div style="margin-top:1em"> <?php 
        // Footer
        ?>
        <table style="width:100%;">
            <tbody>
            <tr>
                <td align="center" colspan="4">
                    <span style="font-size:x-small; font-style: italic;">
                        <?php 
        _e('Did you know: This plugin captures data from both these plugins:', 'contact-form-7-to-database-extension');
        ?>
                        <a target="_cf7" href="http://wordpress.org/extend/plugins/contact-form-7/">Contact Form 7</a>
                        <a target="_fscf" href="http://wordpress.org/extend/plugins/si-contact-form/">Fast Secure Contact Form</a>
                    </span>
                </td>
            </tr>
            <tr>
                <td align="center" colspan="4">
                    <span style="font-size:x-small; font-style: italic;">
                    <?php 
        _e('Did you know: You can add this data to your posts and pages using these shortcodes:', 'contact-form-7-to-database-extension');
        ?>
                        <br/>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=284">[cfdb-html]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=91">[cfdb-datatable]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=93">[cfdb-table]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=98">[cfdb-value]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=278">[cfdb-count]</a>
                        <a target="_faq" href="http://cfdbplugin.com/?page_id=96">[cfdb-json]</a>
                    </span>
                </td>
            </tr>
            <tr>
                <td align="center" colspan="4">
                        <span style="font-size:x-small; font-style: italic;">
                            <?php 
        _e('Would you like to help translate this plugin into your language?', 'contact-form-7-to-database-extension');
        ?>
                            <a target="_i18n"
                               href="http://cfdbplugin.com/?page_id=7"><?php 
        _e('How to create a translation', 'contact-form-7-to-database-extension');
        ?>
</a>
                        </span>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <?php 
        if ($currSelection && 'true' == $plugin->getOption('ShowQuery')) {
            ?>
        <div id="query">
            <strong><?php 
            _e('Query:', 'contact-form-7-to-database-extension');
            ?>
</strong><br/>
            <pre><?php 
            echo $exporter->getPivotQuery($currSelection);
            ?>
</pre>
        </div>
        <?php 
        }
        if ($currSelection) {
            ?>
        <div id="GoogleCredentialsDialog" style="display:none; background-color:#EEEEEE;">
            <table>
                <tbody>
                <tr>
                    <td><label for="guser">User</label></td>
                    <td><input id="guser" type="text" size="25" value="@gmail.com"/></td>
                </tr>
                <tr>
                    <td><label for="gpwd">Password</label></td>
                    <td><input id="gpwd" type="password" size="25" value=""/></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="button" value="<?php 
            _e('Cancel', 'contact-form-7-to-database-extension');
            ?>
"
                               onclick="jQuery('#GoogleCredentialsDialog').dialog('close');"/>
                        <input type="button" value="<?php 
            _e('Upload', 'contact-form-7-to-database-extension');
            ?>
"
                               onclick="uploadGoogleSS()"/>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <script type="text/javascript" language="Javascript">
            var addColumnLabelText = '<?php 
            _e('Add Column', 'contact-form-7-to-database-extension');
            ?>
';
            var deleteColumnLabelText = '<?php 
            _e('Delete Column', 'contact-form-7-to-database-extension');
            ?>
';
        </script>
        <?php 
            do_action_ref_array('cfdb_edit_setup', array($plugin));
        }
    }
 public function getTableOutput()
 {
     $data = array(array('first-name' => 'John', 'last-name' => 'Doe'), array('first-name' => 'Richard', 'last-name' => 'Roe'));
     $this->exportSetup($data);
     $options = array('id' => 'mytable', 'class' => 'myclass');
     $exp = new ExportToHtmlTable();
     ob_start();
     $exp->export('Form', $options);
     $text = ob_get_contents();
     return $text;
 }