Skip to content

Instantly share code, notes, and snippets.

@sburlot
Created April 23, 2024 08:07
Show Gist options
  • Save sburlot/d26a4d4f7590f78d8c9677eee87a956e to your computer and use it in GitHub Desktop.
Save sburlot/d26a4d4f7590f78d8c9677eee87a956e to your computer and use it in GitHub Desktop.
Outputs list of all sites managed with MainWP in a CSV file
#!/usr/bin/env php
<?php
/*
Little helper tool to help me manage all my WordPress sites
Needs MainWP https://mainwp.com/ installed and configured
Creates a CSV file with all sites managed by MainWP
CSV File with site name, url, WP version, PHP version and name of theme
Tested with PHP 8.1.27
Stephan Burlot 2024
*/
$consumer_key = "ck_CONSUMER_KEY"
$consumer_secret = "cs_SECRET_KEY";
$main_url = "https://example.com/wp-json/mainwp/v1/";
$csv_file = "sites.csv";
// https://kb.mainwp.com/docs/mainwp-rest-api/
function get_url($fields) {
global $consumer_key, $consumer_secret, $main_url;
if (!str_contains($fields, '?')) {
$fields .= '?';
} else {
$fields .= '&';
}
$url = $main_url . $fields . "consumer_key=$consumer_key&consumer_secret=$consumer_secret";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_VERBOSE, 0);
// Add WordPress to user agent, some WAF block robot requests without this */
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:108.0) Gecko/20100101 Firefox/108.0; WordPress");
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if (curl_errno($ch)) {
print ('Curl error: ' . curl_error($ch) . " ($http_code) with url: $url\n");
unset($response);
}
curl_close($ch);
return (isset($response) ? $response: null);
}
$response = get_url("sites/all-sites");
$sites = json_decode($response, true);
$csv = "";
$fp = fopen($csv_file, 'w');
// the empty field is used to add a checkbox to the spreasheet
$header = "name,,url,wp_version,php_version,theme\n";
fwrite($fp, $header);
foreach ($sites as $site) {
print("Getting info about " . $site['name'] . " (". $site['id'] . ")\n");
$response = get_url("site/site-info?site_id=" . $site['id']);
if (!isset($response)) {
print("ERROR: Could not get info about site id: " . $site['id']);
break;
}
$site_info = json_decode($response, true);
$csv = $site['name'] . ",TRUE," . $site['url'] . ",\"" . $site_info['wpversion'] . "\"," . $site_info['phpversion'] . "," . $site_info['themeactivated'] . "\n";
fwrite($fp, $csv);
}
fclose($fp);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment