wdt_functions.php 26.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
<?php

defined('ABSPATH') or die('Access denied.');

/**
 * Main wpDataTables functions
 * @package wpDataTables
 * @since 1.6.0
 */
?>
<?php

global $wp_version;

/**
 * The installation/activation method, installs the plugin table
 */
function wdtActivationCreateTables() {
    global $wpdb;
    $tablesTableName = $wpdb->prefix . 'wpdatatables';
    $tablesSql = "CREATE TABLE {$tablesTableName} (
						id INT( 11 ) NOT NULL AUTO_INCREMENT,
						title varchar(255) NOT NULL,
                        show_title tinyint(1) NOT NULL default '1',
						table_type varchar(55) NOT NULL,
						content text NOT NULL,
						filtering tinyint(1) NOT NULL default '1',
						filtering_form tinyint(1) NOT NULL default '0',
						sorting tinyint(1) NOT NULL default '1',
						tools tinyint(1) NOT NULL default '1',
						server_side tinyint(1) NOT NULL default '0',
						editable tinyint(1) NOT NULL default '0',
						inline_editing tinyint(1) NOT NULL default '0',
						popover_tools tinyint(1) NOT NULL default '0',
						editor_roles varchar(255) NOT NULL default '',
						mysql_table_name varchar(255) NOT NULL default '',
                        edit_only_own_rows tinyint(1) NOT NULL default 0,
                        userid_column_id int( 11 ) NOT NULL default 0,
						display_length int(3) NOT NULL default '10',
                        auto_refresh int(3) NOT NULL default 0,
						fixed_columns tinyint(1) NOT NULL default '-1',
						fixed_layout tinyint(1) NOT NULL default '0',
						responsive tinyint(1) NOT NULL default '0',
						scrollable tinyint(1) NOT NULL default '0',
						word_wrap tinyint(1) NOT NULL default '0',
						hide_before_load tinyint(1) NOT NULL default '0',
                        var1 VARCHAR( 255 ) NOT NULL default '',
                        var2 VARCHAR( 255 ) NOT NULL default '',
                        var3 VARCHAR( 255 ) NOT NULL default '',
                        tabletools_config VARCHAR( 255 ) NOT NULL default '',
						advanced_settings TEXT NOT NULL default '',
						UNIQUE KEY id (id)
						) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";

    $columnsTableName = $wpdb->prefix . 'wpdatatables_columns';
    $columnsSql = "CREATE TABLE {$columnsTableName} (
						id INT( 11 ) NOT NULL AUTO_INCREMENT,
						table_id int(11) NOT NULL,
						orig_header varchar(255) NOT NULL,
						display_header varchar(255) NOT NULL,
						filter_type enum('none','null_str','text','number','number-range','date-range','datetime-range','time-range','select','multiselect','checkbox') NOT NULL,
						column_type enum('autodetect','string','int','float','date','link','email','image','formula','datetime','time') NOT NULL,
						input_type enum('none','text','textarea','mce-editor','date','datetime','time','link','email','selectbox','multi-selectbox','attachment') NOT NULL default 'text',
						input_mandatory tinyint(1) NOT NULL default '0',
                        id_column tinyint(1) NOT NULL default '0',
						group_column tinyint(1) NOT NULL default '0',
						sort_column tinyint(1) NOT NULL default '0',
						hide_on_phones tinyint(1) NOT NULL default '0',
						hide_on_tablets tinyint(1) NOT NULL default '0',
						visible tinyint(1) NOT NULL default '1',
						sum_column tinyint(1) NOT NULL default '0',
						skip_thousands_separator tinyint(1) NOT NULL default '0',
						width VARCHAR( 4 ) NOT NULL default '',
						possible_values TEXT NOT NULL default '',
						default_value VARCHAR(100) NOT NULL default '',
						css_class VARCHAR(255) NOT NULL default '',
						text_before VARCHAR(255) NOT NULL default '',
						text_after VARCHAR(255) NOT NULL default '',
                        formatting_rules TEXT NOT NULL default '',
                        calc_formula TEXT NOT NULL default '',
						color VARCHAR(255) NOT NULL default '',
						advanced_settings TEXT NOT NULL default '',
						pos int(11) NOT NULL default '0',
						UNIQUE KEY id (id)
						) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";
    $chartsTableName = $wpdb->prefix . 'wpdatacharts';
    $chartsSql = "CREATE TABLE {$chartsTableName} (
                                  id int(11) NOT NULL AUTO_INCREMENT,
                                  wpdatatable_id int(11) NOT NULL,
                                  title varchar(255) NOT NULL,
                                  engine enum('google','highcharts','chartjs') NOT NULL,
                                  type varchar(255) NOT NULL,
                                  json_render_data text NOT NULL,
                                  UNIQUE KEY id (id)
                                ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($tablesSql);
    dbDelta($columnsSql);
    dbDelta($chartsSql);
    if (!get_option('wdtUseSeparateCon')) {
        update_option('wdtUseSeparateCon', false);
    }
    if (!get_option('wdtMySqlHost') === false) {
        update_option('wdtMySqlHost', '');
    }
    if (!get_option('wdtMySqlDB')) {
        update_option('wdtMySqlDB', '');
    }
    if (!get_option('wdtMySqlUser')) {
        update_option('wdtMySqlUser', '');
    }
    if (!get_option('wdtMySqlPwd')) {
        update_option('wdtMySqlPwd', '');
    }
    if (!get_option('wdtMySqlPort')) {
        update_option('wdtMySqlPort', '3306');
    }
    if (!get_option('wdtRenderCharts')) {
        update_option('wdtRenderCharts', 'below');
    }
    if (!get_option('wdtRenderFilter')) {
        update_option('wdtRenderFilter', 'footer');
    }
    if (!get_option('wdtRenderFilter')) {
        update_option('wdtTopOffset', '0');
    }
    if (!get_option('wdtLeftOffset')) {
        update_option('wdtLeftOffset', '0');
    }
    if (!get_option('wdtBaseSkin')) {
        update_option('wdtBaseSkin', 'skin1');
    }
    if (!get_option('wdtTimeFormat')) {
        update_option('wdtTimeFormat', 'h:i A');
    }
    if (!get_option('wdtTimeFormat')) {
        update_option('wdtTimeFormat', 'h:i A');
    }
    if (!get_option('wdtInterfaceLanguage')) {
        update_option('wdtInterfaceLanguage', '');
    }
    if (!get_option('wdtTablesPerPage')) {
        update_option('wdtTablesPerPage', 10);
    }
    if (!get_option('wdtNumberFormat')) {
        update_option('wdtNumberFormat', 1);
    }
    if (!get_option('wdtDecimalPlaces')) {
        update_option('wdtDecimalPlaces', 2);
    }
    if (!get_option('wdtCSVDelimiter')) {
        update_option('wdtCSVDelimiter', ',');
    }
    if (!get_option('wdtDateFormat')) {
        update_option('wdtDateFormat', 'd/m/Y');
    }
    if (get_option('wdtParseShortcodes') === false) {
        update_option('wdtParseShortcodes', false);
    }
    if (get_option('wdtNumbersAlign') === false) {
        update_option('wdtNumbersAlign', true);
    }
    if (get_option('wdtBorderRemoval') === false) {
        update_option('wdtBorderRemoval', 0);
    }
    if (get_option('wdtBorderRemovalHeader') === false) {
        update_option('wdtBorderRemovalHeader', 0);
    }
    if (!get_option('wdtFontColorSettings')) {
        update_option('wdtFontColorSettings', '');
    }
    if (!get_option('wdtCustomJs')) {
        update_option('wdtCustomJs', '');
    }
    if (!get_option('wdtCustomCss')) {
        update_option('wdtCustomCss', '');
    }
    if (get_option('wdtMinifiedJs') === false) {
        update_option('wdtMinifiedJs', 1);
    }
    if (!get_option('wdtTabletWidth')) {
        update_option('wdtTabletWidth', 1024);
    }
    if (!get_option('wdtMobileWidth')) {
        update_option('wdtMobileWidth', 480);
    }
    if (!get_option('wdtPurchaseCode')) {
        update_option('wdtPurchaseCode', '');
    }
    if (get_option('wdtIncludeBootstrap') === false) {
        update_option('wdtIncludeBootstrap', true);
    }
    if (get_option('wdtIncludeBootstrapBackEnd')  === false) {
        update_option('wdtIncludeBootstrapBackEnd', true);
    }
}

