<?php
/**
* QuickWP - Same-Origin Media Proxy for Visual Media Picker Modal
*
* Uses QuickWP's configured site & credentials server-side to avoid browser CORS issues.
*/
require_once __DIR__ . '/partials/bootstrap.php';
use QuickWP\QuickWP;
header('Content-Type: application/json; charset=utf-8');
$action = $_GET['action'] ?? 'list';
$formatMedia = static function (array $m): array {
$id = (int) ($m['id'] ?? 0);
$title = is_array($m['title'] ?? null) ? ($m['title']['rendered'] ?? '#' . $id) : ($m['title'] ?? '#' . $id);
$url = (string) ($m['source_url'] ?? '');
$thumb = (string) ($m['media_details']['sizes']['medium']['source_url']
?? $m['media_details']['sizes']['thumbnail']['source_url']
?? $url);
return [
'id' => $id,
'title' => html_entity_decode(strip_tags((string) $title), ENT_QUOTES, 'UTF-8'),
'url' => $url,
'thumb' => $thumb,
'alt' => (string) ($m['alt_text'] ?? ''),
'mime_type' => (string) ($m['mime_type'] ?? ''),
];
};
if ($action === 'get') {
$id = (int) ($_GET['id'] ?? 0);
if ($id <= 0) {
echo json_encode(['ok' => false, 'error' => 'Invalid media ID']);
exit;
}
$res = $qwp->media()->get($id);
if (QuickWP::isSuccess($res) && is_array($res['json'])) {
echo json_encode(['ok' => true, 'item' => $formatMedia($res['json'])]);
} else {
echo json_encode(['ok' => false, 'error' => QuickWP::getError($res)]);
}
exit;
}
$page = max(1, (int) ($_GET['page'] ?? 1));
$search = trim((string) ($_GET['search'] ?? ''));
$params = [
'per_page' => 12,
'page' => $page,
'_fields' => 'id,title,source_url,alt_text,mime_type,media_details',
];
if ($search !== '') {
$params['search'] = $search;
}
$res = $qwp->media()->list($params);
if (!QuickWP::isSuccess($res) || !is_array($res['json'])) {
echo json_encode(['ok' => false, 'error' => QuickWP::getError($res)]);
exit;
}
$items = [];
foreach ($res['json'] as $m) {
if (is_array($m)) {
$items[] = $formatMedia($m);
}
}
$totalPages = (int) ($res['headers']['x-wp-totalpages'] ?? 1);
echo json_encode([
'ok' => true,
'items' => $items,
'page' => $page,
'totalPages' => max(1, $totalPages),
]);
|