Completed
Push — beta ( b93f70...3db4e8 )
by Helmut
02:38
created

Core::storeTimeshift()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/*
3
 *
4
 *
5
 * inspired by https://github.com/adamsilverstein/wp-post-meta-revisions/blob/master/wp-post-meta-revisions.php
6
 * many thx @adamsilverstein
7
 *
8
 */
9
10
namespace KMM\Timeshift;
11
12
class Core
13
{
14
    private $plugin_dir;
15
    private $last_author = false;
16
    private $timeshift_cached_meta;
17
18 12
    public function __construct($i18n)
19
    {
20
        global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
21 12
        $this->i18n = $i18n;
0 ignored issues
show
Bug introduced by
The property i18n does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
22 12
        $this->wpdb = $wpdb;
0 ignored issues
show
Bug introduced by
The property wpdb does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
23 12
        $this->plugin_dir = plugin_dir_url(__FILE__) . '../';
24 12
        $this->add_filters();
25 12
        $this->add_actions();
26 12
        $this->add_metabox();
27
        //Disable WP's own revision system
28 12
        remove_post_type_support('post', 'revisions');
29
    }
30
31 2
    public function hasTimeshifts($post_id)
32
    {
33 2
        $post_type = get_post_type($post_id);
34 2
        $table_name = $this->wpdb->prefix . 'timeshift_' . $post_type;
35 2
        $this->checkTable($post_type);
36 2
        $sql = "select count(1) as amount from $table_name where post_id=" . $post_id;
37 2
        $r = $this->wpdb->get_results($sql);
38
39 2
        if ($r && count($r) == 1) {
40 1
            if (intval($r[0]->amount) > 0) {
41 1
                return true;
42
            }
43
        }
44
45 1
        return false;
46
    }
47
48 12
    public function timeshiftVisible()
49
    {
50 12
        $check = apply_filters('krn_timeshift_visible', true);
51
52 12
        return $check;
53
    }
54
55 12
    public function add_metabox()
0 ignored issues
show
Coding Style introduced by
add_metabox uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
56
    {
57 12
        $cl = $this;
58 12
        if (! $this->timeshiftVisible()) {
59
            return;
60
        }
61 12
        if (! isset($_GET['post']) || ! $this->hasTimeshifts($_GET['post'])) {
62 12
            return;
63
        }
64
        add_action('add_meta_boxes', function () use ($cl) {
65
            add_meta_box('krn-timeshift', __('Timeshift', 'kmm-timeshift'), [$cl, 'timeshift_metabox'], null, 'normal', 'core');
66
        });
67
    }
68
69 2
    public function timeshift_metabox()
0 ignored issues
show
Coding Style introduced by
timeshift_metabox uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
70
    {
71
        global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
72 2
        if (! isset($_GET['post'])) {
73 1
            return;
74
        }
75 1
        $prod_post = get_post($_GET['post']);
76 1
        $table_name = $this->wpdb->prefix . 'timeshift_' . $post->post_type;
77 1
        $sql = "select * from $table_name where post_id=" . $post->ID . ' order by create_date desc';
78
79 1
        $last_editor = get_post_meta($prod_post->ID, '_edit_last', true);
80 1
        $row = $this->wpdb->get_results($sql);
81 1
        echo '<table class="widefat fixed">';
82 1
        echo '<thead>';
83 1
        echo '<tr>';
84 1
        echo '<th width=30></th>';
85 1
        echo '<th width="40%" id="columnname" class="manage-column column-columnname"  scope="col">' . __('Title', 'kmm-timeshift') . '</th>';
86 1
        echo '<th width="30%" id="columnname" class="manage-column column-columnname"  scope="col">' . __('Snapshot Date', 'kmm-timeshift') . '</th>';
87 1
        echo '<th width="10%" id="columnname" class="manage-column column-columnname"  scope="col">' . __('Author', 'kmm-timeshift') . '</th>';
88 1
        echo '<th width="10%" id="columnname" class="manage-column column-columnname"  scope="col">' . __('Actions', 'kmm-timeshift') . '</th>';
89 1
        echo '</tr>';
90 1
        echo ' </thead>';
91 1
        echo '<tbody>';
92 1
        echo '<tr style="font-weight: 800;">';
93 1
        echo '<td>' . get_avatar($last_editor, 30) . '</td>';
94 1
        echo '<td>' . $prod_post->post_title . '</td>';
95 1
        echo '<td>' . $prod_post->post_date . '</td>';
96 1
        echo '<td>' . get_the_author_meta('display_name', $last_editor) . '</td>';
97 1
        echo "<td><a href='post.php?post=" . $_GET['post'] . "&action=edit'><span class='dashicons dashicons-admin-site'></span></A></td>";
98 1
        echo '</tr>';
99
100 1
        foreach ($row as $rev) {
101
            $timeshift = unserialize($rev->post_payload);
102
            $style = '';
103
            if (isset($_GET['timeshift']) && $_GET['timeshift'] == $rev->id) {
104
                $style = 'style="font-style:italic;background-color: lightblue;"';
105
            }
106
            echo '<tr ' . $style . '>';
107
            echo '<td>' . get_avatar($timeshift->meta['_edit_last'][0], 30) . '</td>';
108
            echo '<td>' . $timeshift->post->post_title . '</td>';
109
            echo '<td>' . $rev->create_date . '</td>';
110
            echo '<td>' . get_the_author_meta('display_name', $timeshift->meta['_edit_last'][0]) . '</td>';
111
            echo "<td><a href='post.php?post=" . $_GET['post'] . '&action=edit&timeshift=' . $rev->id . "'><span class='dashicons dashicons-backup'></span></a></td>";
112
            echo '</tr>';
113
        }
114 1
        echo '</tbody>';
115 1
        echo '</table>';
116
    }
117
118 12
    public function add_filters()
119
    {
120
        // When revisioned post meta has changed, trigger a revision save.
121
        //add_filter('wp_save_post_revision_post_has_changed', [$this, '_wp_check_revisioned_meta_fields_have_changed'], 10, 3);
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
122
123 12
        add_filter('get_post_metadata', [$this, 'inject_metadata_timeshift'], 1, 4);
124 12
        add_filter('update_post_metadata', [$this, 'update_post_metadata'], 1, 5);
125
    }
126
127 1
    public function update_post_metadata($check, int $object_id, string $meta_key, $meta_value, $prev_value)
0 ignored issues
show
Unused Code introduced by
The parameter $meta_value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $prev_value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
128
    {
129 1
        if ($meta_key == '_edit_last') {
130 1
            $lo = get_post_meta($object_id, '_edit_last', true);
131 1
            $this->last_author = $lo;
132
        }
133
134 1
        return null;
135
    }
136
137 3
    public function inject_metadata_timeshift($value, $post_id, $key, $single)
0 ignored issues
show
Coding Style introduced by
inject_metadata_timeshift uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
138
    {
139 3
        if (! isset($_GET['timeshift'])) {
140 3
            return;
141
        }
142
        //Load timeshift
143
        if (! $this->timeshift_cached_meta) {
144
            $post_type = get_post_type($post_id);
145
            $table_name = $this->wpdb->prefix . 'timeshift_' . $post_type;
146
            $sql = "select * from $table_name where id=" . intval($_GET['timeshift']);
147
            $r = $this->wpdb->get_results($sql);
148 View Code Duplication
            if ($r && count($r) == 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149
                $payload = unserialize($r[0]->post_payload);
150
                $this->timeshift_cached_meta = $payload->meta;
151
            }
152
        }
153
        if ($this->timeshift_cached_meta && isset($this->timeshift_cached_meta[$key])) {
154
            return $this->timeshift_cached_meta[$key];
155
        }
156
        if ($single) {
157
            return null;
158
        }
159
160
        return [];
161
    }
162
163 2
    public function inject_timeshift($p)
0 ignored issues
show
Unused Code introduced by
The parameter $p is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
inject_timeshift uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
164
    {
165
        global $post;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
166 2
        if (! isset($_GET['timeshift'])) {
167 1
            return;
168
        }
169
        //Load timeshift
170 1
        $table_name = $this->wpdb->prefix . 'timeshift_' . $post->post_type;
171 1
        $sql = "select * from $table_name where id=" . intval($_GET['timeshift']);
172 1
        $r = $this->wpdb->get_results($sql);
173 1 View Code Duplication
        if ($r && count($r) == 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
            $payload = unserialize($r[0]->post_payload);
175
            $post = $payload->post;
176
        }
177
    }
178
179 12
    public function add_actions()
0 ignored issues
show
Coding Style introduced by
add_actions uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
180
    {
181 12
        add_action('edit_form_top', [$this, 'inject_timeshift'], 1, 1);
182 12
        add_action('pre_post_update', [$this, 'pre_post_update'], 2, 1);
183 12
        add_action('admin_notices', function () {
184
            if (isset($_GET['timeshift']) && $_GET['timeshift']) {
185
                echo '<div class="notice notice-warning is-dismissible">
186
                         <p style="font-weight: 800; color: red">' . __('You are editing a historical version! if you save or publish, this will replace the current live one', 'kmm-timeshift') . '</p>
187
                                  </div>';
188
            }
189 12
        });
190 12
        add_action('krn_timeshift_create_snapshot', [$this, 'create_snapshot'], 1, 1);
191
    }
192
193 4
    public function checkTable($postType)
194
    {
195 4
        $table_name = $this->wpdb->prefix . 'timeshift_' . $postType;
196
197 4
        $charset_collate = $this->wpdb->get_charset_collate();
198
199 4
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
200
		              id int(12) NOT NULL AUTO_INCREMENT,
201
                  post_id int(12) NOT NULL,
202
								  create_date datetime default CURRENT_TIMESTAMP,
203
									post_payload TEXT
204
		              ,PRIMARY KEY  (id)
205 4
	        ) $charset_collate;";
206
207 4
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
208 4
        $a = dbDelta($sql);
0 ignored issues
show
Unused Code introduced by
$a is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
209
210 4
        return true;
211
    }