function wdtDeactivation() {

}

/**
 * Table and option deleting upon plugin deleting
 */
function wdtUninstallDelete() {
    global $wpdb;

    delete_option('wdtUseSeparateCon');
    delete_option('wdtTimepickerRange');
    delete_option('wdtTimeFormat');
    delete_option('wdtTabletWidth');
    delete_option('wdtTablesPerPage');
    delete_option('wdtSumFunctionsLabel');
    delete_option('wdtRenderFilter');
    delete_option('wdtRenderCharts');
    delete_option('wdtPurchaseCode');
    delete_option('wdtIncludeBootstrap');
    delete_option('wdtIncludeBootstrapBackEnd');
    delete_option('wdtParseShortcodes');
    delete_option('wdtNumbersAlign');
    delete_option('wdtBorderRemoval');
    delete_option('wdtBorderRemovalHeader');
    delete_option('wdtNumberFormat');
    delete_option('wdtMySqlUser');
    delete_option('wdtMySqlPwd');
    delete_option('wdtMySqlPort');
    delete_option('wdtMySqlHost');
    delete_option('wdtMySqlDB');
    delete_option('wdtMobileWidth');
    delete_option('wdtMinifiedJs');
    delete_option('wdtMinFunctionsLabel');
    delete_option('wdtMaxFunctionsLabel');
    delete_option('wdtLeftOffset');
    delete_option('wdtTopOffset');
    delete_option('wdtInterfaceLanguage');
    delete_option('wdtGeneratedTablesCount');
    delete_option('wdtFontColorSettings');
    delete_option('wdtDecimalPlaces');
    delete_option('wdtCSVDelimiter');
    delete_option('wdtDateFormat');
    delete_option('wdtCustomJs');
    delete_option('wdtCustomCss');
    delete_option('wdtBaseSkin');
    delete_option('wdtAvgFunctionsLabel');

    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}wpdatatables");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}wpdatatables_columns");
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}wpdatacharts");
}

