Example #1
0
" /> 
                <?php 
if (!empty($_SESSION['reportFilters'][$Media['ID']])) {
    //dump($_SESSION['reportFilters']);
    ?>
            <input type="submit" value="Clear Results" class="filterSearchbutton" onclick="jQuery('#clearFilters_<?php 
    echo $Media['ID'];
    ?>
').val(1); jQuery('#setFilters_<?php 
    echo $Media['ID'];
    ?>
').submit();" /><input type="hidden" name="reportFilter[ClearFilters]" id="clearFilters_<?php 
    echo $Media['ID'];
    ?>
" value="" />
                <?php 
}
?>
        </div>
    </form>
    <div style="clear:both"></div>
</div>
    <?php 
if (isset($gotTo) && !empty($_SESSION['reportFilters'][$Media['ID']])) {
    echo dr_BuildReportGrid($Media['ID'], $gotTo, $_SESSION['report_' . $Media['ID']]['SortField'], $_SESSION['report_' . $Media['ID']]['SortDir']);
} else {
    if (!empty($_SESSION['reportFilters'][$Media['ID']])) {
        echo dr_BuildReportGrid($Media['ID'], false, false, false);
    }
}
return;
Example #2
0
function dt_process()
{
    if (!empty($_POST['func']) && !empty($_POST['action'])) {
        if ($_POST['action'] == 'wp_dt_ajaxCall') {
            dt_ajaxCall();
            exit;
        }
    }
    if (!empty($_POST['processKey'])) {
        $_POST = stripslashes_deep($_POST);
        if ($_POST['processKey'] == $_SESSION['processKey']) {
            include_once DB_TOOLKIT . 'daiselements.class.php';
            include_once DB_TOOLKIT . 'data_form/class.php';
            include_once DB_TOOLKIT . 'data_report/class.php';
            unset($_SESSION['processKey']);
            $_SESSION['DF_Post'] = array();
            if (!empty($_POST['dr_update'])) {
                $EID = $_POST['dataForm']['EID'];
                $Setup = getelement($EID);
                unset($_POST['dataForm']['dr_update']);
                unset($_POST['dataForm']['EID']);
                $Return = df_processUpdate($_POST['dataForm'], $EID);
                if (!empty($Return['_fail_'])) {
                    $_SESSION['failedProcess'][$EID]['Data'] = $Data;
                    $_SESSION['failedProcess'][$EID]['Fields'] = $Return['_fail_'];
                    $_SESSION['DF_Notification'] = $Return['_error_'];
                    $_SESSION['DF_NotificationTypes'][] = 'error';
                    header('Location: ' . $_SERVER['HTTP_REFERER']);
                    exit;
                }
                if (!empty($Return['Value'])) {
                    dr_trackActivity('Update', $EID, $Return['Value']);
                    $_SESSION['DF_Post_returnID'] = $Return['Value'];
                    $_SESSION['DF_Post_EID'] = $EID;
                }
                if (empty($Setup['Content']['_NotificationsOff'])) {
                    if (!empty($Setup['Content']['_inlineNotifications'])) {
                        $_SESSION['DF_Notification'][] = $Return['Message'];
                        $_SESSION['DF_NotificationTypes'][] = $Return['noticeType'];
                    } else {
                        $_SESSION['DF_Post'][] = $Return['Message'];
                    }
                }
            } else {
                foreach ($_POST['dataForm'] as $EID => $Data) {
                    $Return = df_processInsert($EID, $Data);
                    if (!empty($Return['_fail_'])) {
                        $_SESSION['failedProcess'][$EID]['Data'] = $Data;
                        $_SESSION['failedProcess'][$EID]['Fields'] = $Return['_fail_'];
                        $_SESSION['DF_NotificationTypes'][] = 'error';
                        header('Location: ' . $_SERVER['HTTP_REFERER']);
                        exit;
                    }
                    // Track Activity
                    if (!empty($Return['Value'])) {
                        dr_trackActivity('Insert', $EID, $Return['Value']);
                    }
                    $Setup = getelement($EID);
                    if (empty($Setup['Content']['_NotificationsOff'])) {
                        if (!empty($Setup['Content']['_inlineNotifications'])) {
                            $_SESSION['DF_Notification'][] = $Return['Message'];
                            $_SESSION['DF_NotificationTypes'][] = $Return['noticeType'];
                        } else {
                            $_SESSION['DF_Post'][] = $Return['Message'];
                        }
                    }
                }
            }
            $Redirect = $_SERVER['HTTP_REFERER'];
            if (!empty($Return['Value'])) {
                $ReturnValue = $Return['Value'];
            }
            if (is_admin()) {
                if (!empty($Setup['Content']['_ItemViewInterface'])) {
                    $Location = 'admin.php';
                } else {
                    $Location = $_SERVER['HTTP_REFERER'];
                }
            } else {
                if (!empty($Setup['Content']['_ItemViewPage'])) {
                    $Location = get_permalink($Setup['Content']['_ItemViewPage']);
                } else {
                    $Location = $_SERVER['HTTP_REFERER'];
                }
            }
            //echo $Location;
            //exit;
            if (!empty($ReturnValue)) {
                $url = parse_url($_SERVER['HTTP_REFERER']);
                $returntoken = '?';
                if (!empty($url['query'])) {
                    if (empty($Setup['Content']['_ItemViewPage'])) {
                        $Location = str_replace('?' . $url['query'], '', $_SERVER['HTTP_REFERER']);
                    }
                    parse_str($url['query'], $gets);
                    parse_str($ReturnValue, $returngets);
                    if (!empty($Setup['Content']['_ItemViewInterface'])) {
                        $RedirInterface = get_option($Setup['Content']['_ItemViewInterface']);
                        if (!empty($RedirInterface['_ItemGroup'])) {
                            $app = get_option('_' . $RedirInterface['_Application'] . '_app');
                            if (!empty($app['docked'])) {
                                $gets['page'] = $Setup['Content']['_ItemViewInterface'];
                            } else {
                                $gets['page'] = 'dbt_builder';
                                $gets['renderinterface'] = $Setup['Content']['_ItemViewInterface'];
                            }
                        } else {
                            $gets['page'] = 'dbt_builder';
                            $gets['renderinterface'] = $Setup['Content']['_ItemViewInterface'];
                        }
                    }
                    $ReturnValue = htmlspecialchars_decode(@http_build_query(array_merge($gets, $returngets)));
                } else {
                    if (!empty($Setup['Content']['_ItemViewInterface'])) {
                        $RedirInterface = get_option($Setup['Content']['_ItemViewInterface']);
                        if (!empty($RedirInterface['_ItemGroup'])) {
                            $app = get_option('_' . $RedirInterface['_Application'] . '_app');
                            if (!empty($app['docked'])) {
                                $gets['page'] = $Setup['Content']['_ItemViewInterface'];
                            } else {
                                $gets['page'] = 'dbt_builder';
                                $gets['renderinterface'] = $Setup['Content']['_ItemViewInterface'];
                            }
                        } else {
                            $gets['page'] = 'dbt_builder';
                            $gets['renderinterface'] = $Setup['Content']['_ItemViewInterface'];
                        }
                        $ReturnValue = htmlspecialchars_decode(@http_build_query($gets, $returngets));
                    }
                }
                $Redirect = $Location . $returntoken . $ReturnValue;
            }
            //echo $Redirect;
            //exit;
            header('Location: ' . $Redirect);
            exit;
        }
    }
    //vardump($_POST);
    if (!empty($_POST['importKey'])) {
        $_POST = stripslashes_deep($_POST);
        if (empty($_FILES['fileImport']['size'])) {
            $_SESSION['dataform']['OutScripts'] .= "\n              df_buildImportForm('" . $_POST['importInterface'] . "');\n            ";
            $Redirect = $_SERVER['HTTP_REFERER'];
            header('Location: ' . $Redirect);
            exit;
        }
        $path = wp_upload_dir();
        // set filename and paths
        $Ext = pathinfo($_FILES['fileImport']['name']);
        $newFileName = $_POST['importInterface'] . '.' . $Ext['extension'];
        $newLoc = $path['path'] . '/' . $newFileName;
        $_SESSION['import_' . $_POST['importInterface']]['import'] = wp_upload_bits($newFileName, null, file_get_contents($_FILES['fileImport']['tmp_name']));
        $_SESSION['dataform']['OutScripts'] .= "\n          df_buildImportManager('" . $_POST['importInterface'] . "');\n        ";
        $Redirect = $_SERVER['HTTP_REFERER'];
        header('Location: ' . $Redirect);
        exit;
    }
    if (!empty($_POST['importPrepairKey'])) {
        $Element = getelement($_POST['importInterface']);
        $_SESSION['import_' . $_POST['importInterface']]['import']['table'] = $Element['Content']['_main_table'];
        $_SESSION['import_' . $_POST['importInterface']]['import']['delimiter'] = $_POST['importDelimeter'];
        if (!empty($_POST['importSkipFirst'])) {
            $_SESSION['import_' . $_POST['importInterface']]['import']['importSkipFirst'] = $_POST['importSkipFirst'];
        }
        $_SESSION['import_' . $_POST['importInterface']]['import']['map'] = $_POST['importMap'];
        $_SESSION['dataform']['OutScripts'] .= "\n            df_processImport('" . $_POST['importInterface'] . "');\n        ";
        $Redirect = $_SERVER['HTTP_REFERER'];
        header('Location: ' . $Redirect);
        exit;
    }
    // API Call
    //vardump($_SERVER);
    $pattern = API_getInterfaceRegex();
    if (!empty($pattern)) {
        if (preg_match('/' . $pattern['regex'] . '/s', $_SERVER['REQUEST_URI'], $matches)) {
            include_once DB_TOOLKIT . 'libs/api_engine.php';
            exit;
        }
    }
    /// EXPORT
    foreach ($_GET as $PDFExport => $Val) {
        if (!is_array($Val)) {
            if (strstr($PDFExport, 'format_')) {
                $export = explode('_dt_', $PDFExport);
                $exportFormat = $Val;
                $Media['ID'] = 'dt_' . $export[1];
                $Element = getElement($Media['ID']);
                $Config = $Element['Content'];
            }
        }
    }
    //error_reporting(E_ALL);
    //ini_set('display_errors','On');
    //esds
    if (!empty($exportFormat)) {
        if ($exportFormat == 'pdf') {
            include_once DB_TOOLKIT . 'daiselements.class.php';
            include_once DB_TOOLKIT . 'data_form/class.php';
            include_once DB_TOOLKIT . 'data_report/class.php';
            include_once DB_TOOLKIT . 'data_itemview/class.php';
            include_once DB_TOOLKIT . 'libs/fpdf.php';
            include_once DB_TOOLKIT . 'libs/pdfexport.php';
            $input_params["return"] = isset($input_params["return"]) ? $input_params["return"] : false;
            if (empty($Config['_orientation'])) {
                $Config['_orientation'] = 'P';
            }
            $report = new PDFReport($Config['_orientation'], $Config['_ReportTitle']);
            //you should use loadlib here
            //dump($_SESSION['reportFilters'][$Media['ID']]);
            if (!empty($Config['_FilterMode'])) {
                $Res = mysql_query("SELECT ID, Content FROM `dais_elements` WHERE `Element` = 'data_report' AND `ParentDocument` = " . $Element['ParentDocument'] . " AND `ID` != '" . $Media['ID'] . "';");
                while ($element = mysql_fetch_assoc($Res)) {
                    //dump($element);
                    $eConfig = unserialize($element['Content']);
                    $preReport['ID'] = $element['ID'];
                    $preReport['Config'] = $eConfig;
                    $reportExports[] = $preReport;
                }
            } else {
                $preReport['ID'] = $Media['ID'];
                $preReport['Config'] = $Config;
                $reportExports[] = $preReport;
            }
            $input_params["return"] = isset($input_params["return"]) ? $input_params["return"] : false;
            foreach ($reportExports as $key => $reportExport) {
                //dump($_SESSION);
                $Continue = true;
                $Media['ID'] = $reportExport['ID'];
                $Config = $reportExport['Config'];
                foreach ($reportExport['Config']['_Field'] as $Key => $Value) {
                    if ($Value == 'viewitem_filter') {
                        if (empty($_SESSION['viewSelector_' . $Media['ID']])) {
                            $Continue = false;
                        }
                    }
                }
                if (!empty($Continue)) {
                    $limit = 'full';
                    if (!empty($_GET['limit'])) {
                        $limit = $_GET['limit'];
                    }
                    $OutData = dr_BuildReportGrid($Media['ID'], false, $_SESSION['report_' . $Media['ID']]['SortField'], $_SESSION['report_' . $Media['ID']]['SortDir'], 'pdf', $limit);
                    //vardump($OutData);
                    $CountStat = array();
                    if (is_array($OutData)) {
                        if ($key > 0) {
                            $report->addPage();
                        }
                        // outdata - Headings
                        $report->cf_report_headersMain($OutData, $Config);
                        if (!empty($OutData['Totals'])) {
                            foreach ($OutData['Totals'] as $Field => $Value) {
                                sort($fieldset);
                                $totalData[$Field] = $Value;
                            }
                            $report->cf_report_datagrid($totalData, 7);
                            unset($OutData['Totals']);
                        }
                    }
                    $report->cf_report_spacer();
                    $Headers = array();
                    if (!empty($OutData[0])) {
                        foreach ($OutData[0] as $Header => $v) {
                            if (strpos($Config['_IndexType'][$Header], 'hide') === false) {
                                if (!empty($Config['_FieldTitle'][$Header])) {
                                    $Headers[] = $Config['_FieldTitle'][$Header];
                                } else {
                                    $Headers[] = $Header;
                                }
                            }
                        }
                        $Total = count($OutData) - 1;
                        $Body = array();
                        $Counter = 1;
                        for ($i = 0; $i <= $Total; $i++) {
                            if (is_array($OutData[$i])) {
                                foreach ($OutData[$i] as $Field => $v) {
                                    if (strpos($Config['_IndexType'][$Field], 'hide') === false) {
                                        $Body[$i][] = str_replace('&nbsp;', '', html_entity_decode($v));
                                    }
                                }
                            }
                        }
                    }
                    $options["width"] = "100%";
                    $report->cf_report_data_col_grid($Headers, $Body, $OutData, $Config);
                    $report->cf_report_spacer();
                    //break;
                }
            }
            $report->cf_report_generate_output();
            mysql_close();
            exit;
        }
        if ($exportFormat == 'csv') {
            $CSVout = fopen('php://output', 'w');
            $prequery = explode('LIMIT', $_SESSION['queries'][$Media['ID']]);
            $sql_query = $prequery[0];
            $filename = uniqid(date('mdHis')) . '.csv';
            $out = '';
            // Gets the data from the database
            $result = mysql_query($sql_query);
            $fields_cnt = mysql_num_fields($result);
            //dump($Config['_Field']);
            //dump($Config);
            //exit;
            $VisibleFields = array();
            $FieldHeaders = array();
            foreach ($Config['_Field'] as $Field => $Value) {
                if ($Config['_IndexType'][$Field] == 'index_show' || $Config['_IndexType'][$Field] == 'noindex_show') {
                    $VisibleFields[] = $Field;
                    $FieldHeaders[] = $Config['_FieldTitle'][$Field];
                }
            }
            ob_start();
            fputcsv($CSVout, $FieldHeaders, ',') . "\r\n";
            $out .= ob_get_clean();
            while ($exportData = mysql_fetch_assoc($result)) {
                // run each field type on the result
                $Row = array();
                foreach ($Config['_Field'] as $Field => $Value) {
                    $FieldType = explode('_', $Value);
                    if (in_array($Field, $VisibleFields)) {
                        if (count($FieldType) == 2) {
                            // include fieldtype
                            if (file_exists(DB_TOOLKIT . '/data_form/fieldtypes/' . $FieldType[0] . '/functions.php')) {
                                include_once DB_TOOLKIT . '/data_form/fieldtypes/' . $FieldType[0] . '/functions.php';
                            }
                            // [type_processValue($Value, $Type, $Field, $Config, $EID, $Data)
                            $Func = $FieldType[0] . '_processvalue';
                            //$FieldValue =
                            $outRow = $exportData[$Field];
                            if (function_exists($Func)) {
                                // echo 'yes there is '.$Func.'<br>';
                                $Row[] = trim(strip_tags(str_replace('<br />', "\r\n", $Func($outRow, $FieldType[1], $Field, $Config, $Media['ID'], $exportData))));
                            } else {
                                $Row[] = $outRow;
                            }
                            //dump($FieldType);
                        } else {
                            $Row[] = $exportData[$Field];
                        }
                    }
                }
                //combine row
                ob_start();
                fputcsv($CSVout, $Row, ',') . "\r\n";
                $out .= ob_get_clean();
            }
            //while($export)
            // Format the data
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            //header("Content-Length: " . strlen($out));
            // Output to browser with appropriate mime type, you choose ;)
            //header("Content-type: text/x-csv");
            //header("Content-type: text/csv");
            header("Content-type: application/csv charset=UTF-8");
            header("Content-Disposition: attachment; filename={$filename}");
            //echo '<pre>';
            echo $out;
            //echo '</pre>';
            fclose($CSVout);
            mysql_close();
            exit;
        }
        if ($exportFormat == 'template') {
            echo dt_renderInterface($Media['ID']);
            exit;
        }
        if ($exportFormat != 'pdf') {
            $Element = getelement($Media['ID']);
            $Config = $Element['Content'];
            if (!empty($Config['_Show_Plugins'])) {
                // to do : configure adding plugins to the tool bar
                if (file_exists(DB_TOOLKIT . 'data_report/plugins/' . $exportFormat . '/functions.php')) {
                    include_once DB_TOOLKIT . 'data_report/plugins/' . $exportFormat . '/functions.php';
                    mysql_close();
                    exit;
                }
            }
        }
    }
}
Example #3
0
        $_SESSION['report_' . $Media['ID']]['SortField'] = $Config['_SortField'];
        $_SESSION['report_' . $Media['ID']]['SortDir'] = $Config['_SortDirection'];
    }
} else {
    $_SESSION['report_' . $Media['ID']]['SortField'] = $Config['_SortField'];
    $_SESSION['report_' . $Media['ID']]['SortDir'] = $Config['_SortDirection'];
}
if (!empty($Config['_Field'][$_SESSION['report_' . $Media['ID']]['SortDir']])) {
    //echo 'not';
}
if (!empty($_SESSION['reportFilters'][$Media['ID']]) || empty($Config['_SearchMode'])) {
    $gotTo = false;
    if (!empty($_GET['_pg'])) {
        $gotTo = $_GET['_pg'];
    }
    echo dr_BuildReportGrid($Media['ID'], $gotTo, $_SESSION['report_' . $Media['ID']]['SortField'], $_SESSION['report_' . $Media['ID']]['SortDir']);
    if (!empty($Config['_autoPolling'])) {
        $Rate = $Config['_autoPolling'] * 1000;
        $_SESSION['dataform']['OutScripts'] .= "\n                setInterval('dr_reloadData(\\'" . $Media['ID'] . "\\')', " . $Rate . ");\n        ";
    }
    /*
    * Experimental Graphing
    
    
     global $wpdb;
     $Query = dr_BuildReportGrid($Media['ID'], $gotTo, $_SESSION['report_'.$Media['ID']]['SortField'], $_SESSION['report_'.$Media['ID']]['SortDir'],'sql');
     //$Query = explode('LIMIT', $Query);
     //$Query = $Query[0];
     $rowData = $wpdb->get_results($Query, ARRAY_A);
     //vardump($rowData);
     $graphData =  "var data = [ ";
Example #4
0
        echo '<li><a ' . $class . ' href="' . $link[0] . '">All ' . $counter . '</a> | </li>';
        foreach ($fset as $tab) {
            $break = '';
            $counter = '';
            $class = '';
            if (!empty($_GET['ftab'])) {
                if ($_GET['ftab'] == $tab['code']) {
                    $class = 'class="current"';
                }
            }
            if ($index < $tablen) {
                $break = ' | ';
            }
            if ($tab['ShowCount'] == 'yes') {
                // need to do a counter only process
                $total = dr_BuildReportGrid($Interface['ID'], false, false, false, 'count', true, $tab['Filters']);
                //unset($_SESSION['reportFilters'][$Interface['ID']]);
                $counter = ' <span class="count">(<span class="' . $tab['code'] . '">' . $total . '</span>)</span> ';
            }
            $link = explode('&ftab', $_SERVER['REQUEST_URI']);
            echo '<li><a ' . $class . ' href="' . $link[0] . '&ftab=' . $tab['code'] . '">' . $tab['Title'] . $counter . '</a>' . $break . '</li>';
            $index++;
        }
        ?>

        </ul>
<?php 
    }
    ?>

    <div class="clear"></div>
Example #5
0
function di_showItem($EID, $Item, $Setup = false)
{
    $Element = getelement($EID);
    $Config = $Element['Content'];
    $queryJoin = '';
    $queryWhere = array();
    $queryLimit = '';
    $querySelects = array();
    $WhereTag = '';
    $groupBy = '';
    $orderStr = '';
    $countSelect = '';
    // setup columns
    if (!empty($Config['_FormLayout'])) {
        parse_str($Config['_FormLayout'], $Columns);
        if (empty($Columns['FieldList_left'])) {
            unset($Columns);
            unset($Config['_FormLayout']);
        }
    }
    //setup Field Types
    foreach ($Config['_Field'] as $Field => $Type) {
        // explodes to:
        // [0] = Field plugin dir
        // [1] = Field plugin type
        $Config['_Field'][$Field] = explode('_', $Type);
    }
    // field type filters
    $joinIndex = 'a';
    foreach ($Config['_IndexType'] as $Field => $Type) {
        $querySelects[$Field] = 'prim.`' . $Field . '`';
    }
    if (!empty($Config['_CloneField'])) {
        foreach ($Config['_CloneField'] as $CloneKey => $Clone) {
            //echo 'BEFORE';
            //vardump($querySelects);
            foreach ($querySelects as $selectKey => $selectScan) {
                $queryJoin = str_replace($CloneKey, $Clone['Master'], $queryJoin);
                $WhereTag = str_replace($CloneKey, $Clone['Master'], $WhereTag);
                if (strstr($selectScan, " AS ") === false) {
                    //echo $Clone['Master'].' - concat <br />';
                    if (strstr($selectScan, "_sourceid_") === false) {
                        $querySelects[$selectKey] = str_replace($CloneKey, $Clone['Master'] . '` AS `' . $CloneKey, $selectScan);
                    }
                }
            }
            //echo 'After';
            //vardump($querySelects);
        }
    }
    // Build Query
    foreach ($Config['_Field'] as $Field => $Type) {
        // Run Filters that have been set through each field type
        if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Type[0] . '/queryfilter.php')) {
            include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Type[0] . '/queryfilter.php';
        }
        //apply a generic keyword filter to each field is a key word has been sent
        if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
            if ($WhereTag == '') {
                $WhereTag = " WHERE ";
            }
            $keyField = 'prim.' . $Field;
            if (strpos($querySelects[$Field], ' AS ') !== false) {
                $keyField = strtok($querySelects[$Field], ' AS ');
            }
            $preWhere[] = $keyField . " LIKE '%" . $_SESSION['reportFilters'][$EID]['_keywords'] . "%' ";
            //dump($_SESSION['reportFilters'][$EID]);
        }
        $joinIndex++;
    }
    //post clone fixes
    foreach ($querySelects as $fieldToFix => $select) {
        if (!empty($Config['_CloneField'][$fieldToFix])) {
            $cloneReturns[$fieldToFix] = explode(' AS ', $select);
        }
    }
    if (!empty($cloneReturns)) {
        foreach ($cloneReturns as $cloneKey => $cloneField) {
            $pureName = trim(str_replace('prim.', '', $cloneField[0]), '`');
            if (!empty($cloneReturns[$pureName])) {
                $cloneReturns[$cloneKey][0] = $cloneReturns[$pureName][0];
                $querySelects[$cloneKey] = implode(' AS ', $cloneReturns[$cloneKey]);
            }
        }
    }
    // create Query Selects and Where clause string
    $querySelect = implode(',', $querySelects);
    if (!empty($Setup)) {
        $queryWhere = 'prim.' . $Setup['_filterField'] . ' = \'' . $Item . '\'';
    } else {
        $queryWhere = 'prim.' . $Config['_ReturnFields'][0] . ' = \'' . $Item . '\'';
    }
    if (!empty($queryWhere)) {
        $WhereTag = " WHERE ";
    } else {
        $WhereTag = "";
    }
    if (is_array($groupBy)) {
        $groupBy = 'GROUP BY (' . implode(',', $groupBy) . ')';
        $countLimit = '';
        $entryCount = true;
        //add totals selects to count
        if (is_array($countSelect)) {
            $countSelect = ',' . implode(',', $countSelect);
        }
    }
    $Query = "SELECT " . $querySelect . " FROM `" . $Config['_main_table'] . "` AS prim \n " . $queryJoin . " \n " . $WhereTag . " \n " . $queryWhere . "\n " . $groupBy . " \n " . $orderStr . " \n LIMIT 1;";
    // Wrap fields with ``
    //foreach($querySelects as $Field=>$FieldValue){
    //   $Query = str_replace($Field, '`'.$Field.'`', $Query);
    //}
    // Query Results
    //$Res = mysql_query($Query);
    //echo $Query.'<br /><br /><br />';
    //echo mysql_error();
    //vardump($Config['_ReturnFields']);
    //$Data = mysql_fetch_assoc($Res);
    $Data = dr_BuildReportGrid($EID, false, false, false, 'data', false, array($Config['_ReturnFields'][0] => $Item));
    if (!empty($Config['_UseViewTemplate'])) {
        //dump($Config);
        $PreReturn = $Config['_ViewTemplateContentWrapperStart'];
        $PreReturn .= $Config['_ViewTemplatePreContent'];
        $PreReturn .= $Config['_ViewTemplateContent'];
        $PreReturn .= $Config['_ViewTemplatePostContent'];
        $PreReturn .= $Config['_ViewTemplateContentWrapperEnd'];
        //echo $Config['_ViewTemplateContent'];
        $newTitle = 'View Item';
        if (!empty($Config['_ViewFormText'])) {
            $newTitle = $Config['_ViewFormText'];
        }
        foreach ($Config['_Field'] as $Field => $Types) {
            if (!empty($Config['_ViewFormText'])) {
                //dump($Data);
                if (!empty($Data['_outvalue'][$Field])) {
                    $newTitle = str_replace('{{' . $Field . '}}', $Data['_outvalue'][$Field], $newTitle);
                } else {
                    $newTitle = str_replace('{{' . $Field . '}}', $Data[$Field], $newTitle);
                }
            }
            //	dump($Type);
            if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/conf.php')) {
                if (!empty($Config['_FieldTitle'][$Field])) {
                    $name = $Config['_FieldTitle'][$Field];
                } else {
                    $name = df_parseCamelCase($Field);
                }
                $PreReturn = str_replace('{{_' . $Field . '_name}}', $name, $PreReturn);
                if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/output.php')) {
                    $Out = false;
                    include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/output.php';
                    $PreReturn = str_replace('{{' . $Field . '}}', $Out, $PreReturn);
                }
                $PreReturn = str_replace('{{_PageID}}', $Element['ParentDocument'], $PreReturn);
                $PreReturn = str_replace('{{_PageName}}', getdocument($Element['ParentDocument']), $PreReturn);
                $PreReturn = str_replace('{{_EID}}', $EID, $PreReturn);
            }
        }
        $Output['title'] = $newTitle;
        $Output['width'] = $Config['_popupWidthview'];
        $Output['html'] = $PreReturn;
        return $Output;
    }
    //dump($Data);
    $Row = 'list_row2';
    $LeftColumn = '';
    $RightColumn = '';
    $FarRightColumn = '';
    //vardump($Config);
    //dump($Config['_Field']);
    if (!empty($Config['_gridViewLayout'])) {
        //$Config['_gridViewLayout'] = str_replace('=viewrow', '=row', $Config['_gridLayoutView']);
        parse_str($Config['_gridViewLayout'], $Layout);
        //vardump($Config['_gridView']);
        //vardump($Layout);
        $Form = '';
        $CurrRow = '0';
        $CurrCol = '0';
        $Index = 0;
        $newTitle = 'View Item';
        if (!empty($Config['_ViewFormText'])) {
            $newTitle = $Config['_ViewFormText'];
        }
        //dump($Setup);
        foreach ($Config['_gridView'] as $row => $cols) {
            $Form .= "<div style=\"clear: both;\" class=\"view-gen-row\" id=\"pg-view-" . $row . "\">\n";
            foreach ($cols as $col => $width) {
                $Form .= "<div class=\"view-" . $row . "-" . $col . "\" style=\"float: left; overflow: hidden; width: " . $width . ";\">\n";
                $Form .= "<div id=\"pg-view-" . $row . "-" . $col . "\" class=\"view-gen-row view-gen-col view-col-" . $col . "\">\n";
                // check for section breaks
                $contentKeys = array_keys($Layout, $row . '_' . $col);
                foreach ($contentKeys as $Field) {
                    $Field = str_replace('View_Field_', '', $Field);
                    $FieldSet = $Config['_Field'][$Field];
                    if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/conf.php') && count($FieldSet) == 2) {
                        include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/conf.php';
                        if (!empty($FieldTypes[$FieldSet[1]]['visible']) && (empty($Config['_CloneField'][$Field]) || !empty($FieldTypes[$FieldSet[1]]['cloneview']))) {
                            // Check if is visible or not
                            $Out = false;
                            $Type = $FieldSet[1];
                            $Types = $FieldSet;
                            $Form .= "<label class=\"view-gen-lable singletext\" for=\"entry_" . $Element['ID'] . "_" . $Field . "\" id=\"lable_" . $Element['ID'] . "_" . $Field . "\">" . $Config['_FieldTitle'][$Field] . "</label>\n";
                            $Form .= "<div class=\"view-gen-field-data-wrapper\" id=\"view-data-" . $Field . "\">\n";
                            //$Val = $Defaults[$Field];]
                            include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/output.php';
                            //$Form = str_replace('{{'.$Field.'}}', $Out, $Form);
                            $Form .= $Out;
                            $Form .= "&nbsp;</div>\n";
                            $Form .= "<span class=\"description\" id=\"caption_" . $Element['ID'] . "_" . $Field . "\">\n";
                            $Form .= $Config['_FieldCaption'][$Field] . '&nbsp';
                            $Form .= "</span>\n";
                        } else {
                            if (empty($FieldTypes[$FieldSet[1]]['visible'])) {
                                ob_start();
                                $Val = $Defaults[$Field];
                                include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/input.php';
                                $Hidden .= ob_get_clean();
                            }
                        }
                    } else {
                        if (!empty($Config['_SectionBreak'][$Field])) {
                            $Form .= "<div class=\"sectionbreak\">\n";
                            $Form .= "<h2>" . $Config['_SectionBreak'][$Field]['Title'] . "</h2>\n";
                            if (!empty($Config['_SectionBreak'][$Field]['Caption'])) {
                                $Form .= "<span class=\"description\">" . $Config['_SectionBreak'][$Field]['Caption'] . "</span>\n";
                            }
                            $Form .= "</div>\n";
                        }
                        $Form .= '&nbsp;';
                    }
                }
                if (empty($contentKeys)) {
                    $Form .= '&nbsp;';
                }
                $Form .= "</div>\n";
                $Form .= "</div>\n";
            }
            $Form .= "</div>\n";
        }
        $Form .= '<div style="clear:left;"></div>';
        $Shown = '';
        // add title
        if (!empty($Config['_ViewFormText'])) {
            //dump($Data);
            if (!empty($Data['_outvalue'][$Field])) {
                $newTitle = str_replace('{{' . $Field . '}}', $Data['_outvalue'][$Field], $newTitle);
            } else {
                $newTitle = str_replace('{{' . $Field . '}}', $Data[$Field], $newTitle);
            }
            $Output['title'] = $newTitle;
        }
        $Output['width'] = '420';
        if (!empty($Config['_popupWidthview'])) {
            $Output['width'] = $Config['_popupWidthview'];
        }
        $Output['html'] = '<div class="formular">' . $Form . '</div>';
        if (!empty($Config['_Show_Edit'])) {
            $OutPut['edit'] = true;
        }
        return $Output;
    }
    if (!empty($Config['_FormLayout'])) {
        parse_str($Config['_FormLayout'], $Columns);
        if (empty($Columns['FieldList_left'])) {
            unset($Columns);
            unset($Config['_FormLayout']);
        }
    }
    if (!empty($Columns)) {
        foreach ($Columns as $Key => $Side) {
            if ($Key == 'FieldList_Main') {
                $ColumnSet = 'LeftColumn';
            }
            if ($Key == 'FieldList_left') {
                $ColumnSet = 'RightColumn';
            }
            if ($Key == 'FieldList_right') {
                $ColumnSet = 'FarRightColumn';
            }
            foreach ($Side as $Entry) {
                if (substr($Entry, 0, 12) != 'SectionBreak') {
                    $Row = dais_rowSwitch($Row);
                    $Field = $Entry;
                    $Types = $Config['_Field'][$Field];
                    ${$ColumnSet} .= $FieldSet[1];
                    //ob_start();
                    //dump($Config['_Field']);
                    //$$ColumnSet = ob_get_clean();
                    //$$ColumnSet .= $FieldSet[0].'<br />';
                    if (!empty($Config['_FieldTitle'][$Field])) {
                        $FieldTitle = $Config['_FieldTitle'][$Field];
                    } else {
                        $FieldTitle = df_parsecamelcase($Field);
                    }
                    if (!empty($Types[1])) {
                        include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/conf.php';
                        if ($FieldTypes[$Types[1]]['visible'] == true) {
                            $Out = false;
                            $Out = '<div id="lable_' . $Element['ID'] . '_' . $Field . '" for="entry_' . $Element['ID'] . '_' . $Field . '" class="view-gen-lable"><strong>' . $FieldTitle . '</strong></div>';
                            include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/output.php';
                            ${$ColumnSet} .= $Out;
                        }
                    }
                } else {
                    ${$ColumnSet} .= '<h3>' . $Config['_SectionBreak']['_' . $Entry] . '</h3>';
                }
            }
        }
    } else {
        foreach ($Config['_Field'] as $Field => $Types) {
            $Row = dais_rowswitch($Row);
            if (!empty($Types[1])) {
                if (!empty($Config['_FieldTitle'][$Field])) {
                    $FieldTitle = $Config['_FieldTitle'][$Field];
                } else {
                    $FieldTitle = df_parsecamelcase($Field);
                }
                include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/conf.php';
                if ($FieldTypes[$Types[1]]['visible'] == true) {
                    $Out = false;
                    $Out = '<div id="lable_' . $Element['ID'] . '_' . $Field . '" for="entry_' . $Element['ID'] . '_' . $Field . '" class="view-gen-lable"><strong>' . $FieldTitle . '</strong></div>';
                    include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Types[0] . '/output.php';
                    //echo $Out;
                    if (!empty($Columns)) {
                        if (in_array($Field, $Columns['FieldList_Main'])) {
                            $LeftColumn .= $Out;
                        } elseif (in_array($Field, $Columns['FieldList_left'])) {
                            $RightColumn .= $Out;
                        }
                    } else {
                        $RightColumn .= $Out;
                    }
                }
            }
        }
    }
    if (!empty($Config['_titleField'])) {
        //infobox($Setup['_Prefix'].$Data[$Setup['_titleField']].$Setup['Suffix']);
        $OutPut['title'] = $Config['_Prefix'] . $Data[$Config['_titleField']] . $Config['Suffix'];
    } else {
        //echo '<h2>View Entry</h2>';
        $OutPut['title'] = 'View Entry';
        //$Setup['_Prefix'].$Data[$Setup['_titleField']].$Setup['Suffix'];
    }
    $Return = '<table width="100%" border="0" cellspacing="0" cellpadding="2">
		<tr>';
    $OutPut['width'] = 300;
    if (!empty($LeftColumn)) {
        $ColWidth = '33';
        if (empty($FarRightColumn)) {
            $ColWidth = '50';
        }
        $Return .= '<td width="' . $ColWidth . '%" valign="top">' . $LeftColumn . '</td>';
        $OutPut['width'] = $OutPut['width'] + 100;
    }
    if (!empty($RightColumn)) {
        $Return .= '<td valign="top">' . $RightColumn . '</td>';
        $OutPut['width'] = $OutPut['width'] + 100;
    }
    if (!empty($FarRightColumn)) {
        $Return .= '<td width="33%" valign="top">' . $FarRightColumn . '</td>';
        $OutPut['width'] = $OutPut['width'] + 100;
    }
    $Return .= '</tr>';
    $Return .= '</table>';
    if (!empty($Config['_Show_Edit'])) {
        $OutPut['edit'] = true;
        //$Return .= '<input type="button" value="Edit" class="close" onclick="dr_BuildUpDateForm('.$EID.', '.$Item.');" />';
    }
    if (!empty($Config['_EnableAudit'])) {
        $revres = mysql_query("SELECT count(_ID) as Rev FROM `_audit_" . $Config['_main_table'] . "` WHERE `" . $Config['_ReturnFields'][0] . "` = '" . $Data[$Config['_ReturnFields'][0]] . "';");
        if ($revres) {
            if (mysql_num_rows($revres) == 1) {
                $R = mysql_fetch_assoc($revres);
                $Return .= '<div class="captions">Revision ' . $R['Rev'] . '</div>';
            }
        }
    }
    $OutPut['html'] = $Return;
    return $OutPut;
}
Example #6
0
<h2>Query Tuning</h2>
        
        <span class="description">Customize the generated query to get the most of your results.</span>
        <div class="warning">WARNING: improper setting of the query can and will result in malfunction.<br/>
        To Reset: Clear the custom query and save.</div>
        
        <div class="controls">
        <textarea style="width: 100%;" rows="20" name="Data[Content][_QueryOveride]"><?php 
if (!empty($Element['ID'])) {
    if (!empty($Element['Content']['_QueryOveride'])) {
        $query = $Element['Content']['_QueryOveride'];
    } else {
        $query = dr_BuildReportGrid($Element['ID'], false, false, false, 'sql');
    }
    preg_match('/(LIMIT [ 0-9]+,[ 0-9]+)/', $query, $Limits);
    if (!empty($Limits[0])) {
        $query = str_replace($Limits[0], '', $query);
    } else {
        $query .= $queryLimit;
    }
    echo str_replace(';', '', $query);
}
?>
</textarea>
        </div>
        <?php 
$Sel = '';
if (!empty($Element['Content']['_UserQueryOveride'])) {
    $Sel = 'checked="checked"';
}
echo dais_customfield('checkbox', 'Use Overide', '_UserQueryOveride', '_UserQueryOveride', 'list_row1', 1, $Sel, 'Use the "Tuned" Query.');
Example #7
0
         if (strtolower($Format) != 'xml' && strtolower($Format) != 'json' && strtolower($Format) != 'html') {
             api_Deny();
         }
         //header("content-type: text/" . strtolower($Format));
         //($EID, $Page = false, $SortField = false, $SortDir = false, $Format = false, $limitOveride = false)
         $Return = false;
         if (!empty($_GET['itemID'])) {
             $Return = array($Config['_ReturnFields'][0] => $_GET['itemID']);
         }
         if (!empty($_POST['itemID'])) {
             $Return = array($Config['_ReturnFields'][0] => $_POST['itemID']);
         }
         if ($Format == 'html') {
             $Format = false;
         }
         echo dr_BuildReportGrid($interfaceID, $Page, false, false, strtolower($Format), $Limit, $Return);
         exit;
     }
     break;
 case 'insert':
     if (empty($Config['_APIMethodInsert'])) {
         api_Deny();
         exit;
     }
     if (!empty($_POST)) {
         $result = df_processInsert($interfaceID, $_POST);
         echo json_encode($result);
     } else {
         $Return['Message'] = 'No Data submitted';
         echo json_encode($Return);
     }
Example #8
0
function dr_BuildReportGrid($EID, $Page = false, $SortField = false, $SortDir = false, $Format = false, $limitOveride = false, $wherePush = false, $getOverride = false)
{
    // get element
    $Element = getelement($EID);
    $Config = $Element['Content'];
    if (!empty($Config['_customFooterJavaScript']) && empty($Format)) {
        $_SESSION['dataform']['OutScripts'] .= "\n            " . stripslashes_deep($Config['_customFooterJavaScript']) . "\n        ";
    }
    if (!empty($getOverride)) {
        parse_str($getOverride, $_GET);
    }
    //Filters will be picked up via Session value
    // Set Vars
    if (empty($Page)) {
        $Page = 1;
    }
    if (!empty($Format)) {
        // XML Output
        if (strtolower($Format) == 'xml') {
            $apiOut = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
            $apiOut .= "    <entries>\n";
        }
        //json output
        if (strtolower($Format) == 'json') {
            $jsonIndex = 0;
            $apiOutput = array();
            $apiOutput['page'] = $Page;
            $apiOutput['totalpages'] = '';
            $apiOutput['totalentries'] = '';
            $apiOutput['entrycount'] = '';
            $apiOutput['entries'] = array();
        }
        if (strtolower($Format) == 'pdf') {
            $pdfIndex = 0;
            $apiOutput = array();
            if (!empty($_SESSION['reportFilters'][$EID])) {
                $apiOutput['filters'] = $_SESSION['reportFilters'][$EID];
            }
        }
    }
    //global $ReportReturn;
    $ReportReturn = '';
    if (empty($Config['_main_table'])) {
        return 'No Table Selected';
    }
    $queryJoin = '';
    $queryJoins = array();
    $queryWhere = array();
    $queryLimit = '';
    $querySelects = array();
    $WhereTag = '';
    $groupBy = '';
    $orderStr = '';
    $countSelect = '';
    $countLimit = 'LIMIT 1';
    $isModal = 'false';
    if (!empty($Config['_popupTypeView'])) {
        if ($Config['_popupTypeView'] == 'modal') {
            $isModal = true;
        }
    }
    // Setup Totals Fields
    if (!empty($Config['_TotalsField'])) {
        foreach ($Config['_TotalsField'] as $key => $Field) {
            if (!empty($Config['_TotalsFieldTitle'][$key])) {
                $Title = str_replace(' ', '', ucwords($Config['_TotalsFieldTitle'][$key]));
            } else {
                $Title = $Field . 'Total';
            }
            //if($Config['_TotalsFieldLocation'][$key] == 'inline'){
            $Config['_Field'][$Title] = 'totals_' . $Config['_TotalsFieldType'][$key];
            $Config['_IndexType'][$Title] = 'index_show';
            $Config['_Justify'][$Title] = $Config['_TotalsFieldJustify'][$key];
            //}else{
            $Config['_TotalsFields'][$Title][$Config['_TotalsFieldType'][$key]] = 0;
            //}
            // Create easy sorting array
            $Config['_TotalsFields'][$Title]['Type'] = $Config['_TotalsFieldType'][$key];
            $Config['_TotalsFields'][$Title]['Grouping'] = $Config['_TotalsGroupingField'][$key];
            $Config['_TotalsFields'][$Title]['Location'] = $Config['_TotalsFieldLocation'][$key];
            $Config['_TotalsFields'][$Title]['Function'] = $Config['_TotalsFieldFunction'][$key];
            $Config['_TotalsFields'][$Title]['Prefix'] = $Config['_TotalsFieldPrefix'][$key];
            $Config['_TotalsFields'][$Title]['Suffix'] = $Config['_TotalsFieldSuffix'][$key];
            $Config['_TotalsFields'][$Title]['PrimField'] = $Field;
            //dump($Config['_TotalsFieldTitleWidth']);
            if (!empty($Config['_TotalsFieldTitleWidth'][$key])) {
                $Config['_WidthOverride'][$Title] = $Config['_TotalsFieldTitleWidth'][$key];
            }
            if (!empty($Config['_TotalsFieldCaption'][$key])) {
                $Config['_TotalsFields'][$Title]['Caption'] = $Config['_TotalsFieldCaption'][$key];
            }
            $Config['_TotalsFields'][$Title]['Title'] = $Title;
            unset($Title);
        }
        //unset($Config['_TotalsFieldType']);
        //unset($Config['_TotalsFieldLocation']);
        //unset($Config['_TotalsFieldTitle']);
        //unset($Config['_TotalsField']);
    }
    if (!empty($Page)) {
        $_SESSION['report_' . $EID]['LastPage'] = $Page;
    } else {
        if (empty($_SESSION['report_' . $EID]['LastPage']) || $_SESSION['report_' . $EID]['LastPage'] == 'undefined') {
            $_SESSION['report_' . $EID]['LastPage'] = 1;
        }
        $Page = $_SESSION['report_' . $EID]['LastPage'];
    }
    if (!empty($SortDir)) {
        $_SESSION['report_' . $EID]['SortDir'] = $SortDir;
    }
    if (!empty($SortField)) {
        $_SESSION['report_' . $EID]['SortField'] = $SortField;
    }
    //setup Field Types
    foreach ($Config['_Field'] as $Field => $Type) {
        if (empty($Type)) {
            //$querySelects[$Field] = $Field;
        }
        // explodes to:
        // [0] = Field plugin dir
        // [1] = Field plugin type
        $Config['_Field'][$Field] = explode('_', $Type);
    }
    //SetupHeaders
    // Start Table
    // Check for template
    $customClass = '';
    if (!empty($Config['_ListTableClass'])) {
        $customClass = $Config['_ListTableClass'];
    }
    $tableClass = 'class="data_report_Table ' . $customClass . '"';
    if (is_admin()) {
        $tableClass = 'class="widefat data_report_Table_admin ' . $customClass . '"';
    }
    $ReportReturn .= '<table width="100%" border="0" cellspacing="0" cellpadding="4" ' . $tableClass . ' id="data_report_' . $EID . '" style="cursor:default;">';
    //Start Headers Row
    //$ReportReturn .= '<caption>'.$Config['_ReportTitle'].'</caption>';
    $ReportReturn .= '<thead>';
    $ReportReturn .= '<tr>';
    foreach ($Config['_IndexType'] as $Field => $Type) {
        //echo 'ping';
        //Seperate Index/Display Types
        $Config['_IndexType'][$Field] = explode('_', $Type);
        // Totals Location check to see if field is inline or not.
        $Location = 'inline';
        if (!empty($Config['_TotalsFields'][$Field]['Location'])) {
            $Location = $Config['_TotalsFields'][$Field]['Location'];
        }
        if ($Config['_IndexType'][$Field][1] == 'show' && ($Location == 'inline' || $Location == 'headerinline' || $Location == 'footerinline') && empty($wherePush)) {
            //Set Widths
            $Direction = 'ASC';
            if (key_exists('SortDir', $_SESSION['report_' . $EID])) {
                if ($_SESSION['report_' . $EID]['SortDir'] == 'ASC') {
                    $Direction = 'DESC';
                }
            }
            $sortClass = 'report_header';
            if (key_exists('SortFIeld', $_SESSION['report_' . $EID])) {
                if ($_SESSION['report_' . $EID]['SortField'] == $Field) {
                    $sortClass = 'sorting_' . $_SESSION['report_' . $EID]['SortDir'];
                }
            }
            // set the column Title
            $fieldTitle = $Field;
            if (!empty($Config['_TotalsFields'][$Field]['Title'])) {
                $fieldTitle = $Config['_TotalsFields'][$Field]['Title'];
            }
            if (empty($Config['_WidthOverride'][$Field])) {
                $Config['_WidthOverride'][$Field] = '';
            }
            $ReportReturn .= '<th nowrap="nowrap" scope="col" width="' . ($Config['_WidthOverride'][$Field] == '' ? '{{width_' . $Field . '}}px' : $Config['_WidthOverride'][$Field] . 'px') . '" ';
            if (!empty($Config['_Sortable'][$Field])) {
                $ReportReturn .= 'onclick="dr_sortReport(\'' . $EID . '\', \'' . $Field . '\', \'' . $Direction . '\');" class="' . $sortClass . '"';
            }
            $ReportReturn .= '>';
            if (!empty($Config['_FieldTitle'][$Field])) {
                $ReportReturn .= '<span>' . $Config['_FieldTitle'][$Field] . '</span>';
            } else {
                $ReportReturn .= '<span>' . df_parseCamelCase($fieldTitle) . '</span>';
            }
            $ReportReturn .= '</th>';
            // Preset the selects from query
            $querySelects[$Field] = $Field;
            // 'prim.`' . $Field . '`';
            // Set average width and min width
            $minWidth[$Field] = strlen($fieldTitle) * 8;
            $AvrageWidth[$Field] = array();
            $AvrageWidth[$Field][] = $minWidth[$Field];
        }
        if (!empty($wherePush)) {
            $querySelects[$Field] = $Field;
            //'prim.`' . $Field . '`';
        }
    }
    // Add the return field to select
    if (!empty($Config['_ReturnFields'])) {
        //$querySelects[$Config['_ReturnFields'][0]] = 'prim.'.$Config['_ReturnFields'][0];
        foreach ($Config['_ReturnFields'] as $Field) {
            $newField = '_return_' . $Field;
            $querySelects[$newField] = $Field;
            //'prim.`' . $Field . '`';
        }
    }
    if (empty($Config['_Show_popup'])) {
        if (!empty($Config['_Show_Edit']) && empty($Config['_ItemViewPage']) || !empty($Config['_Show_Delete']) || !empty($Config['_Show_View']) || !empty($Config['_Show_Edit'])) {
            $ShowActionPanel = true;
        }
        if (!empty($ShowActionPanel)) {
            $ReportReturn .= '<th scope="col">';
            $ReportReturn .= 'Action';
            $ReportReturn .= '</th>';
        }
    }
    $ReportReturn .= '</tr>';
    $ReportReturn .= '</thead>';
    // End Headers setup
    // Build Query
    // field type filters
    $joinIndex = 'a';
    foreach ($Config['_Field'] as $Field => $Type) {
        //set filter for auto values
        if ($Type[0] == 'hidden') {
            if (!empty($_SESSION['reportFilters'][$EID][$Field])) {
                if ($WhereTag == '') {
                    $WhereTag = " WHERE ";
                }
                $queryWhere[] = "prim.`" . $Field . "` = '" . $_SESSION['reportFilters'][$EID][$Field] . "'";
            }
        }
        // Run Filters that have been set through each field type
        if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Type[0] . '/queryfilter.php')) {
            include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $Type[0] . '/queryfilter.php';
        }
        if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
            if ($WhereTag == '') {
                $WhereTag = " WHERE ";
            }
            $keyField = 'prim.`' . $Field . '`';
            $preWhere[] = $keyField . " LIKE '%" . $_SESSION['reportFilters'][$EID]['_keywords'] . "%' ";
        }
        //}
        $joinIndex++;
    }
    // combine keyword search if there are any
    if (!empty($preWhere)) {
        $queryWhere[] = '(' . implode(' OR ', $preWhere) . ')';
    }
    if (!empty($wherePush)) {
        if ($WhereTag == '') {
            $WhereTag = " WHERE ";
        }
        foreach ($wherePush as $wField => $wVal) {
            $queryWhere[] = 'prim.`' . $wField . '` = \'' . $wVal . '\'';
        }
    }
    // create Query Selects and Where clause string
    $querySelects = dr_processQuery($Config, $querySelects);
    if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
        if ($WhereTag == '') {
            $WhereTag = " WHERE ";
        }
        foreach ($querySelects as $Key => $Field) {
            if (!empty($Config['_IndexType'][$Field][0])) {
                echo $Field . '<br />';
                $preWhere[] = $Field . " LIKE '%" . $_SESSION['reportFilters'][$EID]['_keywords'] . "%' ";
                // explode and serach parts
                $parts = explode(',', $_SESSION['reportFilters'][$EID]['_keywords']);
                foreach ($parts as $Part) {
                    $preWhere[] = $Field . " LIKE '%" . trim($Part) . "%' ";
                }
                // explode and serach parts
                $parts = explode(', ', $_SESSION['reportFilters'][$EID]['_keywords']);
                foreach ($parts as $Part) {
                    $preWhere[] = $Field . " LIKE '%" . trim($Part) . "%' ";
                }
            }
        }
    }
    //vardump($Config['_CloneField']);    //vardump($querySelects);
    $preSelects = array();
    foreach ($querySelects as $AS => $selectField) {
        $preSelects[] = $selectField . ' AS `' . $AS . '`';
    }
    $querySelect = implode(", \n", $preSelects);
    $queryWhere = implode(' AND ', $queryWhere);
    // create sort fields
    if (!empty($Config['_SortField'])) {
        if (key_exists('SortFields', $_SESSION['report_' . $EID]) && !empty($querySelects[$_SESSION['report_' . $EID]['SortField']])) {
            $orderStr = 'ORDER BY `' . $_SESSION['report_' . $EID]['SortField'] . '` ' . $_SESSION['report_' . $EID]['SortDir'];
        } else {
            $orderStr = 'ORDER BY prim.`' . $Config['_SortField'] . '` ' . $Config['_SortDirection'] . '';
        }
    }
    // create joins and on
    $pattern = 'prim.`(__[a-zA-Z0-9]+)`';
    preg_match_all('/' . $pattern . '/s', $queryJoin, $matches);
    foreach ($matches[0] as $key => $Match) {
        $queryJoin = str_replace($Match, $querySelects[$matches[1][$key]], $queryJoin);
    }
    // Build the grouping if ther are any
    if (is_array($groupBy)) {
        $preGroup = array();
        foreach ($groupBy as $groupField => $preField) {
            if (!empty($querySelects[$groupField])) {
                $preGroup[] = $querySelects[$groupField];
            } else {
                if (strpos($preField, '.') === false) {
                    $preField = 'prim.' . $preField . '';
                }
                $preGroup[] = $preField;
            }
        }
        $groupBy = 'GROUP BY (' . implode('),(', $preGroup) . ')';
        $countLimit = '';
        $entryCount = true;
        //add totals selects to count
        if (is_array($countSelect)) {
            $countSelect = ',' . implode(',', $countSelect);
        }
    }
    // Build WHERES - prim.clones
    $pattern = 'prim.`(__[a-zA-Z0-9]+)`';
    preg_match_all('/' . $pattern . '/s', $queryWhere, $matches);
    foreach ($matches[0] as $key => $Match) {
        if (!empty($querySelects['_sourceid_' . $matches[1][$key]])) {
            $queryWhere = str_replace($Match, $querySelects['_sourceid_' . $matches[1][$key]], $queryWhere);
        } else {
            $replace = dr_findCloneParent($matches[1][$key], $Config['_CloneField'], $querySelects);
            if (strpos($replace, '.') === false) {
                $replace = 'prim.`' . $replace . '`';
            }
            $queryWhere = str_replace($Match, $replace, $queryWhere);
        }
    }
    //return;
    // Totals Query & Results
    //dump($querySelects);
    if (!empty($Config['_CloneField'][$Config['_ReturnFields'][0]])) {
        $countSelect = dr_findCloneParent($Config['_ReturnFields'][0], $Config['_CloneField'], $querySelects);
    } else {
        $countSelect = $Config['_ReturnFields'][0];
    }
    if (strpos($countSelect, '.') === false) {
        $countSelect = 'prim.`' . $countSelect . '`';
    }
    // get done queries
    global $wpdb;
    //dump($Queries);
    // Custom WHERE
    $customWhere = '';
    if (!empty($Config['_useCustomWhere'])) {
        if ($WhereTag == '') {
            $WhereTag = " WHERE ";
        }
        $preWhere = '';
        foreach ($Config['_customWHERE'] as $cwhere) {
            if (!empty($queryWhere)) {
                $queryWhere = '(' . $queryWhere . ')';
                $preWhere .= ' ' . $cwhere['_Req'] . ' ';
            }
            $preWhere .= '(' . $cwhere['_Where'] . ')';
        }
        $queryWhere .= $preWhere;
    }
    $CountQuery = "SELECT count(" . $countSelect . ") as Total FROM `" . $Config['_main_table'] . "` AS prim \n " . $queryJoin . " \n " . $WhereTag . " \n " . $queryWhere . " \n " . $groupBy . "\n\n " . $countLimit . ";";
    $CountResult = mysql_query($CountQuery);
    if (!empty($entryCount)) {
        // Countr Rows
        while ($prCount = mysql_fetch_assoc($CountResult)) {
            $preCount[] = $prCount['Total'];
        }
        if (!empty($preCount)) {
            $Count['TotalEntries'] = array_sum($preCount);
            unset($prCount);
            unset($preCount);
        } else {
            $Count['TotalEntries'] = 0;
        }
        $Count['Total'] = mysql_num_rows($CountResult);
    } else {
        // get Count entry
        if (!empty($CountResult)) {
            $Count = mysql_fetch_assoc($CountResult);
            mysql_free_result($CountResult);
        } else {
            $Count = 0;
        }
    }
    if (!empty($limitOveride) && $limitOveride != 'full') {
        $Config['_Items_Per_Page'] = $limitOveride;
    }
    if (!empty($_SESSION['report_' . $EID]['limitOveride'])) {
        $Config['_Items_Per_Page'] = floatval($_SESSION['report_' . $EID]['limitOveride']);
    }
    if (!empty($Config['_Items_Per_Page'])) {
        $TotalPages = ceil($Count['Total'] / $Config['_Items_Per_Page']);
        $Start = $Page * $Config['_Items_Per_Page'] - $Config['_Items_Per_Page'];
        $Offset = $Config['_Items_Per_Page'];
        if ($Page > 0) {
            if ($Page > $TotalPages) {
                $Page = $TotalPages;
                $Start = $Page * $Config['_Items_Per_Page'] - $Config['_Items_Per_Page'];
                if ($Start < 0) {
                    $Start = 1;
                }
            }
            $queryLimit = " LIMIT " . $Start . ", " . $Offset . " ";
            //$Limit = "";
        }
    }
    if (strtolower($Format) == 'pdf' && $limitOveride != false) {
        if ($limitOveride = 'full') {
            $queryLimit = '';
        }
    }
    if (empty($Config['_Items_Per_Page'])) {
        $queryLimit = '';
    }
    if (!empty($Format)) {
        // XML Output
        if (strtolower($Format) == 'xml') {
            $apiOut .= "    <page>" . $Page . "</page>\n";
            $apiOut .= "    <totalpages>" . $TotalPages . "</totalpages>\n";
            $apiOut .= "    <totalentries>" . $Count['Total'] . "</totalentries>\n";
        }
        //json output
        if (strtolower($Format) == 'json') {
            $apiOutput['totalpages'] = $TotalPages;
            $apiOutput['totalentries'] = $Count['Total'];
        }
    }
    // Select Query
    //$Query = "SELECT count(b.Country) as TotalCountry, ".$querySelect." FROM `".$Config['_main_table']."` AS prim \n ".$queryJoin." \n ".$WhereTag." \n ".$queryWhere."\n GROUP BY b.Country \n ".$orderStr." \n ".$queryLimit.";"
    if (!empty($Config['_useListTemplate']) && empty($Format)) {
        $Media = $Element;
        ob_start();
        $Query = dr_BuildReportGrid($EID, $Page, $SortField, $SortDir, 'sql', $limitOveride, $wherePush);
        //$WrapperEl = 'div';
        if (!empty($Config['_TemplateWrapper'])) {
            $WrapperEl = $Config['_TemplateWrapper'];
        }
        $Wrapperclasses = '';
        if (!empty($Config['_TemplateClass'])) {
            $Wrapperclasses = $Config['_TemplateClass'];
        }
        if (!empty($Config['_TemplateWrapper'])) {
            echo '<' . $WrapperEl . ' id="reportPanel_' . $Media['ID'] . '" class="interfaceWrapper ' . $Wrapperclasses . '">';
        }
        include 'templatemode.php';
        if (!empty($Config['_TemplateWrapper'])) {
            echo '</' . $WrapperEl . '>';
        }
        return ob_get_clean();
    }
    $Query = "SELECT " . $querySelect . " FROM `" . $Config['_main_table'] . "` AS prim \n " . $queryJoin . " \n " . $WhereTag . " \n " . $queryWhere . "\n " . $groupBy . " \n " . $orderStr . " \n " . $queryLimit . ";";
    if (strtolower($Format) == 'data') {
        $dtaRes = mysql_query($Query);
        $Data = mysql_fetch_assoc($dtaRes);
        return $Data;
    }
    if (!empty($Config['_UserQueryOveride']) && !empty($Config['_QueryOveride'])) {
        $Query = $Config['_QueryOveride'];
        preg_match('/(LIMIT [ 0-9]+,[ 0-9]+)/', $Query, $Limits);
        if (!empty($Limits[0])) {
            $Query = str_replace($Limits[0], $queryLimit, $Query);
        } else {
            $Query .= $queryLimit;
        }
    }
    //vardump($Query);
    // Wrap fields with ``
    //foreach($querySelects as $Field=>$FieldValue){
    // echo $Field.' = '.$FieldValue.'<br />';
    //   $Query = str_replace('.'.$Field, '.`'.$Field.'`', $Query);
    //}
    if (!empty($Config['_UseCustomQuery']) && !empty($Config['_ManualQuery'])) {
        $Query = $Config['_ManualQuery'];
        preg_match('/(LIMIT [ 0-9]+,[ 0-9]+)/', $Query, $Limits);
        if (!empty($Limits[0])) {
            $Query = str_replace($Limits[0], $queryLimit, $Query);
        } else {
            $Query .= $queryLimit;
        }
    }
    //echo $Query;
    $QueryHash = md5($Query);
    $_SESSION['queries'][$EID] = $Query;
    if (!empty($Queries[$QueryHash])) {
        $Result = $Queries[$QueryHash];
        mysql_data_seek($Result, 0);
    } else {
        $Result = mysql_query($Query);
        $Queries[$QueryHash] = $Result;
    }
    $_SESSION['queries'][$EID] = $Query;
    //echo $Query;
    if (strtolower($Format) == 'sql') {
        return $Query;
    }
    if (!empty($exitNotice)) {
        return;
        //'<div id="'.$EID.'_wrapper"></div>';
    }
    $Result = $wpdb->get_results($Query, ARRAY_A);
    // Run View Processes
    if (!empty($Config['_ViewProcessors'])) {
        foreach ($Config['_ViewProcessors'] as $viewProcess) {
            if (empty($_GET['format_' . $EID])) {
                //ignore on export
                if (file_exists(DB_TOOLKIT . 'data_report/processors/' . $viewProcess['_process'] . '/functions.php')) {
                    include_once DB_TOOLKIT . 'data_report/processors/' . $viewProcess['_process'] . '/functions.php';
                    $func = 'pre_process_' . $viewProcess['_process'];
                    $Result = $func($Result, $viewProcess, $Config, $EID);
                    if (empty($Result)) {
                        return;
                    }
                }
            }
            //if(file_exists($viewProcess['_process']))
        }
    }
    //pre_process_
    //$Result = mysql_query($Query);
    if (!empty($Config['_chartOnly'])) {
        return '<div id="chart_' . $ChartID . '" style="height:' . $height . 'px;"></div>';
        //$ReportReturn;
    }
    // Build Rows
    $ReportReturn .= '<tbody>';
    // Row number Increment
    $rowIndex = 1;
    // Set Row Style
    $Row = 'odd';
    // add in inline editing
    if (!empty($Config['_InlineEdit'])) {
        $_SESSION['dataform']['OutScripts'] .= "\n\t\t\tjQuery('.inlineedit').bind('change', function(t){\n\t\t\t\tajaxCall('df_inlineedit', this.id, jQuery(this).attr('ref'), this.value, function(f){\n\t\t\t\t\tif(f != '1'){\n\t\t\t\t\t\tdf_dialog(f, jQuery(this).attr('ref'), '0');\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t//alert(this.id+' - '+jQuery(this).attr('ref')+' - '+this.value);\n\t\t\t});\n\t\t";
    }
    if (!empty($Result)) {
        if (!empty($Format)) {
            // XML Output
            if (strtolower($Format) == 'xml') {
                $apiOut .= "    <entrycount>" . count($Result) . "</entrycount>\n";
            }
            //json output
            if (strtolower($Format) == 'json') {
                $apiOutput['entrycount'] = count($Result);
            }
        }
        //while($row = mysql_fetch_assoc($Result)) {
        foreach ($Result as $row) {
            // Switch Row Style
            //$Row = dais_rowswitch($Row);
            //$Row = report_rowswitch($Row);
            $Row = grid_rowswitch($Row);
            // foreach column
            $SelectedRow = '';
            if (!empty($Config['_ReturnFields'][0])) {
                if (!empty($_GET[$Config['_ReturnFields'][0]])) {
                    if ($row['_return_' . $Config['_ReturnFields'][0]] == $_GET[$Config['_ReturnFields'][0]]) {
                        if (!empty($Config['_Show_Edit'])) {
                            $SelectedRow = 'highlight';
                        }
                        $HighlightIndex = true;
                    }
                }
            }
            $ReportReturn .= '<tr class="' . $Row . ' itemRow_' . $EID . ' ' . $SelectedRow . '  report_entry" ref="' . $row['_return_' . $Config['_ReturnFields'][0]] . ' highlight" id="row_' . $EID . '_' . $rowIndex . '" >';
            // API Output
            if (!empty($Format)) {
                // XML Output
                if (strtolower($Format) == 'xml') {
                    $apiOut .= "    <entry>\n";
                }
                // json Output
                if (strtolower($Format) == 'json') {
                    $apiOutput['entries'][$jsonIndex] = array();
                }
                if (strtolower($Format) == 'pdf') {
                    //$apiOutput[$jsonIndex][] = array();
                    if (!empty($_SESSION['reportFilters'][$EID])) {
                        //$apiOutput['filters'] = array();
                    }
                }
            }
            $ColumnCounter = 0;
            //vardump($Config);
            // action panels
            // Edit Functions if no popup
            $actionPanels = '';
            if (!empty($ShowActionPanel)) {
                $ViewLink = '';
                $ActionWidth = 16;
                if (!empty($Config['_Show_View'])) {
                    $ActionWidth = $ActionWidth + 16;
                    $ViewLink .= "<span style=\"cursor:pointer;\" onclick=\"df_loadEntry('" . $row['_return_' . $Config['_ReturnFields'][0]] . "', '" . $EID . "', " . $isModal . "); return false;\"><img src=\"" . WP_PLUGIN_URL . "/db-toolkit/data_report/css/images/magnifier.png\" width=\"16\" height=\"16\" alt=\"View\" title=\"View\" border=\"0\" align=\"absmiddle\" /></span>";
                    if (!is_admin()) {
                        if (!empty($Config['_ItemViewPage'])) {
                            $ReportVars = array();
                            foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                            }
                            // Get permalink
                            $PageLink = get_permalink($Config['_ItemViewPage']);
                            $Location = parse_url($PageLink);
                            if (!empty($Location['query'])) {
                                $PageLink = str_replace('?' . $Location['query'], '', $PageLink);
                                parse_str($Location['query'], $gets);
                                $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query(array_merge($gets, $ReportVars)));
                            } else {
                                $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query($ReportVars));
                            }
                            $ViewLink = "<a href=\"" . $PageLink . "\"><img src=\"" . WP_PLUGIN_URL . "/db-toolkit/data_report/css/images/magnifier.png\" width=\"16\" height=\"16\" alt=\"View\" title=\"View\" border=\"0\" align=\"absmiddle\" /></a>";
                        }
                    }
                }
                if (!empty($Config['_Show_Edit'])) {
                    $ActionWidth = $ActionWidth + 16;
                    if ($ViewLink != '') {
                        $ViewLink .= " ";
                    }
                    $ViewLink .= '<span style="cursor:pointer;" onclick="dr_BuildUpDateForm(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\');"><img src="' . WP_PLUGIN_URL . '/db-toolkit/data_report/edit.png" width="16" height="16" alt="Edit" title="Edit" border="0" align="absmiddle" /></span>';
                }
                if (!empty($Config['_Show_Delete_action'])) {
                    $ActionWidth = $ActionWidth + 16;
                    if ($ViewLink != '') {
                        $ViewLink .= " ";
                    }
                    if (!empty($_GET)) {
                        $hasQuery = build_query($_GET);
                    } else {
                        $hasQuery = false;
                    }
                    $ViewLink .= '<span style="cursor:pointer;" onclick="dr_deleteItem(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\',\'' . $hasQuery . '\');"><img src="' . WP_PLUGIN_URL . '/db-toolkit/data_report/delete.png" width="16" height="16" alt="Delete" title="Delete" border="0" align="absmiddle" /></span>';
                }
                //vardump($Config);
                $PreReportReturn = '<td class="' . $Row . ' action" width="' . $ActionWidth . '" scope="col" style="text-align:center;overflow:hidden;">';
                $PreReportReturn .= $ViewLink;
                //'Edit | View';
                $PreReportReturn .= '</td>';
                $actionPanels .= $PreReportReturn;
            }
            // Show Action Panels on left
            //$ReportReturn .= $actionPanels;
            foreach ($Config['_IndexType'] as $Field => $Type) {
                //foreach ($row as $Field => $Data) {
                if ($Type[1] === 1) {
                    break;
                }
                if (isset($row[$Field])) {
                    $Data = $row[$Field];
                } else {
                    $Data = '';
                }
                if (!empty($Config['_IndexType'][$Field][1])) {
                    if ($Config['_IndexType'][$Field][1] == 'show') {
                        $outData = $Data;
                        /// Capture value for Totals
                        if (!empty($Config['_TotalsFields'][$Field]['Type'])) {
                            switch ($Config['_TotalsFields'][$Field]['Type']) {
                                case 'count':
                                    //echo $Field.' = '.$Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']].'+1<br />';
                                    $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] = $Count['TotalEntries'];
                                    break;
                                case 'sum':
                                    //echo $Field.' = '.$Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']].' + '.$outData.'<br />';
                                    $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] = $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] + $outData;
                                    break;
                                case 'avg':
                                    //echo $Field.' = '.$Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']].' + '.$outData.'<br />';
                                    $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] = $Config['_TotalsFields'][$Field][$Config['_TotalsFields'][$Field]['Type']] + $outData;
                                    break;
                            }
                        }
                        if (function_exists($Config['_Field'][$Field][0] . '_processValue')) {
                            $processFunc = $Config['_Field'][$Field][0] . '_processValue';
                            //						Value  field type
                            $outData = $processFunc($Data, $Config['_Field'][$Field][1], $Field, $Config, $EID, $row);
                        }
                        // Capture columns average width for ato widths
                        $AvrageWidth[$Field][] = strlen($outData) * 8;
                        // Apply keyword Fitler Highlight
                        if (!empty($_SESSION['reportFilters'][$EID]['_keywords'])) {
                            //$outData = str_replace($_SESSION['reportFilters'][$EID]['_keywords'], '<strong>'.$_SESSION['reportFilters'][$EID]['_keywords'].'</strong>', $outData);
                            //$outData = str_replace(ucwords($_SESSION['reportFilters'][$EID]['_keywords']), '<strong>'.ucwords($_SESSION['reportFilters'][$EID]['_keywords']).'</strong>', $outData);
                            //$outData = str_replace(strtoupper($_SESSION['reportFilters'][$EID]['_keywords']), '<strong>'.strtoupper($_SESSION['reportFilters'][$EID]['_keywords']).'</strong>', $outData);
                            //$outData = str_replace(strtolower($_SESSION['reportFilters'][$EID]['_keywords']), '<strong>'.strtolower($_SESSION['reportFilters'][$EID]['_keywords']).'</strong>', $outData);
                        }
                        // set row output
                        //Check if field is in totals and is allowed inline
                        $Location = 'inline';
                        if (!empty($Config['_TotalsFields'][$Field]['Location'])) {
                            $Location = $Config['_TotalsFields'][$Field]['Location'];
                        }
                        if ($Location == 'inline' || $Location == 'headerinline' || $Location == 'footerinline') {
                            // selection highlighting (experimental)
                            $sortClass = '';
                            if (key_exists('SortField', $_SESSION['report_' . $EID]) && $_SESSION['report_' . $EID]['SortField'] == $Field) {
                                $sortClass = 'column_sorting_' . $_SESSION['report_' . $EID]['SortDir'];
                            }
                            $itemID = uniqid('');
                            // Add Reload Highlighting
                            $LiveHighlight = '';
                            $ReportReturn .= '<td class="' . $Row . ' ' . $sortClass . ' ' . $LiveHighlight . '" scope="col" id="' . $itemID . '" ref="itemRow_' . $EID . '" width="' . ($Config['_WidthOverride'][$Field] == '' ? '{{width_' . $Field . '}}px' : $Config['_WidthOverride'][$Field] . 'px') . '" style="text-align:' . $Config['_Justify'][$Field] . '; ">';
                            //inline editing
                            if (!empty($Config['_InlineEdit'][$Field])) {
                                $Req = 'inlineedit';
                                $FieldSet = $Config['_Field'][$Field];
                                //$ReportReturn .= WP_PLUGIN_DIR.'/db-toolkit/data_form/fieldtypes/'.$FieldSet[0].'/input.php';
                                ob_start();
                                $Defaults[$Field] = $row['_sourceid_' . $Field];
                                include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/conf.php';
                                include WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/' . $FieldSet[0] . '/input.php';
                                $ReportReturn .= ob_get_clean();
                            } else {
                                $PreReportReturn = '';
                                // Make View Item Link If page is set
                                if (is_admin()) {
                                    //vardump($Config);
                                    if (!empty($Config['_ItemViewInterface'])) {
                                        // Create return link
                                        $ReportVars = array();
                                        foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                            $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                        }
                                        // Get permalink
                                        // interface admin.php?page=Database_Toolkit&renderinterface=dt_intfc4c04c77ed928a
                                        if ($_GET['page'] != 'dbt_builder') {
                                            if (!empty($Config['_SetDashboard'])) {
                                                $Interface = get_option($EID);
                                                $app = get_option('_' . $Interface['_Application'] . '_app');
                                                if (!empty($app['landing'])) {
                                                    $pageLoc = 'app_' . $Interface['_Application'];
                                                } else {
                                                    $pageLoc = $EID;
                                                }
                                                if (!empty($app['docked'])) {
                                                    $PageLink = 'admin.php?page=' . $pageLoc . '&sub=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                } else {
                                                    $PageLink = 'admin.php?page=dbt_builder&renderinterface=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                }
                                            } else {
                                                $PageLink = 'admin.php?page=' . $_GET['page'] . '&sub=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                            }
                                        } else {
                                            $PageLink = 'admin.php?page=dbt_builder&renderinterface=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                        }
                                        $PreReportReturn .= "<a href=\"" . $PageLink . "\">";
                                    }
                                } else {
                                    if (!empty($Config['_ItemViewInterface']) && !empty($Config['_targetInterface'])) {
                                        // Create return link
                                        $url = !empty($_SERVER['HTTPS']) ? "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
                                        $url = strtok($url, '?');
                                        $ReportVars = array();
                                        foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                            $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                        }
                                        // Get permalink
                                        // interface admin.php?page=Database_Toolkit&renderinterface=dt_intfc4c04c77ed928a
                                        $op = '?';
                                        if (strpos($url, '?') !== false) {
                                            $op = '&';
                                        }
                                        $sendString = htmlspecialchars_decode(http_build_query($ReportVars));
                                        $PageLink = $url . $op . $sendString;
                                        //$sendString = implode('&', $ReturnFields);
                                        //$PreReportReturn .= '<a id href="#'.$Config['_ItemViewInterface'].'" onclick="dr_pushResult(\''.$Config['_ItemViewInterface'].'\', \''.$sendString.'\'); return false;">'.$outData.'</a>';
                                        $PreReportReturn .= "<a href=\"" . $PageLink . "\" onclick=\"dr_pushResult('" . $Config['_ItemViewInterface'] . "', '" . $sendString . "'); return false;\" >";
                                        //$PreReportReturn .= "<a href=\"" . $PageLink . "\">";
                                    }
                                    if (!empty($Config['_ItemViewPage'])) {
                                        // Create return link
                                        $ReportVars = array();
                                        foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                            $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                        }
                                        // Get permalink
                                        $PageLink = get_permalink($Config['_ItemViewPage']);
                                        $Location = parse_url($PageLink);
                                        if (!empty($Location['query'])) {
                                            $PageLink = str_replace('?' . $Location['query'], '', $PageLink);
                                            parse_str($Location['query'], $gets);
                                            $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query(array_merge($gets, $ReportVars)));
                                        } else {
                                            $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query($ReportVars));
                                        }
                                        $PreReportReturn .= "<a href=\"" . $PageLink . "\" >";
                                    }
                                }
                                $ReturnFields = array();
                                if (is_array($Config['_ReturnFields'])) {
                                    foreach ($Config['_ReturnFields'] as $ReturnField) {
                                        $ReturnFields[] = $ReturnField . '=' . urlencode($row['_return_' . $ReturnField]);
                                    }
                                }
                                //$ReturnMix = implode('&', $ReturnFields);
                                //$PreReportReturn .= '<a href="'.getdocument($_GET['PageData']['ID']).'#'.$ReturnMix.'">'.stripslashes($outData).'</a>';
                                // CREATE redirect pushing
                                if (!empty($Config['_layoutTemplate']['_Fields'][$Field])) {
                                    if (!empty($outData)) {
                                        $before = $Config['_layoutTemplate']['_Fields'][$Field]['_before'];
                                        $after = $Config['_layoutTemplate']['_Fields'][$Field]['_after'];
                                        foreach ($row as $repField => $repValue) {
                                            $before = str_replace('{{' . $repField . '}}', $repValue, $before);
                                            $after = str_replace('{{' . $repField . '}}', $repValue, $after);
                                        }
                                        $PreReportReturn .= $before;
                                    }
                                }
                                $PreReportReturn .= $outData;
                                if (!empty($Config['_layoutTemplate']['_Fields'][$Field])) {
                                    if (!empty($outData)) {
                                        $PreReportReturn .= $after;
                                    }
                                }
                                // API Output
                                if (!empty($Format)) {
                                    // XML Output
                                    if (strtolower($Format) == 'xml') {
                                        if (!is_integer($outData)) {
                                            $apiOut .= "        <" . $Field . "><![CDATA[" . stripslashes($outData) . "]]></" . $Field . ">\n";
                                        } else {
                                            $apiOut .= "\t<" . $Field . ">" . stripslashes($outData) . "</" . $Field . ">\n";
                                        }
                                    }
                                    // json Output
                                    if (strtolower($Format) == 'json') {
                                        $apiOutput['entries'][$jsonIndex][$Field] = $outData;
                                        //echo $outData;
                                    }
                                    // PDF output
                                    if (strtolower($Format) == 'pdf') {
                                        $apiOutput[$pdfIndex][$Field] = stripslashes($outData);
                                        if (!empty($_SESSION['reportFilters'][$EID][$Field])) {
                                            $apiOutput['filters'][$Field][stripslashes($outData)] = stripslashes($outData);
                                        }
                                    }
                                }
                                // Close link
                                if (!empty($Config['_ItemViewPage'])) {
                                    $PreReportReturn .= "</a>";
                                }
                                if (!empty($Config['_ItemViewInterface'])) {
                                    $PreReportReturn .= "</a>";
                                }
                                if (!empty($Config['_ItemViewInterface']) && !empty($Config['_targetInterface'])) {
                                    $PreReportReturn .= "</a>";
                                }
                            }
                            $ReportReturn .= $PreReportReturn;
                            if (!empty($Config['_Show_popup'])) {
                                if ($ColumnCounter === 0) {
                                    // Add inline actions
                                    $ViewLink = '';
                                    $ActionWidth = 16;
                                    if (!empty($Config['_Show_View'])) {
                                        $ActionWidth = $ActionWidth + 16;
                                        $ViewLink['view'] = "<a href=\"#\" onclick=\"return false;\"><span style=\"cursor:pointer;\" onclick=\"df_loadEntry('" . $row['_return_' . $Config['_ReturnFields'][0]] . "', '" . $EID . "', " . $isModal . "); return false;\">View</span></a>";
                                        if (is_admin()) {
                                            if (!empty($Config['_ItemViewInterface'])) {
                                                $ReportVars = array();
                                                foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                                    $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                                }
                                                // Get permalink
                                                // check if its in a menu
                                                $inf = get_option($Config['_ItemViewInterface']);
                                                if (empty($inf['_ItemGroup']) && empty($inf['_interfaceName'])) {
                                                    $PageLink = 'admin.php?page=dbt_builder&renderinterface=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                } else {
                                                    $PageLink = 'admin.php?page=' . $Config['_ItemViewInterface'] . '&' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                }
                                                $ViewLink['view'] = "<a href=\"" . $PageLink . "\">View</a>";
                                            }
                                        } else {
                                            if (!empty($Config['_ItemViewPage'])) {
                                                $ReportVars = array();
                                                foreach ($Config['_ReturnFields'] as $ReportReturnField) {
                                                    $ReportVars[$ReportReturnField] = urlencode($row['_return_' . $ReportReturnField]);
                                                }
                                                // Get permalink
                                                $PageLink = get_permalink($Config['_ItemViewPage']);
                                                $Location = parse_url($PageLink);
                                                if (!empty($Location['query'])) {
                                                    $PageLink = str_replace('?' . $Location['query'], '', $PageLink);
                                                    parse_str($Location['query'], $gets);
                                                    $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query(array_merge($gets, $ReportVars)));
                                                } else {
                                                    $PageLink = $PageLink . '?' . htmlspecialchars_decode(http_build_query($ReportVars));
                                                }
                                                $ViewLink['view'] = "<a href=\"" . $PageLink . "\">View</a>";
                                            }
                                        }
                                    }
                                    if (!empty($Config['_Show_Edit'])) {
                                        $ActionWidth = $ActionWidth + 16;
                                        $ViewLink['edit'] = '<a href="#" onclick="return false;"><span style="cursor:pointer;" onclick="dr_BuildUpDateForm(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\');">Edit</span></a>';
                                    }
                                    if (!empty($Config['_Show_Delete_action'])) {
                                        $ActionWidth = $ActionWidth + 16;
                                        $ViewLink['delete'] = '<a href="#" onclick="return false;"><span style="cursor:pointer;" class="delete" onclick="dr_deleteItem(\'' . $EID . '\', \'' . $row['_return_' . $Config['_ReturnFields'][0]] . '\');">Delete</span></a>';
                                    }
                                    //vardump($Config);
                                    //$PreReportReturn = '<td class="'.$Row.' action" width="'.$ActionWidth.'" scope="col" style="text-align:center;overflow:hidden;">';
                                    $ReportReturn .= '<div class="row-actions">' . implode(' | ', $ViewLink) . '</div>';
                                    //'Edit | View';
                                    //$PreReportReturn .= '</td>';
                                    //$ReportReturn .= $PreReportReturn;
                                }
                            }
                            $ReportReturn .= '</td>';
                        }
                    }
                }
                $ColumnCounter++;
            }
            // API Output
            if (!empty($Format)) {
                // XML Output
                if (strtolower($Format) == 'xml') {
                    $apiOut .= "    </entry>\n";
                }
                // json Output
                if (strtolower($Format) == 'json') {
                    $jsonIndex++;
                }
                //PDF Output
                if (strtolower($Format) == 'pdf') {
                    $pdfIndex++;
                }
            }
            // Show Action Panelson right
            $ReportReturn .= $actionPanels;
            $ReportReturn .= '</tr>';
            // Increment row index
            $rowIndex++;
        }
    }
    //echo mysql_error();
    // Close off Table end content
    $ReportReturn .= '</tbody>';
    $ReportReturn .= '</table>';
    // Make Scripts for deleting and select
    if (empty($Config['_Feature_Selectable_Rows'])) {
        $_SESSION['dataform']['OutScripts'] .= "\n\t\tjQuery('#data_report_" . $EID . " .report_entry').bind('click', function(){\n\t\t\tjQuery(this).toggleClass(\"highlight\");\n\t\t});\n\t";
    }
    // Footer
    //TODO: really need to clean up this templating. to much repetition
    if (!empty($Config['_Show_Footer'])) {
        $First = 1;
        $Prev = $Page - 1;
        $Next = $Page + 1;
        $Last = $TotalPages;
        if ($Prev <= 0) {
            $Prev = 1;
        }
        if ($Next > $TotalPages) {
            $Next = $TotalPages;
        }
        if (empty($Page)) {
            $Page = 1;
        }
        //Page Index display
        $toPos = $Page * $Offset;
        if ($toPos > $Count['Total']) {
            $toPos = $Count['Total'];
        }
        $pageLink = '';
        if (!empty($_SERVER['QUERY_STRING'])) {
            $pageLink = $_SERVER['QUERY_STRING'] . '&';
        }
        //$ReportReturn .= '<div style="padding:3px;" class="list_row3">';
        $ReportReturn .= '<div style="padding:3px;" class="tablenav bottom">';
        //Total pages display
        $ReportReturn .= '<div class="tablenav-pages">';
        // Check if there are any entries
        if ($Count['Total'] == 0) {
            $nothingFound = 'Nothing Found';
            if (!empty($Config['_NoResultsText'])) {
                $nothingFound = $Config['_NoResultsText'];
            }
            $ReportReturn .= '<span class="displaying-num">' . $nothingFound . '</span>';
        } else {
            $footerPrefix = $Start + 1 . ' - ' . $toPos . ' of ';
            if (empty($Config['_Items_Per_Page'])) {
                $footerPrefix = '';
            }
            $ReportReturn .= '<span class="displaying-num">' . $footerPrefix . $Count['Total'] . ' Items</span>';
        }
        //$ReportReturn .= '<div class="reportFooter_totals">';
        if ($TotalPages > 1) {
            //$ReportReturn .= '<div class="fbutton" onclick="dr_goToPage('.$EID.', '.$First.');"><div><img src="'.WP_PLUGIN_DIR.'/db-toolkit/data_report/images/resultset_first.png" width="16" height="16" alt="First" align="absmiddle" /></div></div>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=1" title="Go to the first page" class="first-page" onclick="dr_goToPage(\'' . $EID . '\', 1); return false;">&laquo;</a>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=' . $Prev . '" title="Go to the previous page" class="prev-page" onclick="dr_goToPage(\'' . $EID . '\', ' . $Prev . '); return false;">&lsaquo;</a>';
            $ReportReturn .= '<span class="paging-input"> ' . $Page . ' of <span class="total-pages">' . $TotalPages . ' </span></span>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=' . $Next . '" title="Go to the next page" class="next-page" onclick="dr_goToPage(\'' . $EID . '\', ' . $Next . '); return false;">&rsaquo;</a>';
            $ReportReturn .= '<a href="?' . $pageLink . 'npage=' . $TotalPages . '" title="Go to the last page" class="last-page" onclick="dr_goToPage(\'' . $EID . '\', ' . $TotalPages . '); return false;">&raquo;</a>';
            //$ReportReturn .= '<div class="fbutton" onclick="dr_goToPage('.$EID.', '.$Last.');"><div><img src="'.WP_PLUGIN_DIR.'/db-toolkit/data_report/images/resultset_last.png" width="16" height="16" alt="Last" align="absmiddle" /></div></div>';
        }
        $ReportReturn .= '<br class="clear"></div>';
        $ReportReturn .= '</div>';
    }
    //query
    if (is_admin()) {
        if (!empty($_GET['debug'])) {
            //$ReportReturn .= '<div id="'.$EID.'_queryDebug" class="button" style="cursor:pointer; width:100px; text-align: center;" onclick="jQuery(\'#'.$EID.'_queryDebug_panel\').toggle();">Show Query</div>';
            $ReportReturn .= '<div id="' . $EID . '_queryDebug_panel" style="display:block;">';
            $ReportReturn .= '<textarea style="width:99%; height:200px;">' . $CountQuery . '</textarea><br />';
            $ReportReturn .= '<textarea style="width:99%; height:200px;">' . $Query . '</textarea><br />';
            $ReportReturn .= 'ERRORS: ' . mysql_error();
            //$ReportReturn .= '</div>';
        }
    }
    //dump($Config);
    // Create Header and Footer Totals
    if (!empty($Config['_TotalsFields'])) {
        if (!empty($Format)) {
            // XML Output
            if (strtolower($Format) == 'xml') {
                //$apiOut .= "		</entry>\n";
            }
            // json Output
            if (strtolower($Format) == 'json') {
                //	$jsonIndex++;
            }
            //PDF Output
            if (strtolower($Format) == 'pdf') {
                //	$pdfIndex++;
                $apiOutput['Totals'] = array();
                //$apiOutput = array();
                //$apiOutput['
            }
        }
        $header = '<div class="list_row1">';
        $footer = '<div class="list_row2">';
        $hcount = 0;
        $fcount = 0;
        foreach ($Config['_TotalsFields'] as $Field => $TotalsSet) {
            //dump($TotalsSet);
            if ($TotalsSet['Location'] == 'headerinline') {
                $TotalsSet['Location'] = 'header';
            }
            if ($TotalsSet['Location'] == 'footerinline') {
                $TotalsSet['Location'] = 'footer';
            }
            $box = '<div class="stuffbox" style="width:{{width_' . $TotalsSet['Location'] . '}}%; float:left;">';
            if (!empty($TotalsSet['Title'])) {
                $Title = df_parseCamelCase($TotalsSet['Title']);
            }
            $OutValue = round($TotalsSet[$TotalsSet['Type']], 2);
            if ($TotalsSet['Function'] == 'VAT') {
                $OutValue = totals_vat($OutValue);
            }
            if ($TotalsSet['Function'] == 'AddVAT') {
                $OutValue = totals_addvat($OutValue);
            }
            $Title = df_parseCamelCase($Field);
            $Caption = ' ';
            if (!empty($TotalsSet['Caption'])) {
                $Caption = $TotalsSet['Caption'];
            }
            /// Outputs
            if (!empty($Format)) {
                // XML Output
                if (strtolower($Format) == 'xml') {
                    //	$apiOut .= "		</entry>\n";
                }
                // json Output
                if (strtolower($Format) == 'json') {
                    //	$jsonIndex++;
                }
                //PDF Output
                if (strtolower($Format) == 'pdf') {
                    $apiOutput['Totals'][$Title] = $TotalsSet['Prefix'] . $OutValue . $TotalsSet['Suffix'] . ' ' . $Caption;
                }
            }
            $box .= '<h3>' . $Title . '</h3>';
            $box .= '<div class="inside"><h1>' . $TotalsSet['Prefix'] . $OutValue . $TotalsSet['Suffix'] . '</h1></div>';
            $box .= '<div class="inside">' . $Caption . '</div>';
            $box .= '</div>';
            if (!empty(${$TotalsSet}['Location'])) {
                ${$TotalsSet}['Location'] .= $box;
            }
            switch ($TotalsSet['Location']) {
                case 'header':
                    $hcount++;
                    break;
                case 'footer':
                    $fcount++;
                    break;
            }
        }
        $header .= '<div style="clear:both;"></div></div>';
        $footer .= '<div style="clear:both;"></div></div>';
    }
    if (!empty($hcount)) {
        if ($hcount >= 1) {
            $header = str_replace('{{width_header}}', 100 / $hcount - 3, $header);
        }
    }
    if (!empty($fcount)) {
        if ($fcount >= 1) {
            $footer = str_replace('{{width_footer}}', 100 / $fcount - 3, $footer);
        }
    }
    // Run Final Totals Functions on return data
    if (!empty($GLOBALS['Totals'][$EID])) {
        foreach ($GLOBALS['Totals'][$EID] as $Key => $Output) {
            $Total = $Config['_TotalsFields'][$Output['Field']][$Config['_TotalsFields'][$Output['Field']]['Type']];
            if (!empty($GLOBALS['TotalsAverages'][$EID][$Output['Field']]['PreAverage'])) {
                if (empty($AverageBar)) {
                    //foreach$Output['PreAverage']
                    $avT = 0;
                    foreach ($GLOBALS['TotalsAverages'][$EID][$Output['Field']]['PreAverage'] as $val) {
                        $avT = $avT + $val;
                    }
                    $AverageBar = ceil($avT / count($GLOBALS['TotalsAverages'][$EID][$Output['Field']]['PreAverage']));
                }
                $Total = $AverageBar;
            }
            $func = 'totals_' . $Output['Function'];
            $newValue = $func($Output['Value'], $Total);
            $ReportReturn = str_replace($Key, $newValue, $ReportReturn);
        }
    }
    // Set Auto Widths to Averages
    if (!empty($AvrageWidth)) {
        foreach ($AvrageWidth as $Field => $Value) {
            $Tmp = 0;
            foreach ($Value as $Num) {
                $Tmp = $Tmp + $Num;
            }
            $Av = ceil($Tmp / count($Value));
            if (!empty($minWidth[$Field])) {
                if ($Av < $minWidth[$Field]) {
                    $Av = $minWidth[$Field];
                }
            }
            $Av = '';
            $ReportReturn = str_replace('width="{{width_' . $Field . '}}px"', $Av, $ReportReturn);
        }
    }
    //dump($Config);
    //echo $Query;
    // API Output
    if (!empty($Format)) {
        // XML Output
        if (strtolower($Format) == 'xml') {
            return $apiOut . "\n\t</entries>";
        }
        // json Output
        if (strtolower($Format) == 'json') {
            //$apiOutput;
            //vardump($apiOutput);
            return json_encode($apiOutput);
        }
        // PDF Output
        if (strtolower($Format) == 'pdf') {
            //$apiOutput;
            return $apiOutput;
        }
    }
    return do_shortcode($ReportReturn);
}