PluginProbe
wpDataTables – WordPress Data Table, Dynamic Tables & Table Charts Plugin / trunk
wpDataTables – WordPress Data Table, Dynamic Tables & Table Charts Plugin vtrunk
6.5.1.6 6.5.1.5 6.5.1.4 6.5.1.3 6.5.1.2 6.5.1.1 6.5.0.9 6.5.0.8 6.5.0.7 6.5.0.6 trunk 3.4.2.40 3.4.2.41 3.4.2.42 3.4.2.43 3.4.2.44 3.4.2.45 3.4.2.46 3.4.2.47 3.4.2.48 3.4.2.49 3.4.2.50 6.3.2 6.3.3.1 6.3.3.10 All 46 releases
wpdatatables / source / class.wdtconfigcontroller.php

class.wdtconfigcontroller.php in wpDataTables – WordPress Data Table, Dynamic Tables & Table Charts Plugin trunk, at source/class.wdtconfigcontroller.php

1,372 lines 59.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 defined('ABSPATH') or die("Cannot access pages directly.");
4
5 /**
6 * Class WDTConfigController
7 *
8 * This class contains static methods that bridge front-end for table configuration (add from data source)
9 * and the database. Validating, sanitizing and saving column and table settings.
10 *
11 * @since 2.0
12 * @author Alexander Gilmanov
13 */
14 class WDTConfigController {
15
16 private static $_tableConfigCache = array();
17 private static $_resetColumnPosition = false;
18
19 /**
20 * Validate and save the table config to DB
21 * @param StdClass $tableData
22 */
23 public static function saveTableConfig($tableData) {
24 global $wpdb, $wdtVar1, $wdtVar2, $wdtVar3;
25 $tableData = self::sanitizeTableConfig($tableData);
26
27 // Fetching the 3 placeholders
28 $wdtVar1 = isset($tableData->var1) ?
29 sanitize_text_field($tableData->var1) : '';
30 $wdtVar2 = isset($tableData->var2) ?
31 sanitize_text_field($tableData->var2) : '';
32 $wdtVar3 = isset($tableData->var3) ?
33 sanitize_text_field($tableData->var3) : '';
34
35 // trying to generate/validate the WPDataTable config
36 $res = WDTConfigController::tryCreateTable(
37 $tableData->table_type,
38 $tableData->content,
39 $tableData->file_location
40 );
41
42 if (empty($res->error)) {
43 // If the table can be created by wpDataTables performing the save to DB
44 self::saveTableToDB($tableData);
45 // If table saved successfully saving the columns as well
46 if ($wpdb->last_error == '') {
47 if (!isset($tableData->id)) {
48 $tableData->id = $wpdb->insert_id;
49 }
50 // Saving the columns
51 try {
52 self::saveColumns($tableData->columns, $res->table, $tableData->id);
53
54 $wpDataTable = WPDataTable::loadWpDataTable($tableData->id);
55 $tableData = self::loadTableFromDB($tableData->id);
56
57 if (count($wpDataTable->getDataRows()) > 2000) {
58 $tableData->server_side = 1;
59 }
60 if ($tableData->file_location == 'wp_media_lib' &&
61 ($tableData->table_type === 'csv' || $tableData->table_type === 'xls')
62 ) {
63 $tableData->content = WDTTools::pathToUrl($tableData->content);
64 }
65 $tableData->editor_roles = !empty($tableData->editor_roles) ? explode(",", $tableData->editor_roles) : '';
66 foreach ($tableData->columns as &$column) {
67 $column->defaultValueValues = $wpDataTable->getColumn($column->orig_header)->getDefaultValues();
68 }
69
70 $res->table = $tableData;
71 $res->wdtJsonConfig = json_decode($wpDataTable->getJsonDescription());
72 $res->wdtHtml = $wpDataTable->generateTable();
73
74 } catch (Exception $e) {
75 $res->error = ltrim($e->getMessage(), '<br/><br/>');
76 }
77 } else {
78 $res->error = $wpdb->last_error;
79 }
80 }
81
82 echo json_encode($res);
83 exit();
84 }
85
86 /**
87 * Returns the JSON string with config object for the table and all of its columns
88 *
89 * @param $tableId - Id of the table
90 * @param $tableView - Standard or Excel-like table view
91 * @throws Exception
92 * @return stdClass Object with the wpDataTable HTML and config
93 */
94 public static function loadTableConfig($tableId, $tableView = null) {
95 $res = new stdClass();
96
97 try {
98 $wpDataTable = WPDataTable::loadWpDataTable($tableId, $tableView);
99 $tableData = self::loadTableFromDB($tableId);
100
101 if (count($wpDataTable->getDataRows()) > 2000) {
102 $tableData->server_side = 1;
103 }
104 if ($tableData->file_location == 'wp_media_lib' &&
105 ($tableData->table_type === 'csv' || $tableData->table_type === 'xls')
106 ) {
107 $tableData->content = WDTTools::pathToUrl($tableData->content);
108 }
109 $tableData->editor_roles = !empty($tableData->editor_roles) ? explode(",", $tableData->editor_roles) : '';
110 foreach ($tableData->columns as &$column) {
111 $column->defaultValueValues = $wpDataTable->getColumn($column->orig_header)->getDefaultValues();
112 }
113
114 $res->table = $tableData;
115 $res->wdtJsonConfig = json_decode($wpDataTable->getJsonDescription());
116 $res->wdtHtml = $wpDataTable->generateTable();
117 } catch (Exception $e) {
118 $res->error = $e->getMessage();
119 }
120 return $res;
121 }
122
123
124 /**
125 * Helper method that load table config data from DB
126 * @param $tableId
127 * @return array|null|bool|object|stdClass
128 * @throws Exception
129 */
130 public static function loadTableFromDB($tableId, $loadFromCache = true) {
131 global $wpdb;
132
133 do_action('wpdatatables_before_get_table_metadata', $tableId);
134
135 if (!isset(self::$_tableConfigCache[$tableId]) || $loadFromCache === false) {
136
137 $tableQuery = $wpdb->prepare(
138 'SELECT * FROM ' . $wpdb->prefix . 'wpdatatables WHERE id = %d',
139 $tableId
140 );
141
142 $table = $wpdb->get_row($tableQuery);
143
144 if (!empty($wpdb->last_error)) {
145 throw new Exception(
146 __(
147 'There was an error trying to fetch the table data: ',
148 'wpdatatables'
149 ) . $wpdb->last_error
150 );
151 }
152
153 if (!isset($table)) {
154 return false;
155 }
156
157 $advancedSettings = json_decode($table->advanced_settings);
158
159 $table->tabletools_config = unserialize($table->tabletools_config, ["allowed_classes" => false]);
160 $table->columns = self::getColumnsConfig($tableId);
161 $table->info_block = (isset($advancedSettings->info_block)) ? $advancedSettings->info_block : 1;
162 $table->showTableToolsIncludeHTML = (isset($advancedSettings->showTableToolsIncludeHTML)) ? $advancedSettings->showTableToolsIncludeHTML : 0;
163 $table->showTableToolsIncludeTitle = (isset($advancedSettings->showTableToolsIncludeTitle)) ? $advancedSettings->showTableToolsIncludeTitle : 0;
164 $table->responsiveAction = (isset($advancedSettings->responsiveAction)) ? $advancedSettings->responsiveAction : 'icon';
165 $table->pagination = (isset($advancedSettings->pagination)) ? $advancedSettings->pagination : 1;
166 $table->paginationAlign = (isset($advancedSettings->paginationAlign)) ? $advancedSettings->paginationAlign : 'right';
167 $table->paginationLayout = (isset($advancedSettings->paginationLayout)) ? $advancedSettings->paginationLayout : 'full_numbers';
168 $table->paginationLayoutMobile = (isset($advancedSettings->paginationLayoutMobile)) ? $advancedSettings->paginationLayoutMobile : 'simple';
169 $table->global_search = (isset($advancedSettings->global_search)) ? $advancedSettings->global_search : 1;
170 $table->showRowsPerPage = (isset($advancedSettings->showRowsPerPage)) ? $advancedSettings->showRowsPerPage : 1;
171 $table->clearFilters = (isset($advancedSettings->clearFilters)) ? $advancedSettings->clearFilters : 0;
172 $table->simpleHeader = (isset($advancedSettings->simpleHeader)) ? $advancedSettings->simpleHeader : 0;
173 $table->simpleResponsive = (isset($advancedSettings->simpleResponsive)) ? $advancedSettings->simpleResponsive : 0;
174 $table->stripeTable = (isset($advancedSettings->stripeTable)) ? $advancedSettings->stripeTable : 0;
175 $table->cellPadding = (isset($advancedSettings->cellPadding)) ? $advancedSettings->cellPadding : 10;
176 $table->removeBorders = (isset($advancedSettings->removeBorders)) ? $advancedSettings->removeBorders : 0;
177 $table->borderCollapse = (isset($advancedSettings->borderCollapse)) ? $advancedSettings->borderCollapse : 'collapse';
178 $table->borderSpacing = (isset($advancedSettings->borderSpacing)) ? $advancedSettings->borderSpacing : 0;
179 $table->verticalScroll = (isset($advancedSettings->verticalScroll)) ? $advancedSettings->verticalScroll : 0;
180 $table->verticalScrollHeight = (isset($advancedSettings->verticalScrollHeight)) ? $advancedSettings->verticalScrollHeight : 0;
181 $table->simple_template_id = isset($table->simple_template_id) || isset($advancedSettings->simple_template_id) ? $advancedSettings->simple_template_id : 0;
182 $table->pdfPaperSize = isset($advancedSettings->pdfPaperSize) ? $advancedSettings->pdfPaperSize : 'A4';
183 $table->pdfPageOrientation = isset($advancedSettings->pdfPageOrientation) ? $advancedSettings->pdfPageOrientation : 'portrait';
184 $table->show_table_description = isset($advancedSettings->show_table_description) ? $advancedSettings->show_table_description : false;
185 $table->table_description = isset($advancedSettings->table_description) ? $advancedSettings->table_description : '';
186 $table->table_wcag = isset($table->table_wcag) || isset($advancedSettings->table_wcag) ? $advancedSettings->table_wcag : 0;
187 $table->pagination_top = (isset($advancedSettings->pagination_top)) ? $advancedSettings->pagination_top : 0;
188
189 $table = self::sanitizeTableConfig($table);
190
191 self::$_tableConfigCache[$tableId] = $table;
192 }
193
194 self::$_tableConfigCache[$tableId] = apply_filters('wpdatatables_filter_table_metadata', self::$_tableConfigCache[$tableId], $tableId);
195
196 return self::$_tableConfigCache[$tableId];
197 }
198 /**
199 * Helper method that load columns config data from DB
200 * @param $tableId
201 * @param array $columnNames
202 * @return array|null|object
203 */
204 public static function loadColumnsFromDB($tableId, $columnNames = array()) {
205 global $wpdb;
206
207 do_action('wpdatatables_before_get_columns_metadata', $tableId);
208
209 $params[] = $tableId;
210
211 $qWhere = '';
212 foreach ($columnNames as $column) {
213 if ($qWhere != '') {
214 $qWhere .= ', ';
215 }
216 $qWhere .= '%s';
217 $params[] = $column;
218 }
219
220 if ($qWhere != '') {
221 $qWhere = " AND orig_header IN ( $qWhere )";
222 }
223
224 $columnsQuery = $wpdb->prepare(
225 'SELECT * FROM ' . $wpdb->prefix . 'wpdatatables_columns
226 WHERE table_id = %d ' . $qWhere . '
227 ORDER BY pos',
228 $params
229 );
230
231 $columns = $wpdb->get_results($columnsQuery);
232 $columns = apply_filters('wpdatatables_filter_columns_metadata', $columns, $tableId);
233
234 return $columns;
235 }
236
237
238 public static function loadSingleColumnFromDB($columnId) {
239 global $wpdb;
240
241 $columnQuery = $wpdb->prepare(
242 'SELECT * FROM ' . $wpdb->prefix . 'wpdatatables_columns WHERE id = %d',
243 $columnId
244 );
245
246 $column = $wpdb->get_row($columnQuery, ARRAY_A);
247 $column = apply_filters('wpdatatables_filter_column_metadata', $column, $columnId);
248
249 return $column;
250 }
251
252 /**
253 * Helper method that formats table config data in a format for DB
254 * and saves to DB
255 * @param $table - stdObj with table dada
256 */
257 public static function saveTableToDB($table) {
258 global $wpdb, $wdtVar1, $wdtVar2, $wdtVar3;
259
260 // Fetching the 3 placeholders
261 $wdtVar1 = isset($table->var1) ?
262 sanitize_text_field($table->var1) : '';
263 $wdtVar2 = isset($table->var2) ?
264 sanitize_text_field($table->var2) : '';
265 $wdtVar3 = isset($table->var3) ?
266 sanitize_text_field($table->var3) : '';
267
268 // Preparing the config
269 $tableConfig = array(
270 'title' => $table->title,
271 'show_title' => $table->show_title,
272 'table_type' => $table->table_type,
273 'content' => $table->content,
274 'file_location' => $table->file_location,
275 'sorting' => $table->sorting,
276 'fixed_layout' => $table->fixed_layout,
277 'word_wrap' => $table->word_wrap,
278 'tools' => $table->tools,
279 'display_length' => $table->display_length,
280 'hide_before_load' => $table->hide_before_load,
281 'tabletools_config' => serialize($table->tabletools_config),
282 'responsive' => $table->responsive,
283 'scrollable' => $table->scrollable,
284 'auto_refresh' => $table->auto_refresh,
285 'editor_roles' => $table->editor_roles,
286 'cache_source_data' => $table->cache_source_data,
287 'auto_update_cache' => $table->auto_update_cache,
288
289
290 'userid_column_id' => (int)$table->userid_column_id,
291 'var1' => $wdtVar1,
292 'var2' => $wdtVar2,
293 'var3' => $wdtVar3,
294 'advanced_settings' => json_encode(
295 array(
296 'info_block' => $table->info_block,
297 'showTableToolsIncludeHTML' => $table->showTableToolsIncludeHTML,
298 'showTableToolsIncludeTitle' => $table->showTableToolsIncludeTitle,
299 'responsiveAction' => $table->responsiveAction,
300 'pagination' => $table->pagination,
301 'paginationAlign' => $table->paginationAlign,
302 'paginationLayout' => $table->paginationLayout,
303 'paginationLayoutMobile' => $table->paginationLayoutMobile,
304 'global_search' => $table->global_search,
305 'showRowsPerPage' => $table->showRowsPerPage,
306 'clearFilters' => $table->clearFilters,
307 'simpleResponsive' => $table->simpleResponsive,
308 'simpleHeader' => $table->simpleHeader,
309 'stripeTable' => $table->stripeTable,
310 'cellPadding' => $table->cellPadding,
311 'removeBorders' => $table->removeBorders,
312 'borderCollapse' => $table->borderCollapse,
313 'borderSpacing' => $table->borderSpacing,
314 'verticalScroll' => $table->verticalScroll,
315 'verticalScrollHeight' => $table->verticalScrollHeight,
316 'pdfPaperSize' => $table->pdfPaperSize,
317 'pdfPageOrientation' => $table->pdfPageOrientation,
318 'table_description' => $table->table_description,
319 'show_table_description' => $table->show_table_description,
320 'table_wcag' => $table->table_wcag,
321 'simple_template_id' => $table->simple_template_id,
322 'pagination_top' => $table->pagination_top,
323 )
324 )
325 );
326
327 $tableConfig = apply_filters('wpdatatables_filter_insert_table_array', $tableConfig);
328
329 if (!$table->id) {
330 // It is a new table.
331 // Inserting an entry to wp_wpdatatables table
332 $wpdb->insert(
333 $wpdb->prefix . 'wpdatatables',
334 $tableConfig
335 );
336 } else {
337 // It is an existing table.
338 // Updating the DB entry
339 $wpdb->update(
340 $wpdb->prefix . 'wpdatatables',
341 $tableConfig,
342 array(
343 'id' => $table->id
344 )
345 );
346 }
347
348 do_action('wpdatatables_after_save_table', $table->id);
349
350 }
351
352 /**
353 * Helper method for sanitizing the user input in the table config
354 * @param stdClass $table object with table config
355 * @return stdClass object with sanitized table config
356 */
357 public static function sanitizeTableConfig($table) {
358 if (isset($table->id)) {
359 $table->id = (int)$table->id;
360 }
361 $table->title = sanitize_text_field($table->title);
362 $table->show_title = (int)$table->show_title;
363 $table->table_description = sanitize_textarea_field($table->table_description);
364 $table->show_table_description = (int)$table->show_table_description;
365 $table->table_type = sanitize_text_field($table->table_type);
366 $table->tools = (int)$table->tools;
367 $table->showTableToolsIncludeHTML = (int)$table->showTableToolsIncludeHTML;
368 $table->showTableToolsIncludeTitle = (int)$table->showTableToolsIncludeTitle;
369 $table->responsive = (int)$table->responsive;
370 $table->hide_before_load = (int)$table->hide_before_load;
371 $table->fixed_layout = (int)$table->fixed_layout;
372 $table->scrollable = (int)$table->scrollable;
373 $table->sorting = (int)$table->sorting;
374 $table->word_wrap = (int)$table->word_wrap;
375 $table->server_side = (int)$table->server_side;
376 $table->auto_refresh = (int)$table->auto_refresh;
377 $table->info_block = (int)$table->info_block;
378 $table->responsiveAction = sanitize_text_field($table->responsiveAction);
379 $table->cache_source_data = (int)$table->cache_source_data;
380 $table->auto_update_cache = (int)$table->auto_update_cache;
381 $table->pagination = (int)$table->pagination;
382 $table->paginationAlign = sanitize_text_field($table->paginationAlign);
383 $table->paginationLayout = sanitize_text_field($table->paginationLayout);
384 $table->paginationLayoutMobile = sanitize_text_field($table->paginationLayoutMobile);
385 $table->file_location = sanitize_text_field($table->file_location);
386 $table->simpleResponsive = (int)$table->simpleResponsive;
387 $table->simpleHeader = (int)$table->simpleHeader;
388 $table->stripeTable = (int)$table->stripeTable;
389 $table->cellPadding = (int)$table->cellPadding;
390 $table->removeBorders = (int)$table->removeBorders;
391 $table->borderCollapse = sanitize_text_field($table->borderCollapse);
392 $table->borderSpacing = (int)$table->borderSpacing;
393 $table->verticalScroll = (int)$table->verticalScroll;
394 $table->verticalScrollHeight = (int)$table->verticalScrollHeight;
395 $table->filtering = (int)$table->filtering;
396 $table->global_search = (int)$table->global_search;
397 $table->editable = (int)$table->editable;
398 $table->popover_tools = (int)$table->popover_tools;
399 $table->edit_only_own_rows = (int)$table->edit_only_own_rows;
400 $table->inline_editing = (int)$table->inline_editing;
401 $table->mysql_table_name = sanitize_text_field($table->mysql_table_name);
402 $table->filtering_form = (int)$table->filtering_form;
403 $table->clearFilters = (int)$table->clearFilters;
404 $table->display_length = (int)$table->display_length;
405 $table->showRowsPerPage = (int)$table->showRowsPerPage;
406 $table->pdfPaperSize = sanitize_text_field($table->pdfPaperSize);
407 $table->pdfPageOrientation = sanitize_text_field($table->pdfPageOrientation);
408 $table->table_wcag = (int)($table->table_wcag);
409 $table->simple_template_id = (int)$table->simple_template_id;
410 $table->pagination_top = (int)$table->pagination_top;
411 $table->userid_column_id = $table->userid_column_id != null ?
412 (int)$table->userid_column_id : null;
413
414 if (!empty($table->editor_roles)) {
415 $table->editor_roles = (array)$table->editor_roles;
416 foreach ($table->editor_roles as &$editor_roles) {
417 $editor_roles = sanitize_text_field($editor_roles);
418 }
419 } else {
420 $table->editor_roles = array();
421 }
422 $table->editor_roles = implode(",", $table->editor_roles);
423
424 if (!empty($table->tabletools_config)) {
425 $table->tabletools_config = (array)$table->tabletools_config;
426 foreach ($table->tabletools_config as &$tabletools_config) {
427 $tabletools_config = (int)$tabletools_config;
428 }
429 } else {
430 $table->tabletools_config = array();
431 }
432
433 if ($table->table_type == 'nested_json' && isset($table->jsonAuthParams)) {
434 $table->jsonAuthParams = WDTConfigController::sanitizeNestedJsonParams($table->jsonAuthParams);
435 $table->content = json_encode($table->jsonAuthParams);
436 }
437
438 if ($table->table_type != 'simple') {
439 $table->columns = WDTConfigController::sanitizeColumnsConfig($table->columns);
440 } else {
441 $table = self::sanitizeTableSettingsSimpleTable($table);
442 }
443
444 if ($table->file_location == 'wp_media_lib' &&
445 (($table->table_type == 'csv') || ($table->table_type == 'xls'))
446 ) {
447 $table->content = WDTTools::urlToPath($table->content);
448 }
449
450 return $table;
451
452 }
453
454 /**
455 * Helper method for sanitizing the user input in the table settings of Simple table
456 * @param stdClass $table object with table config
457 * @return stdClass object with sanitized table config
458 */
459 public static function sanitizeTableSettingsSimpleTable($table) {
460 $table->method = 'simple';
461 $table->connection = '';
462 $table->columnCount = 0;
463 $table->columns = array();
464
465 if (isset($table->name)){
466 $table->name = sanitize_text_field($table->name);
467 } else {
468 $table->name = '';
469 }
470 if (isset($table->table_description)){
471 $table->table_description = sanitize_textarea_field($table->table_description);
472 } else {
473 $table->table_description = '';
474 }
475
476 if (isset($table->content)){
477 $isContentObj = false;
478 if (!is_object($table->content)){
479 $isContentObj = true;
480 $table->content = json_decode($table->content);
481 }
482 if (isset($table->content->colNumber)){
483 $table->content->colNumber = (int)$table->content->colNumber;
484 } else {
485 $table->content->colNumber = 5;
486 }
487
488 if (isset($table->content->rowNumber)){
489 $table->content->rowNumber = (int)$table->content->rowNumber;
490 } else {
491 $table->content->rowNumber = 5;
492 }
493
494 if (isset($table->content->reloadCounter)){
495 $table->content->reloadCounter = (int)$table->content->reloadCounter;
496 } else {
497 $table->content->reloadCounter = 0;
498 }
499
500 if (isset($table->content->mergedCells)){
501 if (!empty($table->content->mergedCells)){
502 foreach ($table->content->mergedCells as $key => $mergedCell){
503 $table->content->mergedCells[$key]->row = (int)$mergedCell->row;
504 $table->content->mergedCells[$key]->col = (int)$mergedCell->col;
505 $table->content->mergedCells[$key]->rowspan = (int)$mergedCell->rowspan;
506 $table->content->mergedCells[$key]->colspan = (int)$mergedCell->colspan;
507 $table->content->mergedCells[$key]->removed = (bool)$mergedCell->removed;
508 }
509 } else {
510 $table->content->mergedCells = array();
511 }
512 }
513 if (isset($table->content->colHeaders)){
514 if (!empty($table->content->colHeaders)){
515 foreach ($table->content->colHeaders as $keyColHeader => $colHeader){
516 $table->content->colHeaders[$keyColHeader] = sanitize_text_field($colHeader);
517 }
518 } else {
519 $table->content->colHeaders = array();
520 }
521 }
522 if (isset($table->content->colWidths)){
523 foreach ($table->content->colWidths as $keyColWidth => $colWidth){
524 $table->content->colWidths[$keyColWidth] = (int)$colWidth;
525 }
526 }
527 if ($isContentObj){
528 $table->content = json_encode($table->content);
529 }
530 }
531 return $table;
532 }
533
534 /**
535 * Helper method for sanitizing the user input in the row data of Simple table
536 */
537 public static function sanitizeRowDataSimpleTable($rowsData, $tableID) {
538 $rowsDataSanitized = [];
539 foreach ($rowsData as $rowKey => $rowData){
540 $rowsDataSanitized[$rowKey] = $rowData;
541 foreach ($rowsDataSanitized[$rowKey]->cells as $cellKey => $cell){
542 if ($cell->data != '' ){
543 if ( ! current_user_can( 'unfiltered_html' ) ) {
544 $rowsDataSanitized[$rowKey]->cells[$cellKey]->data = wp_kses_post($cell->data);
545 } else {
546 $rowsDataSanitized[$rowKey]->cells[$cellKey]->data = $cell->data;
547 }
548 } else {
549 $rowsDataSanitized[$rowKey]->cells[$cellKey]->data = '';
550 }
551 }
552 }
553
554 return $rowsDataSanitized;
555 }
556
557 /**
558 * Helper method for sanitizing the user input for nested JSON params
559 * @param stdClass $jsonParams object with nested JSON params
560 * @return stdClass object with sanitized nested JSON params
561 */
562 public static function sanitizeNestedJsonParams($jsonParams){
563 $sanitizedParams = new stdClass();
564
565 if (isset($jsonParams->url)){
566 $sanitizedParams->url = sanitize_url($jsonParams->url);
567 if ( is_admin() && ! current_user_can( 'unfiltered_html' ) )
568 $sanitizedParams->url = sanitize_url(wp_kses_post($jsonParams->url));
569 } else {
570 $sanitizedParams->url = '';
571 }
572
573 if (isset($jsonParams->method)){
574 $sanitizedParams->method = sanitize_text_field($jsonParams->method);
575 } else {
576 $sanitizedParams->method = 'get';
577 }
578
579 if (isset($jsonParams->authOption)){
580 $sanitizedParams->authOption = sanitize_text_field($jsonParams->authOption);
581 } else {
582 $sanitizedParams->authOption = '';
583 }
584 if (isset($jsonParams->username)){
585 $sanitizedParams->username = sanitize_text_field($jsonParams->username);
586 if ( is_admin() && ! current_user_can( 'unfiltered_html' ) )
587 $sanitizedParams->username = sanitize_text_field(wp_kses_post($jsonParams->username));
588 } else {
589 $sanitizedParams->username = '';
590 }
591 if (isset($jsonParams->password)){
592 $sanitizedParams->password = sanitize_text_field($jsonParams->password);
593 if ( is_admin() && ! current_user_can( 'unfiltered_html' ) )
594 $sanitizedParams->password = sanitize_text_field(wp_kses_post($jsonParams->password));
595 } else {
596 $sanitizedParams->password = '';
597 }
598 if (isset($jsonParams->customHeaders) && !empty($jsonParams->customHeaders)){
599 foreach ($jsonParams->customHeaders as &$customHeader){
600 $customHeader->setKeyName = sanitize_text_field($customHeader->setKeyName);
601 $customHeader->setKeyValue = sanitize_textarea_field($customHeader->setKeyValue);
602 if ( is_admin() && ! current_user_can( 'unfiltered_html' ) ) {
603 $customHeader->setKeyName = sanitize_text_field(wp_kses_post($customHeader->setKeyName));
604 $customHeader->setKeyValue = sanitize_textarea_field(wp_kses_post($customHeader->setKeyValue));
605 }
606 }
607 $sanitizedParams->customHeaders = $jsonParams->customHeaders;
608 } else {
609 $sanitizedParams->customHeaders = [];
610 }
611 if (isset($jsonParams->root)){
612 $sanitizedParams->root = sanitize_text_field($jsonParams->root);
613 } else {
614 $sanitizedParams->root = '';
615 }
616
617 return $sanitizedParams;
618 }
619
620 /**
621 * Helper method for sanitizing the user input in the table config
622 * @param array $columns Array with the columns coming from front-end form
623 * @return array $columns Array with sanitized column data
624 */
625 public static function sanitizeColumnsConfig($columns) {
626 if (!empty($columns)) {
627 foreach ($columns as &$column) {
628 $column->calculateAvg = (int)$column->calculateAvg;
629 $column->calculateMax = (int)$column->calculateMax;
630 $column->calculateMin = (int)$column->calculateMin;
631 $column->calculateTotal = (int)$column->calculateTotal;
632 $column->color = sanitize_text_field($column->color);
633 $column->dateInputFormat = sanitize_text_field($column->dateInputFormat);
634 $column->decimalPlaces = (int)$column->decimalPlaces;
635 $column->defaultSortingColumn = (int)$column->defaultSortingColumn;
636 $column->display_header = sanitize_text_field($column->display_header);
637 $column->editingDefaultValue = sanitize_text_field($column->editingDefaultValue);
638 $column->exactFiltering = (int)$column->exactFiltering;
639 $column->globalSearchColumn = (int)($column->globalSearchColumn);
640 $column->filterDefaultValue = sanitize_text_field($column->filterDefaultValue);
641 $column->filterLabel = sanitize_text_field($column->filterLabel);
642 $column->formula = sanitize_text_field($column->formula);
643 $column->hide_on_mobiles = (int)$column->hide_on_mobiles;
644 $column->hide_on_tablets = (int)$column->hide_on_tablets;
645 $column->id = (int)$column->id;
646 $column->id_column = (int)$column->id_column;
647 $column->orig_header = sanitize_text_field($column->orig_header);
648 $column->linkTargetAttribute = sanitize_text_field($column->linkTargetAttribute);
649 $column->linkNofollowAttribute = (int)($column->linkNofollowAttribute);
650 $column->linkNoreferrerAttribute = (int)($column->linkNoreferrerAttribute);
651 $column->linkSponsoredAttribute = (int)($column->linkSponsoredAttribute);
652 $column->linkButtonAttribute = (int)$column->linkButtonAttribute;
653 $column->linkButtonLabel = sanitize_text_field($column->linkButtonLabel);
654 $column->linkButtonClass = sanitize_text_field($column->linkButtonClass);
655 $column->pos = (int)$column->pos;
656 $column->possibleValuesAddEmpty = (int)$column->possibleValuesAddEmpty;
657 $column->possibleValuesType = sanitize_text_field($column->possibleValuesType);
658 $column->column_align_fields = sanitize_text_field($column->column_align_fields);
659 $column->column_align_header = sanitize_text_field($column->column_align_header);
660 $column->skip_thousands_separator = (int)$column->skip_thousands_separator;
661 $column->sorting = (int)$column->sorting;
662 if (is_admin() && ! current_user_can( 'unfiltered_html' ) ) {
663 if (is_null($column->text_after)){
664 $column->text_after = sanitize_text_field($column->text_after);
665 } else {
666 $column->text_after = sanitize_text_field(wp_kses_post($column->text_after));
667 }
668 if (is_null($column->text_before)){
669 $column->text_before = sanitize_text_field($column->text_before);
670 } else {
671 $column->text_before = sanitize_text_field(wp_kses_post($column->text_before));
672 }
673 } else {
674 $column->text_after = (string)$column->text_after;
675 $column->text_before = (string)$column->text_before;
676 }
677 $column->css_class = sanitize_text_field($column->css_class);
678 $column->type = sanitize_text_field($column->type);
679 $column->visible = (int)$column->visible;
680 $column->width = sanitize_text_field($column->width);
681
682 if (isset($column->foreignKeyRule->tableId) && $column->foreignKeyRule->tableId != 0) {
683 $column->foreignKeyRule->tableId = (int)$column->foreignKeyRule->tableId;
684 $column->foreignKeyRule->tableName = sanitize_text_field($column->foreignKeyRule->tableName);
685 $column->foreignKeyRule->displayColumnId = (int)$column->foreignKeyRule->displayColumnId;
686 $column->foreignKeyRule->displayColumnName = sanitize_text_field($column->foreignKeyRule->displayColumnName);
687 $column->foreignKeyRule->storeColumnId = (int)$column->foreignKeyRule->storeColumnId;
688 $column->foreignKeyRule->storeColumnName = sanitize_text_field($column->foreignKeyRule->storeColumnName);
689 }
690 }
691 }
692 return $columns;
693 }
694
695 /**
696 * Helper method that tries to create a wpDataTable based on the provided content
697 * Returns an object which contains a wpDataTable in case of success,
698 * or an error message otherwise
699 *
700 * @param $type - Type of the table (mysql, excel, csv, google spreadsheet, serialized array)
701 * @param $content - Content for creating the table (path to source or a MySQL query)
702 * @return stdClass Object which has an 'error' property in case there were problems, or a 'table' on success
703 */
704 public static function tryCreateTable($type, $content, $fileLocation = '') {
705
706 global $wdtVar1, $wdtVar2, $wdtVar3;
707
708 $tbl = new WPDataTable();
709 $result = new stdClass();
710
711 do_action('wpdatatables_try_generate_table', $type, $content);
712
713 // Defining the table data for init read
714 $tableData = new stdClass();
715 $tableData->table_type = $type;
716 $tableData->content = $content;
717 $tableData->file_location = $fileLocation;
718 $tableData->init_read = true;
719 $tableData->limit = 10;
720 $tableData->var1 = !empty($wdtVar1) ? $wdtVar1 : '';
721 $tableData->var2 = !empty($wdtVar2) ? $wdtVar2 : '';
722 $tableData->var3 = !empty($wdtVar3) ? $wdtVar3 : '';
723
724 // Trying to generate the table and returning
725 // an error message in case of thrown exception
726 try {
727 $tbl->fillFromData($tableData, array());
728 if ($tbl->getNoData()) {
729 throw new WDTException(__('Table in data source has no rows.', 'wpdatatables'));
730 }
731 $result->table = $tbl;
732 } catch (Exception $e) {
733 $result->error = $e->getMessage();
734 return $result;
735 }
736
737 $result = apply_filters('wpdatatables_try_generate_table_result', $result);
738
739 return $result;
740
741 }
742
743 /**
744 * Save the columns for the table in DB
745 * @param $frontendColumns array of column config objects in front-end format
746 * @param $table WPDataTable object that is generated from the data source
747 * @param $tableId int ID of the table
748 */
749 public static function saveColumns($frontendColumns, $table, $tableId) {
750 global $wpdb;
751
752 do_action('wpdatatables_before_create_columns', $table, $tableId, $frontendColumns);
753
754 // Get existing columns array
755 $existingColumnsQuery = $wpdb->prepare(
756 "SELECT orig_header
757 FROM " . $wpdb->prefix . "wpdatatables_columns
758 WHERE table_id = %d",
759 $tableId
760 );
761
762 $columnsNotInSource = $wpdb->get_col($existingColumnsQuery);
763
764 $existingColumnsTypesQuery = $wpdb->prepare(
765 "SELECT column_type
766 FROM " . $wpdb->prefix . "wpdatatables_columns
767 WHERE table_id = %d",
768 $tableId
769 );
770
771 $columnsTypes = $wpdb->get_col($existingColumnsTypesQuery);
772 $columnsTypesArray = array_diff(array_combine($columnsNotInSource, $columnsTypes), ['formula']);
773
774 // Getting columns returned by the data source
775 $dataSourceColumns = $table->getColumns();
776
777 $dataSourceColumnsHeaders = array_map(function ($column) {
778 return $column->getOriginalHeader();
779 }, $dataSourceColumns);
780
781 self::$_resetColumnPosition = count(array_diff($dataSourceColumnsHeaders, array_keys($columnsTypesArray))) > 0 ||
782 count(array_diff(array_keys($columnsTypesArray), $dataSourceColumnsHeaders)) > 0;
783
784 /** @var WDTColumn $column */
785 foreach ($dataSourceColumns as $key => &$column) {
786
787 $columnConfig = self::prepareDBColumnConfig($column, $frontendColumns, $tableId, $key);
788
789 // Change column type in database structure, if column type is changes on the frontend
790 if ($table->getTableType() == 'manual' && $columnsTypesArray[$column->getOriginalHeader()] != $columnConfig['column_type']) {
791
792 switch ($columnConfig['column_type']) {
793 case 'int':
794 $newType = 'INT(11)';
795 break;
796 case 'float':
797 $newType = 'DECIMAL(16,4)';
798 break;
799 case 'date':
800 $newType = 'date';
801 break;
802 case 'datetime':
803 $newType = 'datetime';
804 break;
805 case 'time':
806 $newType = 'time';
807 break;
808 default:
809 $newType = 'VARCHAR(255)';
810 }
811
812 $mySqlTable = substr($table->getTableContent(), strpos($table->getTableContent(), 'FROM') + 5);
813 $alterQuery = "ALTER TABLE {$mySqlTable} MODIFY COLUMN {$columnConfig['orig_header']} {$newType}";
814
815 if (!get_option('wdtUseSeparateCon')) {
816 $wpdb->query($alterQuery);
817 } else {
818 $sql = new PDTSql(WDT_MYSQL_HOST, WDT_MYSQL_DB, WDT_MYSQL_USER, WDT_MYSQL_PASSWORD, WDT_MYSQL_PORT);
819 $sql->doQuery($alterQuery);
820 }
821 }
822
823 $columnConfig = apply_filters('wpdatatables_filter_column_before_save', $columnConfig, $tableId);
824
825 // Removing this column from the array of marked for deletion
826 $columnsNotInSource = array_diff($columnsNotInSource, array($columnConfig['orig_header']));
827
828 self::saveSingleColumn($columnConfig);
829
830 }
831
832 // Go through the formula columns and add / update them
833 if ($frontendColumns != null) {
834 foreach ($frontendColumns as $feColumn) {
835 // We are only interested in formula columns in this loop
836 if ($feColumn->type != 'formula') {
837 continue;
838 }
839
840 // Removing this column from the array of marked for deletiong
841 $columnsNotInSource = array_diff($columnsNotInSource, array($feColumn->orig_header));
842
843 $wdtColumn = WDTColumn::generateColumn(
844 'formula',
845 array(
846 'orig_header' => $feColumn->orig_header,
847 'decimalPlaces' => $feColumn->decimalPlaces
848 )
849 );
850 $columnConfig = self::prepareDBColumnConfig($wdtColumn, $frontendColumns, $tableId);
851 $columnConfig['filter_type'] = 'none';
852
853 self::saveSingleColumn($columnConfig);
854
855 }
856 }
857
858 // Delete columns that are not in source any more
859 foreach ($columnsNotInSource as $orig_header) {
860
861 // If column doesn't exist in front-end, or doesn't exist in data source any more we delete it
862 $wpdb->delete(
863 $wpdb->prefix . "wpdatatables_columns",
864 array(
865 'orig_header' => $orig_header,
866 'table_id' => $tableId
867 ),
868 array(
869 '%s',
870 '%d'
871 )
872 );
873
874 }
875
876 do_action('wpdatatables_after_save_columns');
877
878 }
879
880 /**
881 * Method iterates through the array of column configs received from front-end
882 * Tries to find config for the provided column by the key (original header from the data source)
883 * Returns the config for a given column on success, FALSE on failure.
884 *
885 * @param $frontendColumns
886 * @param $columnOrigHeader
887 * @return bool|StdClass FALSE if column not found, Object with column properties on success
888 */
889 public static function getFrontEndColumnConfig($frontendColumns, $columnOrigHeader) {
890 $result = FALSE;
891 if (!empty($frontendColumns)) {
892 foreach ($frontendColumns as $feColumn) {
893 if ($feColumn->orig_header == $columnOrigHeader) {
894 return $feColumn;
895 }
896 }
897 }
898 return $result;
899 }
900
901 /**
902 * Helper method which prepares the column config object for saving in the DB
903 * Merges the data returned by the data source, and config provided in frontend
904 *
905 * @param WDTColumn $column - wpDataColumn Data for column returned by data source
906 * @param $frontendColumns - Array of objects describing config which was sent from front-end
907 * @param $tableId - ID of the table
908 * @param int $pos - Position of the column in the data source
909 * @return array - Array with merged column config
910 */
911 public static function prepareDBColumnConfig($column, $frontendColumns, $tableId, $pos = 0) {
912 $feColumn = self::getFrontEndColumnConfig($frontendColumns, $column->getOriginalHeader());
913
914 // Initializing config array for the column
915 $columnConfig = array(
916 'calc_formula' => $feColumn ? $feColumn->formula : '',
917 'color' => $feColumn ? $feColumn->color : '',
918 'column_type' => $feColumn ? $feColumn->type : $column->getDataType(),
919 'css_class' => $feColumn ? $feColumn->css_class : '',
920 'display_header' => $feColumn ? $feColumn->display_header : $column->getTitle(),
921 'group_column' => $feColumn ? $feColumn->groupColumn : 0,
922 'hide_on_phones' => $feColumn ? $feColumn->hide_on_mobiles : 0,
923 'hide_on_tablets' => $feColumn ? $feColumn->hide_on_tablets : 0,
924 'id_column' => $feColumn ? $feColumn->id_column : 0,
925 'orig_header' => $column->getOriginalHeader(),
926 'pos' => self::$_resetColumnPosition ? $pos : $feColumn->pos,
927 'skip_thousands_separator' => $feColumn ? $feColumn->skip_thousands_separator : 0,
928 'sort_column' => $feColumn ? $feColumn->defaultSortingColumn : 0,
929 'table_id' => $tableId,
930 'text_after' => $feColumn ? $feColumn->text_after : '',
931 'text_before' => $feColumn ? $feColumn->text_before : '',
932 'visible' => $feColumn ? $feColumn->visible : 1,
933 'width' => $feColumn ? $feColumn->width : '',
934 );
935
936 // Add ID if provided
937 if (isset($feColumn->id)) {
938 $columnConfig['id'] = $feColumn->id;
939 }
940 if (isset($feColumn->defaultSortingColumn)) {
941 $columnConfig['sort_column'] = $feColumn->defaultSortingColumn;
942 }
943
944 // 2.0+ version settings all go to single JSON-encoded DB table column
945 $columnConfig['advanced_settings'] = array();
946
947 $columnConfig['advanced_settings']['decimalPlaces'] =
948 $feColumn ? $feColumn->decimalPlaces : -1;
949 $columnConfig['advanced_settings']['column_align_fields'] =
950 $feColumn ? $feColumn->column_align_fields : '';
951 $columnConfig['advanced_settings']['column_align_header'] =
952 $feColumn ? $feColumn->column_align_header : '';
953 $columnConfig['advanced_settings']['sorting'] =
954 $feColumn ? $feColumn->sorting : 1;
955 $columnConfig['advanced_settings']['dateInputFormat'] =
956 $feColumn ? $feColumn->dateInputFormat : '';
957 $columnConfig['advanced_settings']['linkTargetAttribute'] =
958 $feColumn ? $feColumn->linkTargetAttribute : '';
959 $columnConfig['advanced_settings']['linkNofollowAttribute'] =
960 $feColumn ? $feColumn->linkNofollowAttribute : 0;
961 $columnConfig['advanced_settings']['linkNoreferrerAttribute'] =
962 $feColumn ? $feColumn->linkNoreferrerAttribute : 0;
963 $columnConfig['advanced_settings']['linkSponsoredAttribute'] =
964 $feColumn ? $feColumn->linkSponsoredAttribute : 0;
965 $columnConfig['advanced_settings']['linkButtonAttribute'] =
966 $feColumn ? $feColumn->linkButtonAttribute : 0;
967 $columnConfig['advanced_settings']['linkButtonLabel'] =
968 $feColumn ? $feColumn->linkButtonLabel : null;
969 $columnConfig['advanced_settings']['linkButtonClass'] =
970 $feColumn ? $feColumn->linkButtonClass : null;
971 $columnConfig['advanced_settings']['globalSearchColumn'] =
972 $feColumn ? $feColumn->globalSearchColumn : 1;
973
974
975
976 // JSON-encoding all the 2.0+ settings
977 $columnConfig['advanced_settings'] = json_encode($columnConfig['advanced_settings']);
978
979 return $columnConfig;
980 }
981
982 /**
983 * Tries to save (insert or update) a column with the provided config to the database
984 * Throws exception on error with DB error message
985 * Otherwise returns true
986 *
987 * @param stdClass $columnConfig Configuration for the column
988 * @return bool True in case column saved successfully
989 * @throws Exception
990 */
991 public static function saveSingleColumn($columnConfig) {
992 global $wpdb;
993
994 if (!empty($columnConfig['id'])) {
995
996 $columnConfig = apply_filters('wpdatatables_filter_update_column_array', $columnConfig, $columnConfig['table_id']);
997
998 $columnId = $columnConfig['id'];
999 unset($columnConfig['id']);
1000
1001 $wpdb->update(
1002 $wpdb->prefix . 'wpdatatables_columns',
1003 $columnConfig,
1004 array(
1005 'id' => $columnId
1006 ),
1007 array(),
1008 array(
1009 '%d'
1010 )
1011 );
1012
1013 } else {
1014
1015 $columnConfig = apply_filters('wpdatatables_filter_insert_column_array', $columnConfig, $columnConfig['table_id']);
1016
1017 $wpdb->insert(
1018 $wpdb->prefix . 'wpdatatables_columns',
1019 $columnConfig
1020 );
1021
1022 $columnConfig['id'] = $wpdb->insert_id;
1023 }
1024
1025 if ($wpdb->last_error !== '') {
1026 throw new Exception($wpdb->last_error);
1027 } else {
1028 do_action('wpdatatables_after_insert_column', $columnConfig, $columnConfig['table_id']);
1029 return true;
1030 }
1031
1032 }
1033
1034 /**
1035 * Method which returns an array of column config objects for front-end
1036 * @param $tableId
1037 * @return array Array of column config objects
1038 */
1039 public static function getColumnsConfig($tableId) {
1040
1041 $dbColumns = self::loadColumnsFromDB($tableId);
1042
1043 $feColumns = array();
1044
1045 if (!empty($dbColumns)) {
1046 foreach ($dbColumns as $dbColumn) {
1047 $feColumns[] = self::prepareFEColumnConfig($dbColumn);
1048 }
1049 }
1050
1051 return $feColumns;
1052 }
1053
1054 /**
1055 * Method which prepares a column description object to be returned to frontend JSON
1056 * @param $dbColumn - Array with the column config from DB
1057 * @return stdClass A class describing the column config for front-end
1058 */
1059 public static function prepareFEColumnConfig($dbColumn) {
1060 $feColumn = new stdClass();
1061
1062 $feColumn->calculateTotal = (int)$dbColumn->sum_column;
1063 $feColumn->color = $dbColumn->color;
1064 $feColumn->conditional_formatting = json_decode($dbColumn->formatting_rules);
1065 $feColumn->css_class = $dbColumn->css_class;
1066 $feColumn->defaultSortingColumn = (int)$dbColumn->sort_column;
1067 $feColumn->display_header = $dbColumn->display_header;
1068 $feColumn->editor_type = $dbColumn->input_type;
1069 $feColumn->filter_type = $dbColumn->filter_type;
1070 $feColumn->filterDefaultValue = $dbColumn->default_value;
1071 $feColumn->formula = $dbColumn->calc_formula;
1072 $feColumn->groupColumn = (int)$dbColumn->group_column;
1073 $feColumn->hide_on_mobiles = (int)$dbColumn->hide_on_phones;
1074 $feColumn->hide_on_tablets = (int)$dbColumn->hide_on_tablets;
1075 $feColumn->id = (int)$dbColumn->id;
1076 $feColumn->id_column = (int)$dbColumn->id_column;
1077 $feColumn->input_mandatory = (int)$dbColumn->input_mandatory;
1078 $feColumn->orig_header = $dbColumn->orig_header;
1079 $feColumn->pos = (int)$dbColumn->pos;
1080 $feColumn->skip_thousands_separator = (int)$dbColumn->skip_thousands_separator;
1081 $feColumn->text_after = $dbColumn->text_after;
1082 $feColumn->text_before = $dbColumn->text_before;
1083 $feColumn->type = $dbColumn->column_type;
1084 $feColumn->valuesList = $dbColumn->possible_values;
1085 $feColumn->visible = (int)$dbColumn->visible;
1086 $feColumn->width = $dbColumn->width;
1087
1088 $advancedSettings = json_decode($dbColumn->advanced_settings);
1089 $feColumn->decimalPlaces = isset($advancedSettings->decimalPlaces) ?
1090 $advancedSettings->decimalPlaces : -1;
1091 $feColumn->possibleValuesAddEmpty = isset($advancedSettings->possibleValuesAddEmpty) ?
1092 $advancedSettings->possibleValuesAddEmpty : 0;
1093 $feColumn->column_align_fields = isset($advancedSettings->column_align_fields) ?
1094 $advancedSettings->column_align_fields : '';
1095 $feColumn->column_align_header = isset($advancedSettings->column_align_header) ?
1096 $advancedSettings->column_align_header : '';
1097 $feColumn->calculateAvg = isset($advancedSettings->calculateAvg) ?
1098 $advancedSettings->calculateAvg : 0;
1099 $feColumn->calculateMax = isset($advancedSettings->calculateMax) ?
1100 $advancedSettings->calculateMax : 0;
1101 $feColumn->calculateMin = isset($advancedSettings->calculateMin) ?
1102 $advancedSettings->calculateMin : 0;
1103 $feColumn->sorting = isset($advancedSettings->sorting) ?
1104 $advancedSettings->sorting : 1;
1105 $feColumn->exactFiltering = isset($advancedSettings->exactFiltering) ?
1106 $advancedSettings->exactFiltering : 0;
1107 $feColumn->filterLabel = isset($advancedSettings->filterLabel) ?
1108 $advancedSettings->filterLabel : null;
1109 $feColumn->possibleValuesType = isset($advancedSettings->possibleValuesType) ?
1110 $advancedSettings->possibleValuesType : 'read';
1111 $feColumn->editingDefaultValue = isset($advancedSettings->editingDefaultValue) ?
1112 $advancedSettings->editingDefaultValue : null;
1113 $feColumn->dateInputFormat = isset($advancedSettings->dateInputFormat) ?
1114 $advancedSettings->dateInputFormat : '';
1115 $feColumn->linkTargetAttribute = isset($advancedSettings->linkTargetAttribute) ?
1116 $advancedSettings->linkTargetAttribute : '';
1117 $feColumn->linkNofollowAttribute = isset($advancedSettings->linkNofollowAttribute) ?
1118 $advancedSettings->linkNofollowAttribute : 0;
1119 $feColumn->linkNoreferrerAttribute = isset($advancedSettings->linkNoreferrerAttribute) ?
1120 $advancedSettings->linkNoreferrerAttribute : 0;
1121 $feColumn->linkSponsoredAttribute = isset($advancedSettings->linkSponsoredAttribute) ?
1122 $advancedSettings->linkSponsoredAttribute : 0;
1123 $feColumn->linkButtonAttribute = isset($advancedSettings->linkButtonAttribute) ?
1124 $advancedSettings->linkButtonAttribute : 0;
1125 $feColumn->linkButtonLabel = isset($advancedSettings->linkButtonLabel) ?
1126 $advancedSettings->linkButtonLabel : null;
1127 $feColumn->linkButtonClass = isset($advancedSettings->linkButtonClass) ?
1128 $advancedSettings->linkButtonClass : null;
1129 $feColumn->globalSearchColumn = isset($advancedSettings->globalSearchColumn) ?
1130 $advancedSettings->globalSearchColumn : 1;
1131
1132 if ($feColumn->possibleValuesType == 'foreignkey') {
1133 if (!isset($feColumn->foreignKeyRule)) {
1134 $feColumn->foreignKeyRule = new stdClass();
1135 }
1136 $feColumn->foreignKeyRule->tableId = $advancedSettings->foreignKeyRule->tableId;
1137 $feColumn->foreignKeyRule->tableName = $advancedSettings->foreignKeyRule->tableName;
1138 $feColumn->foreignKeyRule->displayColumnId = $advancedSettings->foreignKeyRule->displayColumnId;
1139 $feColumn->foreignKeyRule->displayColumnName = $advancedSettings->foreignKeyRule->displayColumnName;
1140 $feColumn->foreignKeyRule->storeColumnId = $advancedSettings->foreignKeyRule->storeColumnId;
1141 $feColumn->foreignKeyRule->storeColumnName = $advancedSettings->foreignKeyRule->storeColumnName;
1142 }
1143
1144 return $feColumn;
1145
1146 }
1147
1148 /**
1149 * Helper method returning default settings for table object
1150 * @return stdClass with default settings for the table object
1151 * // TODO - allow changing/saving default settings from GUI
1152 */
1153 public static function getConfigDefaults() {
1154 $table = new \stdClass();
1155 $table->id = null;
1156 $table->title = '';
1157 $table->show_title = 0;
1158 $table->table_type = '';
1159 $table->showTableToolsIncludeHTML = 0;
1160 $table->showTableToolsIncludeTitle = 0;
1161 $table->tools = 1;
1162 $table->responsive = 0;
1163 $table->hide_before_load = 1;
1164 $table->fixed_layout = 0;
1165 $table->scrollable = 0;
1166 $table->verticalScroll = 0;
1167 $table->sorting = 1;
1168 $table->word_wrap = 0;
1169 $table->server_side = 0;
1170 $table->auto_refresh = 0;
1171 $table->info_block = 1;
1172 $table->responsiveAction = 'icon';
1173 $table->pagination_top = 0;
1174 $table->pagination = 1;
1175 $table->paginationAlign = 'right';
1176 $table->paginationLayout = 'full_numbers';
1177 $table->paginationLayoutMobile = 'simple';
1178 $table->file_location = 'wp_media_lib';
1179 $table->simpleResponsive = 0;
1180 $table->cache_source_data = 0;
1181 $table->auto_update_cache = 0;
1182 $table->simpleHeader = 0;
1183 $table->stripeTable = 0;
1184 $table->cellPadding = 10;
1185 $table->removeBorders = 0;
1186 $table->borderCollapse = 'collapse';
1187 $table->borderSpacing = 0;
1188 $table->verticalScrollHeight = 600;
1189 $table->filtering = 1;
1190 $table->global_search = 1;
1191 $table->editable = 0;
1192 $table->popover_tools = 0;
1193 $table->edit_only_own_rows = 0;
1194 $table->inline_editing = 0;
1195 $table->mysql_table_name = '';
1196 $table->filtering_form = 0;
1197 $table->clearFilters = 0;
1198 $table->display_length = 10;
1199 $table->showRowsPerPage = 10;
1200 $table->userid_column_id = null;
1201 $table->editor_roles = array();
1202 $table->tabletools_config = array(
1203 'print' => 1,
1204 'copy' => 1,
1205 'excel' => 1,
1206 'csv' => 1,
1207 'pdf' => 0,
1208 );
1209 $table->columns = array();
1210 $table->content = '';
1211 $table->pdfPaperSize = 'A4';
1212 $table->pdfPageOrientation = 'portrait';
1213 $table->table_description = '';
1214 $table->show_table_description = 0;
1215 $table->table_wcag = 0;
1216 $table->simple_template_id = 0;
1217 return $table;
1218 }
1219 /**
1220 * Helper method that load table config data for Simple table from DB
1221 * @param int $tableID
1222 */
1223 public static function loadSimpleTableConfig($tableID){
1224 $res = new stdClass();
1225
1226 try {
1227 $wpDataTableRows = WPDataTableRows::loadWpDataTableRows($tableID);
1228 $res->tableID = $wpDataTableRows->getTableID();
1229 $res->table = $wpDataTableRows->getTableSettingsData();
1230 $res->wdtHtml = $wpDataTableRows->generateTable($tableID);
1231 } catch (Exception $e) {
1232 $res->error = ltrim($e->getMessage(), '<br/><br/>');
1233 }
1234 return $res;
1235 }
1236 /**
1237 * Helper method that load rows config data from DB
1238 * @param int $tableID
1239 */
1240 public static function loadRowsDataFromDB($tableID){
1241 global $wpdb;
1242
1243 do_action('wpdatatables_before_get_rows_metadata', $tableID);
1244
1245 $rowsQuery = $wpdb->prepare(
1246 "SELECT data FROM " . $wpdb->prefix . "wpdatatables_rows WHERE table_id = %d ORDER BY id ASC", $tableID);
1247
1248 $rows = $wpdb->get_results($rowsQuery);
1249
1250 foreach ($rows as $key=> $row){
1251 $rows[$key] = json_decode($row->data);
1252 }
1253
1254 $rows = apply_filters('wpdatatables_filter_rows_metadata', $rows, $tableID);
1255
1256 return $rows;
1257 }
1258 /**
1259 * Helper method that load rows config data from DB for simple templates (data, content and settings from wpdatatables_templates)
1260 *
1261 * @param int $tableID
1262 */
1263 public static function loadRowsDataFromDBTemplateAll($tableID)
1264 {
1265 global $wpdb;
1266
1267 $rowsQuery = $wpdb->prepare(
1268 "SELECT data, content, settings FROM " . $wpdb->prefix . "wpdatatables_templates WHERE table_id = %d ORDER BY id ASC", $tableID);
1269
1270 $rows = $wpdb->get_results($rowsQuery);
1271
1272 foreach ($rows as $key => $row) {
1273 $rows[$key]->data = json_decode($row->data);
1274 $rows[$key]->content = json_decode($row->content);
1275 $rows[$key]->settings = json_decode($row->settings);
1276 }
1277
1278 return $rows;
1279 }
1280 /**
1281 * Save row data from Simple table in database
1282 * @param stdClass $rowData
1283 * @param int $tableID
1284 */
1285 public static function saveRowData($rowData, $tableID)
1286 {
1287 global $wpdb;
1288
1289 do_action('wpdatatables_before_create_row', $tableID, $rowData);
1290
1291 $wpdb->insert(
1292 $wpdb->prefix . "wpdatatables_rows",
1293 array(
1294 'table_id' => $tableID,
1295 'data' => json_encode($rowData)
1296 )
1297 );
1298
1299 do_action('wpdatatables_after_save_row');
1300 }
1301
1302 /**
1303 * Helper function for getting all tables and charts from the database for page builders
1304 *
1305 * @param $builder
1306 * @param $type
1307 * @return array
1308 */
1309 public static function getAllTablesAndChartsForPageBuilders($builder, $type)
1310 {
1311 $selectedType = substr($type, 0, -1);
1312
1313 global $wpdb;
1314 $returnData = [];
1315
1316 $query = "SELECT id, title FROM {$wpdb->prefix}wpdata{$type} ORDER BY id";
1317
1318 $allItems = $wpdb->get_results($query, ARRAY_A);
1319
1320 if ($builder === 'avada' || $builder === 'elementor' || $builder === 'divi') {
1321 $returnData[0] = esc_attr__( 'Select a ' . $selectedType, 'wpdatatables' );
1322 } else if ($builder === 'bakery') {
1323 $returnData[__( 'Select a ' . $selectedType, 'wpdatatables' )] = '';
1324 }
1325
1326 if ($allItems != null){
1327 foreach ($allItems as $item) {
1328 switch ($builder) {
1329 case 'gutenberg':
1330 $returnData[] = [
1331 'name' => $item['title'],
1332 'id' => $item['id'],
1333 ];
1334 break;
1335 case 'avada':
1336 case 'elementor':
1337 case 'divi':
1338 $returnData[$item['id']] = $item['title'] . ' (id: ' . $item['id'] . ')';
1339 break;
1340 case 'bakery':
1341 $returnData[$item['title']] = $item['id'];
1342 break;
1343 }
1344 }
1345 }
1346 return $returnData;
1347 }
1348
1349 public static function wdt_create_chart_notice() {
1350
1351 return 'Please create a wpDataChart first. You can check out how on this <a target="_blank" href="https://wpdatatables.com/documentation/wpdatacharts/creating-charts-wordpress-wpdatachart-wizard/">link</a>.';
1352
1353 }
1354
1355 public static function wdt_select_chart_notice() {
1356
1357 return 'Please select a wpDataChart.';
1358
1359 }
1360
1361 public static function wdt_create_table_notice() {
1362
1363 return 'Please create a wpDataTable first. You can find detailed instructions in our docs on this <a target="_blank" href="https://wpdatatables.com/documentation/general/features-overview/">link</a>.';
1364 }
1365
1366 public static function wdt_select_table_notice() {
1367
1368 return 'Please select a wpDataTable.';
1369 }
1370
1371 }
1372