/**
 * Activation hook
 * @param $networkWide
 */
function wdtActivation($networkWide) {
    global $wpdb;

    if (function_exists('is_multisite') && is_multisite()) {
        //check if it is network activation if so run the activation function for each id
        if ($networkWide) {
            $oldBlog = $wpdb->blogid;
            //Get all blog ids
            $blogIds = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");

            foreach ($blogIds as $blogId) {
                switch_to_blog($blogId);
                //Create database table if not exists
                wdtActivationCreateTables();
            }
            switch_to_blog($oldBlog);

            return;
        }
    }
    //Create database table if not exists
    wdtActivationCreateTables();
}

/**
 * Uninstall hook
 */
function wdtUninstall() {
    if (function_exists('is_multisite') && is_multisite()) {
        global $wpdb;
        $oldBlog = $wpdb->blogid;
        //Get all blog ids
        $blogIds = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
        foreach ($blogIds as $blogId) {
            switch_to_blog($blogId);
            wdtUninstallDelete();
        }
        switch_to_blog($oldBlog);
    } else {
        wdtUninstallDelete();
    }
}

/**
 * Create tables on every new site (multisite)
 * @param $blogId
 */
function wdtOnCreateSiteOnMultisiteNetwork($blogId) {
    if (is_plugin_active_for_network('wpdatatables/wpdatatables.php')) {
        switch_to_blog($blogId);
        wdtActivationCreateTables();
        restore_current_blog();
    }
}

add_action('wpmu_new_blog', 'wdtOnCreateSiteOnMultisiteNetwork');

/**
 * Delete table on site delete (multisite)
 * @param $tables
 * @return array
 */
function wdtOnDeleteSiteOnMultisiteNetwork($tables) {
    global $wpdb;
    $tables[] = $wpdb->prefix . 'wpdatatables';
    $tables[] = $wpdb->prefix . 'wpdatatables_columns';
    $tables[] = $wpdb->prefix . 'wpdatacharts';

    return $tables;
}

