<?php
// Require WordPress to prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    $wp_load = dirname( __FILE__ );
    for ( $i = 0; $i < 10; $i++ ) {
        $wp_load = dirname( $wp_load );
        if ( file_exists( $wp_load . '/wp-load.php' ) ) {
            require_once $wp_load . '/wp-load.php';
            break;
        }
    }
}

if ( ! defined( 'ABSPATH' ) ) {
    http_response_code( 403 );
    die( 'Forbidden' );
}

// Restrict to gallery directories within the uploads folder only
$allowed_base = wp_upload_dir();
$allowed_base = realpath( $allowed_base['basedir'] );

if ( ! $allowed_base ) {
    http_response_code( 403 );
    die( 'Forbidden' );
}

$raw_path = isset( $_GET['path'] ) ? urldecode( base64_decode( $_GET['path'] ) ) : '';
$folder   = isset( $_GET['folder'] ) ? $_GET['folder'] : '';

$raw_path = str_replace( "\0", '', $raw_path );
$folder   = sanitize_file_name( basename( str_replace( "\0", '', $folder ) ) );

$resolved = realpath( $raw_path );

// Path traversal guard: resolved path must be inside uploads
if (
    ! $resolved ||
    strpos( $resolved . DIRECTORY_SEPARATOR, $allowed_base . DIRECTORY_SEPARATOR ) !== 0
) {
    header( 'Content-Type: application/json' );
    echo json_encode( array( 'flag' => 0 ) );
    die();
}

$target = $resolved . '/' . $folder;
$target = realpath( $target );

if (
    ! $target ||
    strpos( $target . DIRECTORY_SEPARATOR, $allowed_base . DIRECTORY_SEPARATOR ) !== 0 ||
    ! is_dir( $target )
) {
    header( 'Content-Type: application/json' );
    echo json_encode( array( 'flag' => 0 ) );
    die();
}

function nbdesigner_get_list_files( $folder ) {
    $files = array();
    if ( $handle = opendir( $folder ) ) {
        while ( false !== ( $entry = readdir( $handle ) ) ) {
            if ( $entry !== '.' && $entry !== '..' ) {
                $full = $folder . '/' . $entry;
                $ext  = strtolower( pathinfo( $entry, PATHINFO_EXTENSION ) );
                if ( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg' ), true ) ) {
                    $files[] = $full;
                }
            }
        }
        closedir( $handle );
    }
    return $files;
}

function nbdesigner_get_gallery( $images ) {
    $gallery = array();
    asort( $images );
    foreach ( $images as $image ) {
        $size = @getimagesize( $image );
        if ( ! $size ) {
            continue;
        }
        $gallery[] = array(
            'src'    => basename( $image ),
            'width'  => $size[0],
            'height' => $size[1],
            'title'  => '',
            'sizes'  => $size[0] . 'x' . $size[1],
        );
    }
    return $gallery;
}

$data = array( 'flag' => 0 );
$data['images'] = nbdesigner_get_gallery( nbdesigner_get_list_files( $target ) );
$data['flag']   = 1;

header( 'Content-Type: application/json' );
echo json_encode( $data );
die();
