Skip to content

Instantly share code, notes, and snippets.

@mattconnell
Created March 16, 2023 01:26
Show Gist options
  • Save mattconnell/93099b36fa60e77cc917fc81b84e3580 to your computer and use it in GitHub Desktop.
Save mattconnell/93099b36fa60e77cc917fc81b84e3580 to your computer and use it in GitHub Desktop.
A standalone, API-based Wallabag JSON importer
<?php
// Digest exported wallabag JSON and re-import it,
// since the built-in importer is broken.
// CONFIGURATION //
// Secrets file, for your API keys
define('WALLABAG_SECRETS', 'wallabag-secrets.php');
// Path to exported JSON file
define('WALLABAG_JSON_FILE', 'wallabag.json');
// Path to debug log file
define('WALLABAG_LOGFILE', 'wallabag.log');
// SETUP //
// Wallabag instance information
require_once(WALLABAG_SECRETS);
if(
!isset($wallabag_domain) ||
!isset($wallabag_client_id) ||
!isset($wallabag_client_secret) ||
!isset($wallabag_username) ||
!isset($wallabag_password)
) {
print('Missing necessary client credential(s) or configuration.'.PHP_EOL);
exit(1);
}
$data = json_decode(file_get_contents(WALLABAG_JSON_FILE));
if(!$data) {
print('Unable to parse JSON from specified file.'.PHP_EOL);
exit(1);
}
$ch = curl_init();
$token_post_data = [
'grant_type' => 'password',
'client_id' => $wallabag_client_id,
'client_secret' => $wallabag_client_secret,
'username' => $wallabag_username,
'password' => $wallabag_password
];
$opts = [
CURLOPT_URL => 'https://'.$wallabag_domain.'/oauth/v2/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $token_post_data
];
curl_setopt_array($ch, $opts);
$token_data = json_decode(curl_exec($ch));
$wallabag_access_token = $token_data->access_token;
curl_close($ch);
// IMPORT //
foreach($data as $datum) {
// Translate export fields to API parameters
$import_datum = [
'url' => $datum->url,
'title' => $datum->title,
'tags' => $datum->tags ?? [],
'archive' => $datum->is_archived ?? 0,
'starred' => $datum->is_starred ?? 0,
'content' => $datum->content ?? '',
'language' => $datum->language ?? 'en',
'preview_picture' => $datum->preview_picture ?? '',
'published_at' => $datum->published_at ?? 0,
'public' => $datum->is_public,
'origin_url' => $datum->origin_url ?? $datum->url
];
print('Importing "'.$import_datum['title'].'" ('.$import_datum['url'].')'.PHP_EOL);
$ch = curl_init();
$opts = [
CURLOPT_URL => 'https://'.$wallabag_domain.'/api/entries.json',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($import_datum),
CURLOPT_HTTPHEADER => array('Authorization: Bearer '.$wallabag_access_token)
];
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
// Debug logging
file_put_contents(WALLABAG_LOGFILE, $response, FILE_APPEND);
curl_close($ch);
}
@biosaat
Copy link

biosaat commented Nov 22, 2024

Thank you, matt, that worked for me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment