Skip to content

Instantly share code, notes, and snippets.

@ville6000
Last active January 31, 2023 07:25
Show Gist options
  • Save ville6000/d15e1f1b6f7a5636bf1a123d9cc9eaf1 to your computer and use it in GitHub Desktop.
Save ville6000/d15e1f1b6f7a5636bf1a123d9cc9eaf1 to your computer and use it in GitHub Desktop.
<?php
class KnowitTelltale
{
public function hooks(): void
{
add_action(
'rest_api_init',
\Closure::fromCallable([$this, 'registerRestRoutes'])
);
if (!defined('WP_CLI') || !\WP_CLI) {
return;
}
\WP_CLI::add_command(
'knowit:telltale',
\Closure::fromCallable([$this, 'run'])
);
}
private function registerRestRoutes(): void
{
register_rest_route(
'knowit/telltale/v1',
'update-prompt',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => \Closure::fromCallable([$this, 'updatePromptCallback']),
]
);
}
private function updatePromptCallback(): WP_Error | WP_REST_Response | WP_HTTP_Response
{
$response = $this->run()
? 'Ok'
: 'Error';
return rest_ensure_response(['message' => $response]);
}
private function run(): bool
{
$info = [
'wp' => $this->getWordPressInfo(),
'plugins' => $this->getPlugins(),
];
$response = wp_remote_post(
'http://wordpress-dashboard.lndo.site/api/sites',
[
'method' => 'POST',
'headers' => array(
'Content-Type' => 'application/json',
),
'body' => json_encode($info),
]
);
if (is_wp_error($response)) {
if (defined('WP_CLI') && \WP_CLI) {
\WP_CLI::log('Error');
}
return false;
}
$body = json_decode(wp_remote_retrieve_body($response));
if (defined('WP_CLI') && \WP_CLI) {
\WP_CLI::log($body->message);
}
return wp_remote_retrieve_response_code($response) === 201;
}
private function getPlugins(): array
{
$allPlugins = get_plugins();
$activePlugins = get_option('active_plugins');
$plugins = [];
foreach ($allPlugins as $key => $value) {
$plugins[] = [
'name' => $value['Name'],
'path' => $key,
'version' => $value['Version'],
'active' => in_array($key, $activePlugins, true),
];
}
return $plugins;
}
private function getWordPressInfo(): array
{
return [
'name' => get_bloginfo('name'),
'wpurl' => get_bloginfo('wpurl'),
'version' => get_bloginfo('version'),
];
}
}
(new KnowitTelltale())->hooks();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment