GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#1025)
by Tom
03:09
created

Backup_Status::is_running()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 2
b 0
f 0
nc 4
nop 0
dl 0
loc 21
rs 8.7624
1
<?php
2
3
namespace HM\BackUpWordPress;
4
5
use Symfony\Component\Filesystem\LockHandler;
6
7
/**
8
 * Manages status and progress of a backup
9
 */
10
class Backup_Status {
11
12
	/**
13
	 * The filename for the backup file we are the tracking status of
14
	 *
15
	 * @var string
16
	 */
17
	private $filename = '';
18
19
	/**
20
	 * [$lock_handler description]
21
	 *
22
	 * @var LockHandler
23
	 */
24
	private $lock_handler = '';
25
26
	private $callback;
27
28
	/**
29
	 * @param string $id The unique id for the backup job
30
	 */
31
	public function __construct( $id ) {
32
		$this->id = (string) $id;
0 ignored issues
show
Bug introduced by
The property id 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...
33
		$this->cleanup_after_crash();
34
	}
35
36
	/**
37
	 * Start the tracking a backup process.
38
	 *
39
	 * This creates a backup running file and issues a file lock. This prevents duplicate
40
	 * instances of this backup process running concurrently and allows us to detect if
41
	 * the PHP thread running the process is killed as that will clear the lock.
42
	 *
43
	 * @param  string $backup_filename The filename for the backup file that we're tracking
44
	 * @param  string $status_message  The initial status for the backup process
45
	 *
46
	 * @return boolean                  Whether the backup process was success marked as started
47
	 */
48
	public function start( $backup_filename, $status_message ) {
49
		$this->filename = $backup_filename;
50
51
		// Clear any errors from previous backup runs
52
		Notices::get_instance()->clear_notice_context( 'backup_failed' );
53
54
		add_action( 'shutdown', array( $this, 'catch_fatals' ), 10 );
55
56
		if ( ! defined( 'HMBKP_DISABLE_FILE_LOCKING' ) || ! HMBKP_DISABLE_FILE_LOCKING ) {
57
			$this->lock_handler = new LockHandler( basename( $this->get_status_filepath() ), Path::get_path() );
58
59
			if ( ! $this->lock_handler->lock() || $this->get_status() ) {
60
			    return false;
61
			}
62
		}
63
64
		return $this->set_status( $status_message );
65
	}
66
67
	/**
68
	 * Mark a backup process as finished.
69
	 *
70
	 * This removes the file lock and deletes the running file.
71
	 */
72
	public function finish() {
73
74
		if ( ! defined( 'HMBKP_DISABLE_FILE_LOCKING' ) || ! HMBKP_DISABLE_FILE_LOCKING ) {
75
			if ( isset( $this->lock_handler ) && is_a( $this->lock_handler, 'LockHandler' ) ) {
76
				$this->lock_handler->release();
77
			}
78
		}
79
80
		// Delete the backup running file
81
		if ( file_exists( $this->get_status_filepath() ) ) {
82
			return unlink( $this->get_status_filepath() );
83
		}
84
85
		return false;
86
	}
87
88
	/**
89
	 * Check if the backup has been started by checking if the running file
90
	 * exists.
91
	 *
92
	 * @return boolean Whether the backup process has been started
93
	 */
94
	public function is_started() {
95
		return (bool) file_exists( $this->get_status_filepath() );
96
	}
97
98
	public function is_running() {
99
100
		if ( ! $this->is_started() ) {
101
			return false;
102
		}
103
104
		if ( ! defined( 'HMBKP_DISABLE_FILE_LOCKING' ) || ! HMBKP_DISABLE_FILE_LOCKING ) {
105
106
			// If we're in the same thread then we know we must be running if the running file exists
107
			if ( is_a( $this->lock_handler, 'LockHandler' ) ) {
108
				return $this->is_started();
109
			}
110
111
			$lock_handler = new LockHandler( basename( $this->get_status_filepath() ), Path::get_path() );
112
113
			return ! $lock_handler->lock();
114
		}
115
116
		// If the backup is started and we don't support file locks then we have to assume we're still running
117
		return true;
118
	}
119
120
	/**
121
	 * If the running file exists but isn't locked then the thread that
122
	 * the backup process is running in must have been killed.
123
	 *
124
	 * You should only be running this command from a separate thread
125
	 *
126
	 * @return boolean Whether the backup process has crashed or not
127
	 */
128
	public function has_crashed() {
129
		return ( $this->is_started() && ! $this->is_running() );
130
	}
131
132
	/**
133
	 * Handle a process that's previouly crashed.
134
	 *
135
	 * Delete the partially created backup if it exists and then run the standard
136
	 * cleanup tasks and set an error message for the user.
137
	 *
138
	 * @return bool Whether the crash was handled or not
139
	 */
140
	public function cleanup_after_crash() {
141
142
		if ( ! $this->has_crashed() ) {
143
			return false;
144
		}
145
146 View Code Duplication
		if ( file_exists( trailingslashit( Path::get_path() ) . $this->get_backup_filename() ) ) {
147
			unlink( trailingslashit( Path::get_path() ) . $this->get_backup_filename() );
148
		}
149
150
		$this->finish();
151
152
		// If we already have a fatal error then let's not stomp on it.
153
		if ( Notices::get_instance()->get_notices( 'backup_failed' ) ) {
154
			$message = __( 'Your last backup failed. The backup process was killed before it could complete. Please contact your host for assistance or try excluding more files.', 'backupwordpress' );
155
			Notices::get_instance()->set_notices( 'backup_failed', array( $message ), true );
156
		}
157
158
		return true;
159
160
	}
161
162
	/**
163
	 * Catch fatal errors and react accordingly.
164
	 *
165
	 * Hooked into the shutdown action. If we've shutdown because of a Fatal error
166
	 * then we cleanup and set an error message for the user.
167
	 */
168
	public function catch_fatals() {
169
170
		$error = error_get_last();
171
172
		if ( empty( $error ) ) {
173
			return;
174
		}
175
176
		if ( ! isset( $error['type'] ) || ! defined( 'E_ERROR' ) || E_ERROR !== $error['type'] ) {
177
			return;
178
		}
179
180 View Code Duplication
		if ( file_exists( trailingslashit( Path::get_path() ) . $this->get_backup_filename() ) ) {
181
			unlink( trailingslashit( Path::get_path() ) . $this->get_backup_filename() );
182
		}
183
184
		$this->finish();
185
186
		$message = sprintf( __( 'Your last backup failed. The backup process encountered an error before it could complete. The error was %s. Please contact your host for assistance or try excluding more files.', 'backupwordpress' ), '<code>' . esc_html( $error['message'] ) . '</code>' );
187
		Notices::get_instance()->set_notices( 'backup_failed', array( $message ), true );
188
189
	}
190
191
	/**
192
	 * Get the filepath for the backup file we're tracking
193
	 *
194
	 * @return string The path to the backup file
195
	 */
196
	public function get_backup_filename() {
197
198
		if ( $this->is_started() ) {
199
			$status = json_decode( file_get_contents( $this->get_status_filepath() ) );
200
201
			if ( ! empty( $status->filename ) ) {
202
				$this->filename = $status->filename;
203
			}
204
		}
205
206
		return $this->filename;
207
	}
208
209
	/**
210
	 * Get the status of the running backup.
211
	 *
212
	 * @return string
213
	 */
214
	public function get_status() {
215
216
		if ( ! file_exists( $this->get_status_filepath() ) ) {
217
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by HM\BackUpWordPress\Backup_Status::get_status of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
218
		}
219
220
		$status = json_decode( file_get_contents( $this->get_status_filepath() ) );
221
222
		if ( ! empty( $status->status ) ) {
223
			return $status->status;
224
		}
225
226
		return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by HM\BackUpWordPress\Backup_Status::get_status of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
227
228
	}
229
230
	/**
231
	 * Set the status of the running backup
232
	 *
233
	 * @param string $message
234
	 *
235
	 * @return null
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
236
	 */
237
	public function set_status( $message ) {
238
239
		if ( is_callable( $this->callback ) ) {
240
			call_user_func( $this->callback, $message );
241
		}
242
243
		// If start hasn't been called yet then we wont' have a backup filename
244
		if ( ! $this->filename ) {
245
			return false;
246
		}
247
248
		$status = json_encode( (object) array(
249
			'filename' => $this->filename,
250
			'started'  => $this->get_start_time(),
251
			'status'   => $message,
252
		) );
253
254
		return (bool) file_put_contents( $this->get_status_filepath(), $status );
255
256
	}
257
258
	/**
259
	 * Get the time that the current running backup was started
260
	 *
261
	 * @return int $timestamp
262
	 */
263
	public function get_start_time() {
264
265
		if ( ! file_exists( $this->get_status_filepath() ) ) {
266
			return 0;
267
		}
268
269
		$status = json_decode( file_get_contents( $this->get_status_filepath() ) );
270
271
		if ( ! empty( $status->started ) && (int) (string) $status->started === $status->started ) {
272
			return $status->started;
273
		}
274
275
		return time();
276
277
	}
278
279
	/**
280
	 * Get the path to the backup running file that stores the running backup status
281
	 *
282
	 * @return string
283
	 */
284
	public function get_status_filepath() {
285
		return Path::get_path() . '/.backup-' . $this->id . '-running';
286
	}
287
288
	public function set_status_callback( $callback ) {
289
		$this->callback = $callback;
290
	}
291
}
292