Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
4.90% covered (danger)
4.90%
7 / 143
0.00% covered (danger)
0.00%
0 / 6
CRAP
n/a
0 / 0
Safeguard\search_plugin_info
63.64% covered (warning)
63.64%
7 / 11
0.00% covered (danger)
0.00%
0 / 1
4.77
Safeguard\request_check_plugin
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
182
Safeguard\uncompress_package
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
Safeguard\clean_folder
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
Safeguard\get_plugin_data_from_package
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
462
Safeguard\log_safeguard_error
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * Safeguard utilities file.
4 *
5 * @package safeguard
6 */
7
8namespace Safeguard;
9
10use Automattic\Jetpack\Connection\Client as Jetpack_Client;
11use Jetpack_Options;
12use RecursiveDirectoryIterator;
13use RecursiveIteratorIterator;
14use WP_Error;
15use WPCOMSH_Log;
16use ZipArchive;
17
18const DOTORG_API_HOST             = 'https://api.wordpress.org';
19const DOTORG_PLUGINS_HOST         = DOTORG_API_HOST . '/plugins';
20const DOTORG_PLUGIN_INFO_ENDPOINT = DOTORG_PLUGINS_HOST . '/info/1.0/';
21
22/**
23 * Perform a request to the .org API to get information about the given plugin.
24 *
25 * @param  string $slug Plugin slug.
26 * @return array|WP_Error
27 */
28function search_plugin_info( $slug ) {
29    $request  = array(
30        'action'  => 'plugin_information',
31        'timeout' => 15,
32    );
33    $response = wp_remote_post( DOTORG_PLUGIN_INFO_ENDPOINT . $slug, array( 'body' => $request ) );
34    if ( is_wp_error( $response ) ) {
35        return $response;
36    }
37
38    $plugin_info = maybe_unserialize( wp_remote_retrieve_body( $response ) );
39
40    if ( $plugin_info && property_exists( $plugin_info, 'error' ) ) {
41        return new WP_Error( 'search_plugin_error', $plugin_info->error );
42    }
43
44    return $plugin_info;
45}
46
47/**
48 * Perform a request to WP COM API endpoint to check the plugin.
49 *
50 * @param string $slug Plugin slug.
51 * @param array  $body Array data with needed information to check the plugin.
52 * @return WP_Error|array Error instance if something fails, the response if plugin is accepted.
53 */
54function request_check_plugin( $slug, $body ) {
55    $wpcom_blog_id = Jetpack_Options::get_option( 'id' );
56    $endpoint      = "/sites/{$wpcom_blog_id}/plugins/{$slug}/check";
57
58    $request = Jetpack_Client::wpcom_json_api_request_as_blog(
59        $endpoint,
60        Jetpack_Client::WPCOM_JSON_API_VERSION,
61        array( 'method' => 'POST' ),
62        $body
63    );
64
65    if ( is_wp_error( $request ) ) {
66        return $request;
67    }
68
69    if ( ! is_array( $request ) || ! isset( $request['body'] ) ) {
70        return new WP_Error(
71            'failed_to_fetch_data',
72            esc_html__( 'Unable to fetch the requested data.', 'wpcomsh' ),
73            array( 'status' => 500 )
74        );
75    }
76
77    $response_code = wp_remote_retrieve_response_code( $request );
78    $response      = json_decode( wp_remote_retrieve_body( $request ), true ) ?? array();
79
80    $error_data = array(
81        'wpcom_blog_id' => $wpcom_blog_id,
82        'endpoint'      => $endpoint,
83        'response'      => $response,
84    );
85
86    if ( $response_code === 404 ) {
87        $error_data['response-code'] = 404;
88        return new WP_Error( 'checking_plugin_failed', 'Request route not found.', $error_data );
89    }
90
91    // It should be changed passing the `reject` action.
92    if ( $response_code === 400 ) {
93        $error_data['response-code'] = 400;
94        return new WP_Error( 'unaccepted_plugin', $response['message'] ?? '', $error_data );
95    }
96
97    if ( empty( $response ) || ! $response_code || $response_code < 200 || $response_code >= 300 ) {
98        return new WP_Error(
99            'checking_plugin_failed',
100            "Invalid response from API - {$response_code}",
101            $error_data
102        );
103    }
104
105    if ( isset( $response['action'] ) && $response['action'] === 'reject' ) {
106        return new WP_Error( 'unaccepted_plugin', $response['message'] ?? '', $response['threats'] ?? '' );
107    }
108
109    $result = array(
110        'action'     => (string) ( $response['action'] ?? '' ),
111        'message'    => (string) ( $response['message'] ?? '' ),
112        'registered' => (string) ( $response['registered'] ?? '' ),
113    );
114
115    if ( array_key_exists( 'threats', $response ) ) {
116        $result['threats'] = $response['threats'];
117    }
118
119    return $result;
120}
121
122/**
123 * Tries to decompress the package into a temporary folder.
124 *
125 * @param string $package Plugin package.
126 * @return string|WP_Error
127 */
128function uncompress_package( $package ) {
129    $package_info     = pathinfo( $package );
130    $package_filename = $package_info['filename'];
131
132    $current_upload_folder = wp_upload_dir();
133    $path                  = $current_upload_folder['path'];
134
135    $tmp_package_folder = "{$path}/{$package_filename}";
136
137    // Try to unzip the file.
138    $zip_handler = new ZipArchive();
139    $was_opened  = $zip_handler->open( $package );
140    if ( $was_opened !== true ) {
141        return new WP_Error( 'process_failed', 'The zip file could not be opened.' );
142    }
143
144    $was_uncompressed = $zip_handler->extractTo( $tmp_package_folder );
145    if ( ! $was_uncompressed ) {
146        return new WP_Error( 'process_failed', 'The zip file could not be decompressed.' );
147    }
148
149    $zip_handler->close();
150
151    return $tmp_package_folder;
152}
153
154/**
155 * Clean folder structure.
156 *
157 * @param string $dir Directory path.
158 *
159 * @return bool
160 */
161function clean_folder( $dir ) {
162    if ( ! is_dir( $dir ) ) {
163        return false;
164    }
165
166    $it        = new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::SKIP_DOTS );
167    $old_files = new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::CHILD_FIRST );
168
169    foreach ( $old_files as $old_file ) {
170        if ( $old_file->isDir() ) {
171            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
172            rmdir( $old_file->getRealPath() );
173        } else {
174            // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
175            unlink( $old_file->getRealPath() );
176        }
177    }
178    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
179    rmdir( $dir );
180
181    return true;
182}
183
184/**
185 * It tries to get the plugin-slug and plugin-version from the file package.
186 *
187 * Some information:
188 *
189 *  > If you use a directory to contain your Plugin files, then the directory name will be used by WordPress
190 *  > when checking the WordPress Plugin Repository for updates. If your plugin only consists of a single PHP
191 *  > file, then the file name will be used. If WordPress tells you that a newer version of your Plugin is
192 *  > available, but you know nothing about a newer version, beware. It's possible that another Plugin with the
193 *  > same directory name or file name is in the Plugin Repository, and it's this one which WordPress is seeing.
194 *
195 *  - https://codex.wordpress.org/Writing_a_Plugin#Names.2C_Files.2C_and_Locations
196 *
197 * @param string $package Path of the package. Generally it's a .zip file.
198 * @return array|WP_Error  Slug and version Array, or a WP_Error instance if something fails.
199 */
200function get_plugin_data_from_package( $package ) {
201    if ( ! is_file( $package ) ) {
202        return new WP_Error( 'process_package_fails', 'Invalid plugin file.' );
203    }
204
205    $plugin_folder     = false;
206    $tmp_plugin_folder = uncompress_package( $package );
207    if ( is_wp_error( $tmp_plugin_folder ) ) {
208        return $tmp_plugin_folder;
209    }
210
211    $tmp_plugin_dir = @ opendir( $tmp_plugin_folder ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
212    $plugin_files   = array();
213    if ( $tmp_plugin_dir ) {
214        while ( ( $file = readdir( $tmp_plugin_dir ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
215            if ( substr( $file, 0, 1 ) === '.' ) {
216                continue;
217            }
218            if ( is_dir( $tmp_plugin_folder . '/' . $file ) ) {
219                // Get plugin slug from the folder.
220                $plugin_folder = $tmp_plugin_folder . '/' . $file;
221
222                $plugins_subdir = @ opendir( $tmp_plugin_folder . '/' . $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
223                if ( $plugins_subdir ) {
224                    while ( ( $subfile = readdir( $plugins_subdir ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
225                        if ( substr( $subfile, 0, 1 ) === '.' ) {
226                            continue;
227                        }
228                        if ( substr( $subfile, -4 ) === '.php' ) {
229                            $plugin_files[] = "$file/$subfile";
230                        }
231                    }
232                    closedir( $plugins_subdir );
233                }
234            } elseif ( substr( $file, -4 ) === '.php' ) {
235                    $plugin_files[] = $file;
236
237                    // Get plugin slug from the file.
238                    $plugin_folder = $tmp_plugin_folder . '/' . $file;
239            }
240        }
241        closedir( $tmp_plugin_dir );
242    }
243
244    if ( ! $plugin_folder ) {
245        return new WP_Error( 'process_package_fails', 'Getting plugin slug from package failed.' );
246    }
247
248    if ( empty( $plugin_files ) ) {
249        return new WP_Error( 'process_package_fails', 'Package does not have valid files.' );
250    }
251
252    // Finish getting plugin slug.
253    $plugin_pathinfo = pathinfo( $plugin_folder );
254    $plugin_slug     = $plugin_pathinfo['filename'];
255
256    if ( ! $plugin_slug ) {
257        return new WP_Error( 'process_package_fails', 'Plugin slug not found.' );
258    }
259
260    $result = array(
261        'slug' => $plugin_slug,
262        'hash' => hash_file( 'sha256', $package ),
263    );
264
265    /*
266     * Populate result array with plugin data, check if the plugin name is defined,
267     * and get the plugin version if it exists.
268     */
269    foreach ( $plugin_files as $plugin_file ) {
270        $plugin_filename = "{$tmp_plugin_folder}/{$plugin_file}";
271        if ( ! is_readable( $plugin_folder ) ) {
272            continue;
273        }
274
275        $plugin_data = get_plugin_data( $plugin_filename, false, false );
276        if ( empty( $plugin_data['Name'] ) ) {
277            continue;
278        }
279
280        $result['header'] = $plugin_data;
281    }
282
283    if ( ! array_key_exists( 'header', $result ) ) {
284        return new WP_Error( 'process_package_fails', 'Package does not have valid header.' );
285    }
286
287    // Copy version from header.
288    if ( array_key_exists( 'Version', $result['header'] ) ) {
289        $result['version'] = $result['header']['Version'];
290    }
291    if ( array_key_exists( 'version', $result['header'] ) ) {
292        $result['version'] = $result['header']['version'];
293    }
294
295    // Clean temporary folder.
296    clean_folder( $tmp_plugin_folder );
297
298    return $result;
299}
300
301/**
302 * Logs safeguard errors.
303 *
304 * @param WP_Error|string $error WP_Error object or error message.
305 * @param array           $extra Optional. Additional information about the error. Defaults to empty array.
306 *
307 * @return WP_Error|string
308 */
309function log_safeguard_error( $error, $extra = array() ) {
310    $message = 'Safeguard: ';
311
312    if ( is_wp_error( $error ) ) {
313        $message .= $error->get_error_message();
314    } else {
315        $message .= $error;
316    }
317
318    WPCOMSH_Log::unsafe_direct_log(
319        $message,
320        wp_json_encode( $extra, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES )
321    );
322
323    return $error;
324}