add_filter('wpmu_drop_tables', 'wdtOnDeleteSiteOnMultisiteNetwork');

function wdtAddBodyClass($classes) {

    $classes .= ' wpdt-c';

    return $classes;
}

// Make sure we don't expose any info if called directly
if (!function_exists('add_action')) {
    echo "Hi there!  I'm just a plugin, not much I can do when called directly.";
    exit;
}

/**
 * Helper func that prints out the table
 * @param $id
 */
function wdtOutputTable($id) {
    echo wdtWpDataTableShortcodeHandler(array('id' => $id));
}

/**
 * Handler for the chart shortcode
 * @param $atts
 * @param null $content
 * @return bool|string
 */
function wdtWpDataChartShortcodeHandler($atts, $content = null) {
    extract(shortcode_atts(array(
        'id' => '0'
    ), $atts));


    /** @var mixed $id */
    if (!$id) {
        return false;
    }

    $wpDataChart = new WPDataChart();
    $wpDataChart->setId($id);
    $wpDataChart->loadFromDB();

    $chartExists = $wpDataChart->getwpDataTableId();
    if (empty($chartExists)) {
        return __('wpDataChart with provided ID not found!', 'wpdatatables');
    }

    do_action('wpdatatables_before_render_chart', $wpDataChart->getId());

    return $wpDataChart->renderChart();
}

/**
 * Handler for the table shortcode
 * @param $atts
 * @param null $content
 * @return mixed|string
 */
function wdtWpDataTableShortcodeHandler($atts, $content = null) {
    global $wdtVar1, $wdtVar2, $wdtVar3, $wdtExportFileName;

    extract(shortcode_atts(array(
        'id' => '0',
        'var1' => '%%no_val%%',
        'var2' => '%%no_val%%',
        'var3' => '%%no_val%%',
        'export_file_name' => '%%no_val%%',
        'table_view' => 'regular'
    ), $atts));

    /**
     * Protection
     * @var int $id
     */
    if (!$id) {
        return false;
    }

    $tableData = WDTConfigController::loadTableFromDB($id);
    if (empty($tableData->content)) {
        return __('wpDataTable with provided ID not found!', 'wpdatatables');
    }

    do_action('wpdatatables_before_render_table', $id);

    /** @var mixed $var1 */
    $wdtVar1 = $var1 !== '%%no_val%%' ? $var1 : $tableData->var1;
    /** @var mixed $var2 */
    $wdtVar2 = $var2 !== '%%no_val%%' ? $var2 : $tableData->var2;
    /** @var mixed $var3 */
    $wdtVar3 = $var3 !== '%%no_val%%' ? $var3 : $tableData->var3;

    /** @var mixed $export_file_name */
    $wdtExportFileName = $export_file_name !== '%%no_val%%' ? $export_file_name : '';

    /** @var mixed $table_view */
    if ($table_view == 'excel') {
        /** @var WPExcelDataTable $wpDataTable */
        $wpDataTable = new WPExcelDataTable();
    } else {
        /** @var WPDataTable $wpDataTable */
        $wpDataTable = new WPDataTable();
    }

    $wpDataTable->setWpId($id);

    $columnDataPrepared = $wpDataTable->prepareColumnData($tableData);

    try {
        $wpDataTable->fillFromData($tableData, $columnDataPrepared);
        $wpDataTable = apply_filters('wpdatatables_filter_initial_table_construct', $wpDataTable);

        $output = '';
        if ($tableData->show_title && $tableData->title) {
            $output .= apply_filters('wpdatatables_filter_table_title', (empty($tableData->title) ? '' : '<h2 class="wpdt-c" id="wdt-table-title-'. $id .'">' . $tableData->title . '</h2>'), $id);
        }
        $output .= $wpDataTable->generateTable();
    } catch (Exception $e) {
        $output = WDTTools::wdtShowError($e->getMessage());
    }
    $output = apply_filters('wpdatatables_filter_rendered_table', $output, $id);

    return $output;
}

/**
 * Handler for the SUM, AVG, MIN and MAX function shortcode
 * @param $atts
 * @param null $content
 * @param null $shortcode
 * @return string
 */
function wdtFuncsShortcodeHandler($atts, $content = null, $shortcode = null) {

    $attributes = shortcode_atts(array(
        'table_id' => 0,
        'col_id' => 0,
        'label' => null
    ), $atts);

    if (!$attributes['table_id']) {
        return __("Please provide table_id attribute for {$shortcode} shortcode!", 'wpdatatables');
    }
    if (!$attributes['col_id']) {
        return __("Please provide col_id attribute for {$shortcode} shortcode!", 'wpdatatables');
    }

    $wpDataTable = WPDataTable::loadWpDataTable($attributes['table_id'], null, true);

    $wpDataTableColumns = $wpDataTable->getColumns();
    if (empty($wpDataTableColumns)) {
        return __('wpDataTable with provided ID not found!', 'wpdatatables');
    }

    $column = WDTConfigController::loadSingleColumnFromDB($attributes['col_id']);

    $columnExists = $column['table_id'] === $attributes['table_id'];
    if ($columnExists === false) {
        return __("Column with ID {$attributes['col_id']} is not found in table with ID {$attributes['table_id']}!", 'wpdatatables');
    }
    if ($column['column_type'] !== 'int' && $column['column_type'] !== 'float' && $column['column_type'] !== 'formula') {
        return __('Provided column is not Integer or Float column type', 'wpdatatables');
    }

    if ($shortcode === 'wpdatatable_sum') {
        $function = 'sum';
        if (!isset($attributes['label'])) {
            $attributes['label'] = get_option('wdtSumFunctionsLabel') ? get_option('wdtSumFunctionsLabel') : '&#8721; =';
        }
    } else if ($shortcode === 'wpdatatable_avg') {
        $function = 'avg';
        if (!isset($attributes['label'])) {
            $attributes['label'] = get_option('wdtAvgFunctionsLabel') ? get_option('wdtAvgFunctionsLabel') : 'Avg =';
        }
    } else if ($shortcode === 'wpdatatable_min') {
        $function = 'min';
        if (!isset($attributes['label'])) {
            $attributes['label'] = get_option('wdtMinFunctionsLabel') ? get_option('wdtMinFunctionsLabel') : 'Min =';
        }
    } else {
        $function = 'max';
        if (!isset($attributes['label'])) {
            $attributes['label'] = get_option('wdtMaxFunctionsLabel') ? get_option('wdtMaxFunctionsLabel') : 'Max =';
        }
    }

    /** @noinspection PhpUnusedLocalVariableInspection */
    $funcResult = $wpDataTable->calcColumnFunction($column['orig_header'], $function);

    ob_start();
    include WDT_TEMPLATE_PATH . 'frontend/aggregate_functions.inc.php';
    $aggregateFunctionsHtml = ob_get_contents();
    ob_end_clean();

    return $aggregateFunctionsHtml;

}

function wdtRenderScriptStyleBlock() {
    $customJs = get_option('wdtCustomJs');
    $scriptBlockHtml = '';
    $styleBlockHtml = '';
    $wpDataTable = new WPDataTable();

    if ($customJs) {
        $scriptBlockHtml .= '<script type="text/javascript">' . stripslashes_deep($customJs) . '</script>';
    }
    $returnHtml = $scriptBlockHtml;

    // Color and font settings
    $wdtFontColorSettings = get_option('wdtFontColorSettings');
    if (!empty($wdtFontColorSettings)) {
        /** @noinspection PhpUnusedLocalVariableInspection */
        ob_start();
        include WDT_TEMPLATE_PATH . 'frontend/style_block.inc.php';
        $styleBlockHtml = ob_get_contents();
        ob_end_clean();
        $styleBlockHtml = apply_filters('wpdatatables_filter_style_block', $styleBlockHtml, $wpDataTable->getWpId());
    }

    $returnHtml .= $styleBlockHtml;
    return $returnHtml;
}

/**
 * Checks if current user can edit table on the front-end
 * @param $tableEditorRoles
 * @param $id
 * @return bool|mixed
 */