212
213 2
    public function storeTimeshift($timeshift)
214
    {
215 2
        $table_name = $this->wpdb->prefix . 'timeshift_' . $timeshift->post->post_type;
216 2
        $sql = "insert into $table_name (post_id, post_payload) VALUES(%d, '%s')";
217 2
        $query = $this->wpdb->prepare($sql, $timeshift->post->ID, serialize($timeshift));
218 2
        $this->wpdb->query($query);
219
    }
220
221
    public function create_snapshot($postID)
222
    {
223
        $this->pre_post_update($postID);
224
    }
225
226 1
    public function pre_post_update(int $post_ID, array $data = null)
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
227
    {
228 1
        if (wp_is_post_autosave($post_ID)) {
229
            return;
230
        }
231 1
        if (get_post_status($post_ID) == 'auto-draft') {
232
            return;
233
        }
234 1
        $post_type = get_post_type($post_ID);
235 1
        $this->checkTable($post_type);
236
237 1
        $mdata = get_metadata('post', $post_ID);
238 1
        $post = get_post($post_ID);
239
240 1
        if ($this->last_author) {
241
            $mdata['_edit_last'][0] = $this->last_author;
242
        }
243 1
        unset($mdata['_edit_lock']);
244
245 1
        $timeshift = (object) ['post' => $post, 'meta' => $mdata];
246 1
        $this->storeTimeshift($timeshift);
247
    }
248
}
249