| 1 |
<?php |
| 2 |
|
| 3 |
namespace FlyWP\Api; |
| 4 |
|
| 5 |
class Plugins { |
| 6 |
|
| 7 |
/** |
| 8 |
* API constructor. |
| 9 |
*/ |
| 10 |
public function __construct() { |
| 11 |
flywp()->router->get( 'plugins', [ $this, 'respond' ] ); |
| 12 |
} |
| 13 |
|
| 14 |
/** |
| 15 |
* Handle request. |
| 16 |
* |
| 17 |
* @return void |
| 18 |
*/ |
| 19 |
public function respond( $args ) { |
| 20 |
$valid_statuses = [ 'all', 'active', 'inactive' ]; |
| 21 |
$status = isset( $args['status'] ) && in_array( $args['status'], $valid_statuses, true ) ? $args['status'] : 'all'; |
| 22 |
|
| 23 |
if ( ! function_exists( 'get_plugins' ) ) { |
| 24 |
require_once ABSPATH . 'wp-admin/includes/plugin.php'; |
| 25 |
} |
| 26 |
|
| 27 |
if ( ! function_exists( 'get_plugin_updates' ) ) { |
| 28 |
require_once ABSPATH . 'wp-admin/includes/update.php'; |
| 29 |
} |
| 30 |
|
| 31 |
$response = []; |
| 32 |
$plugins = get_plugins(); |
| 33 |
$updates = get_plugin_updates(); |
| 34 |
|
| 35 |
foreach ( $plugins as $file => $details ) { |
| 36 |
$plugin_status = $this->get_status( $file ); |
| 37 |
|
| 38 |
if ( 'all' !== $status && $status !== $plugin_status ) { |
| 39 |
continue; |
| 40 |
} |
| 41 |
|
| 42 |
$update = $this->get_update( $file, $updates ); |
| 43 |
|
| 44 |
$response[] = [ |
| 45 |
'name' => $details['Name'], |
| 46 |
'version' => $details['Version'], |
| 47 |
'url' => $details['PluginURI'], |
| 48 |
'update_available' => $update ? true : false, |
| 49 |
'new_version' => $update ? $update['new_version'] : null, |
| 50 |
'author' => $details['Author'], |
| 51 |
'file' => $file, |
| 52 |
'status' => $plugin_status, |
| 53 |
'textdomain' => $details['TextDomain'], |
| 54 |
'description' => $details['Description'], |
| 55 |
'php' => $details['RequiresPHP'], |
| 56 |
]; |
| 57 |
} |
| 58 |
|
| 59 |
wp_send_json( $response ); |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Get plugin active status. |
| 64 |
* |
| 65 |
* @param string $file |
| 66 |
* |
| 67 |
* @return string |
| 68 |
*/ |
| 69 |
private function get_status( $file ) { |
| 70 |
return is_plugin_active( $file ) ? 'active' : 'inactive'; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Check if a plugin has an update available. |
| 75 |
* |
| 76 |
* @param string $plugin_file |
| 77 |
* @param array $updates |
| 78 |
* |
| 79 |
* @return array|bool |
| 80 |
*/ |
| 81 |
private function get_update( $plugin_file, $updates ) { |
| 82 |
if ( isset( $updates[ $plugin_file ] ) && isset( $updates[ $plugin_file ]->update ) ) { |
| 83 |
return [ |
| 84 |
'new_version' => $updates[ $plugin_file ]->update->new_version, |
| 85 |
'package' => $updates[ $plugin_file ]->update->package, |
| 86 |
]; |
| 87 |
} |
| 88 |
|
| 89 |
return false; |
| 90 |
} |
| 91 |
} |
| 92 |
|