function wdtCurrentUserCanEdit($tableEditorRoles, $id) {
    $wpRoles = new WP_Roles();
    $userCanEdit = false;

    $tableEditorRoles = strtolower($tableEditorRoles);
    $editorRoles = array();

    if (empty($tableEditorRoles)) {
        $userCanEdit = true;
    } else {
        $editorRoles = explode(',', $tableEditorRoles);

        $allRoles = $wpRoles->get_names();

        $currentUser = wp_get_current_user();
        if (!($currentUser instanceof WP_User)) {
            return false;
        }

        foreach ($currentUser->roles as $userRole) {
            if (in_array(strtolower($allRoles[$userRole]), $editorRoles)) {
                $userCanEdit = true;
                break;
            }
        }
    }

    return apply_filters('wpdatatables_allow_edit_table', $userCanEdit, $editorRoles, $id);
}

/**
 * Removes all dangerous strings from query
 * @param $query
 * @return mixed|string
 */
function wdtSanitizeQuery($query) {
    $query = str_replace('DELETE', '', $query);
    $query = str_replace('DROP', '', $query);
    $query = str_replace('INSERT', '', $query);
    $query = stripslashes($query);

    return $query;
}

/**
 * Buttons for "insert wpDataTable" and "insert wpDataCharts" in WP MCE editor
 */
function wdtMCEButtons() {
    add_filter("mce_external_plugins", "wdtAddButtons");
    add_filter('mce_buttons', 'wdtRegisterButtons');
}

add_action('init', 'wdtMCEButtons');

/**
 * Function that add buttons for MCE editor
 * @param $pluginArray
 * @return mixed
 */
function wdtAddButtons($pluginArray) {
    $pluginArray['wpdatatables'] = WDT_JS_PATH . '/wpdatatables/wdt.mce.js';

    return $pluginArray;
}

/**
 * Function that register buttons for MCE editor
 * @param $buttons
 * @return mixed
 */
function wdtRegisterButtons($buttons) {
    array_push($buttons, 'wpdatatable', 'wpdatachart');

    return $buttons;
}

/**
 * Loads the translations
 */
function wdtLoadTextdomain() {
    load_plugin_textdomain('wpdatatables', false, dirname(plugin_basename(dirname(__FILE__))) . '/languages/' . get_locale() . '/');
}

/**
 * Workaround for NULLs in WP
 */
if ($wp_version < 4.4) {
    add_filter('query', 'wdtSupportNulls');

    function wdtSupportNulls($query) {
        $query = str_ireplace("'NULL'", "NULL", $query);
        $query = str_replace('null_str', 'null', $query);

        return $query;
    }
}

/**
 * Auto update function
 */
if ('' !== get_option('wdtPurchaseCode')) {

    global $wdt_plugin_slug;

    $filePath = plugin_basename(__FILE__);
    $filePathArr = explode('/', $filePath);
    $wdt_plugin_slug = $filePathArr[0] . '/wpdatatables.php';

    function wdtTransientUpdate($transient) {
        global $wdt_plugin_slug;

        // Remote version
        $remoteVersion = WDTTools::checkRemoteVersion();

        if (version_compare(WDT_CURRENT_VERSION, $remoteVersion, '<')) {
            $obj = new stdClass();
            $obj->slug = $wdt_plugin_slug;
            $obj->new_version = $remoteVersion;
            $obj->url = 'http://wpdatatables.com/verified-download.php?purchase_code=' . get_option('wdtPurchaseCode');
            $obj->package = 'http://wpdatatables.com/verified-download.php?purchase_code=' . get_option('wdtPurchaseCode');
            $transient->response[$wdt_plugin_slug] = $obj;
        }

        return $transient;
    }

    add_filter('pre_set_site_transient_update_plugins', 'wdtTransientUpdate');

    function wdtPluginsApi($false, $action, $arg) {
        global $wdt_plugin_slug;

        if (property_exists($arg, 'slug') && ($arg->slug === $wdt_plugin_slug || $arg->slug == 'wpdatatables.php')) {
            $information = WDTTools::checkRemoteInfo();

            return $information;
        }

        return false;
    }

    add_filter('plugins_api', 'wdtPluginsApi', 10, 3);

}

