Completed
Push — beta ( 90f176...19e68d )
by
unknown
09:39
created

src/Core.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace KMM\Flattable;
4
5
class Core
6
{
7
    private $plugin_dir;
8
9 6
    public function __construct()
10
    {
11
        global $wpdb;
12 6
        $this->wpdb = $wpdb;
13 6
        $this->plugin_dir = plugin_dir_url(__FILE__) . '../';
14 6
        $this->add_filters();
15
    }
16
17 6
    private function add_filters()
18
    {
19 6
        add_action('save_post', [$this, 'save_post'], 100, 3);
20 6
        add_action('delete_post', [$this, 'delete_post'], 100, 3);
21
22 6
        add_action('krn_flattable_check_table', [$this, 'checkTable'], 10, 2);
23 6
        add_action('krn_flattable_publish', [$this, 'manualPublish'], 10);
24
25 6
        add_action('init', [$this, 'init'], 30);
26
27
        //DEMO
28
    }
29
30
    public function init()
31
    {
32
        $post_types = get_post_types();
33
        foreach ($post_types as $type) {
34
            add_action('rest_insert_' . $type, [$this, 'rest_update'], 10, 3);
35
        }
36
    }
37
38 1
    public function rest_update($postObj, $request, $update)
39
    {
40
        /*
41
        * class-wp-rest-attachments-controller.php calls the action with $attachment as array, and also calls parent::update_item(),
42
        *  -> parent class is class-wp-rest-posts-controller.php, that also calls the action, but with $attachment as type WP_Post
43
        */
44 1
        if (! $postObj instanceof \WP_Post) {
45 1
            return;
46
        }
47
        $_POST['post_type'] = $postObj->post_type;
48
        // save all the data in an anonymous function
49
        $trigger_func = function ($response, $handler, $request) use ($postObj, $update) {
50
            // call the internal save_post after all postmeta is written
51
            $this->save_post($postObj->ID, $postObj, $update);
52
53
            return $response;
54
        };
55
        // add a filter => after all callbacks are called (after update_additional_fields_for_object())
56
        add_filter('rest_request_after_callbacks', $trigger_func, 10, 3);
57
    }
58
59
    public function manualPublish($postId)
60
    {
61
        $postObj = get_post($postId);
62
        $_POST['post_type'] = $postObj->post_type;
63
        $this->save_post($postId, $postObj, true);
64
    }
65
66 2
    public function delete_post($postId, $state = false)
67
    {
68 2
        $postObj = get_post($postId);
69 2
        $table_name = $this->wpdb->prefix . 'flattable_' . $postObj->post_type;
70
        //check if flattable is enabled for this post type.
71 2
        $enabled = apply_filters('krn_flattable_enabled_' . $postObj->post_type, $state, $postObj, $postObj);
72 2
        if ($enabled) {
73 1
            do_action('krn_flattable_pre_delete_' . $postObj->post_type, $postObj);
74 1
            $customCols = apply_filters('krn_flattable_columns_' . $postObj->post_type, [], $postObj);
75
            //check if there are any other than required columns, we dont need an "empty" table
76 1
            if (empty($customCols)) {
77
                return;
78
            }
79 1
            $sql = 'delete from ' . $table_name . ' where post_id=' . $postId;
80 1
            $this->wpdb->query($sql);
81
        }
82
    }
83
84 5
    public function save_post($postId, $postObject, $update, $state = false)
85
    {
86 5
        $postType = false;
87 5
        if (! $postObject) {
88
            //postObject not set, check if $_POST has post_type
89 1
            if (isset($_POST['post_type'])) {
90 1
                $postType = $_POST['post_type'];
91
            }
92
        } else {
93
            //PostObject set
94 4
            $postType = $postObject->post_type;
95
        }
96
        //Neither $postObject nor $_POST[post_type] set return here.
97 5
        if (! $postType) {
98 1
            return;
99
        }
100
101 4
        $table_name = $this->wpdb->prefix . 'flattable_' . $postType;
102
        //check if flattable is enabled for this post type.
103 4
        $enabled = apply_filters('krn_flattable_enabled_' . $postType, $state, $postObject, $postObject);
104 4
        if ($enabled) {
105
            //We are in flattable enabled mode.
106
            //get a list of columns.
107
            $defaultCols = [
108 1
                ['column' => 'post_id', 'type' => 'int(12)'],
109
                ['column' => 'post_type', 'type' => 'varchar(100)'],
110
            ];
111 1
            $customCols = apply_filters('krn_flattable_columns_' . $postType, [], $postObject);
112 1
            $columns = array_merge($defaultCols, $customCols);
113 1
            do_action('krn_flattable_pre_write_' . $postType, $columns, $postObject);
114
            //check if there are any other than required columns, we dont need an "empty" table
115 1
            if (empty($customCols)) {
116
                return;
117
            }
118
            //check if table exists, and if table has atleast required columns
119 1
            if ($this->checkTable($postType, $columns)) {
120 1
                $db_cols = [];
121 1
                $assoc_db = [];
122 1
                foreach ($columns as $column) {
123 1
                    $db_cols[] = $column['column'];
124 1
                    $assoc_db[$column['column']] = $column;
125
                }
126
127 1
                $finalFields = apply_filters('krn_flattable_values_' . $postType, [], $postObject);
128
129 1
                $checkRow = $this->wpdb->get_row("select post_id from $table_name where post_id=" . $postId);
130
                //if we have already a published record, update it
131 1
                $update = true;
132 1
                if (! $checkRow) {
133 1
                    $update = false;
134
                }
135
136 1
                if (! $update) {
137
                    //INSERT
138 1
                    $updateCols = ['post_type', 'post_id'];
139 1
                    $updateVals = ["'" . $postType . "'", $postId];
140 1
                    $updateInserValues = [];
141 1
                    foreach ($finalFields as $key => $value) {
142 1
                        $updateCols[] = $key;
143 1
                        $updateVals[] = $assoc_db[$key]['printf'];
144 1
                        $updateInserValues[] = $value;
145
                    }
146 1
                    $sql = " insert into $table_name (" . join(',', $updateCols) . ') VALUES(' . join(',', $updateVals) . ')';
147 1
                    $query = call_user_func_array([$this->wpdb, 'prepare'], array_merge([$sql], $updateInserValues));
148 1
                    $this->wpdb->query($query);
149
                } else {
150
                    //UPDATE
151
152
                    //$v = get_field('field_58512668ff1d2', $postId);
153
                    //echo "<pre>";
154
                    //var_dump($v);
155
                    //exit;
156
                    $updateCols = [];
157
                    $updateVals = [];
158
                    foreach ($finalFields as $key => $value) {
159
                        $updateCols[] = $key . ' = ' . $assoc_db[$key]['printf'];
160
                        $updateVals[] = $value;
161
                    }
162
                    $updateVals[] = $postId;
163
164
                    $sql = "update $table_name SET " . join(',', $updateCols) . ' WHERE post_id = %d';
165
                    $query = call_user_func_array([$this->wpdb, 'prepare'], array_merge([$sql], $updateVals));
166
                    $this->wpdb->query($query);
167
                }
168
169 1
                do_action('krn_flattable_post_write_' . $postType, $postObject);
170
            }
171
        }
172
    }
173
174 2
    public function checkTable($postType, $columns)
175
    {
176 2
        $table_name = $this->wpdb->prefix . 'flattable_' . $postType;
177
178 2
        $charset_collate = $this->wpdb->get_charset_collate();
179
180 2
        $sql_columns = [];
181 2
        foreach ($columns as $column) {
182 2
            $sql_columns[] = $column['column'] . ' ' . $column['type'];
183
        }
184
185 2
        $column_string = join(',', $sql_columns);
186
187 2
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
188
            id int(12) NOT NULL AUTO_INCREMENT,
189 2
            $column_string
190
            ,PRIMARY KEY (id)
191 2
        ) $charset_collate;";
192
193 2
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
194 2
        $a = dbDelta($sql);
195
196
        //Check columns
197 2
        foreach ($columns as $column) {
198 2
            $row = $this->wpdb->get_results("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
199 2
                WHERE table_name = '$table_name' AND column_name = '" . $column['column'] . "'");
200
201 2
            if (empty($row)) {
202 2
                if(!defined("WP_DEBUG") || !WP_DEBUG) {
0 ignored issues
show
The constant KMM\Flattable\WP_DEBUG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
203 2
                    $this->wpdb->suppress_errors(true);
204 2
                }
205
                $this->wpdb->query("ALTER TABLE $table_name ADD " . $column['column'] . ' ' . $column['type']);
206
                $this->wpdb->suppress_errors(false);
207
            }
208 2
        }
209
        return true;
210
    }
211
}
212