/**
 * Optional Visual Composer integration
 */
if (function_exists('vc_map')) {

    /**
     * Get all tables non-paged for the Visual Composer integration
     */
    function wdtGetAllTablesVC() {
        global $wpdb;
        $query = "SELECT id, title FROM {$wpdb->prefix}wpdatatables ORDER BY id";

        $allTables = $wpdb->get_results($query, ARRAY_A);

        $returnTables = array(__('Choose a table', 'wpdatatables') => '');
        foreach ($allTables as $table) {
            $returnTables[$table['title']] = $table['id'];
        }

        return $returnTables;
    }

    /**
     * Get all charts non-paged for the Visual Composer integration
     */
    function wdtGetAllChartsVC() {
        global $wpdb;
        $query = "SELECT id, title FROM {$wpdb->prefix}wpdatacharts ORDER BY id";

        $all_charts = $wpdb->get_results($query, ARRAY_A);

        $returnTables = array();
        foreach ($all_charts as $chart) {
            $returnTables[$chart['title']] = $chart['id'];
        }

        return $returnTables;
    }

    /**
     * Insert wpDataTable button
     */
    vc_map(
        array(
            'name' => 'wpDataTable',
            'base' => 'wpdatatable',
            'description' => __('Interactive Responsive Table', 'wpdatatable'),
            'category' => __('Content'),
            'icon' => plugin_dir_url(dirname(__FILE__)) . 'assets/img/vc-icon.png',
            'params' => array(
                array(
                    'type' => 'dropdown',
                    'class' => '',
                    'heading' => __('wpDataTable', 'wpdatatables'),
                    'admin_label' => true,
                    'param_name' => 'id',
                    'value' => wdtGetAllTablesVC(),
                    'description' => __('Choose the wpDataTable from a dropdown', 'wpdatatables')
                ),
                array(
                    'type' => 'dropdown',
                    'class' => '',
                    'heading' => __('Table view', 'wpdatatables'),
                    'admin_label' => true,
                    'param_name' => 'table_view',
                    'value' => array(
                        __('Regular wpDataTable', 'wpdatatables') => 'regular',
                        __('Excel-like table', 'wpdatatables') => 'excel'
                    )
                ),
                array(
                    'type' => 'textfield',
                    'heading' => __('Variable placeholder #1', 'wpdatatables'),
                    'param_name' => 'var1',
                    'value' => '',
                    'group' => __('Variables', 'wpdatatables'),
                    'description' => __('If you used the VAR1 placeholder you can assign a value to it here', 'wpdatatables')
                ),
                array(
                    'type' => 'textfield',
                    'heading' => __('Variable placeholder #2', 'wpdatatables'),
                    'param_name' => 'var2',
                    'value' => '',
                    'group' => __('Variables', 'wpdatatables'),
                    'description' => __('If you used the VAR2 placeholder you can assign a value to it here', 'wpdatatables')
                ),
                array(
                    'type' => 'textfield',
                    'heading' => __('Variable placeholder #3', 'wpdatatables'),
                    'param_name' => 'var3',
                    'value' => '',
                    'group' => __('Variables', 'wpdatatables'),
                    'description' => __('If you used the VAR3 placeholder you can assign a value to it here', 'wpdatatables')
                )
            )
        )
    );

    /**
     * Insert wpDataChart button
     */
    vc_map(
        array(
            'name' => 'wpDataChart',
            'base' => 'wpdatachart',
            'description' => __('Google or Highcharts chart based on a wpDataTable', 'wpdatatable'),
            'category' => __('Content'),
            'icon' => plugin_dir_url(dirname(__FILE__)) . 'assets/img/vc-charts-icon.png',
            "params" => array(
                array(
                    "type" => "dropdown",
                    "class" => "",
                    "heading" => __('wpDataChart', 'wpdatatables'),
                    "param_name" => "id",
                    'admin_label' => true,
                    "value" => wdtGetAllChartsVC(),
                    "description" => __("Choose one of wpDataCharts from the list", 'wpdatatables')
                )
            )
        )
    );

}