private function allMedia(Tree $tree, string $folder, string $subfolders, string $sort, string $filter, string $form_type): array
    {
        $query = DB::table('media')
            ->join('media_file', static function (JoinClause $join): void {
                $join
                    ->on('media_file.m_file', '=', 'media.m_file')
                    ->on('media_file.m_id', '=', 'media.m_id');
            })
            ->where('media.m_file', '=', $tree->id())
            ->distinct();

        // Match all external files, and whatever folders were specified
        $query->where(static function (Builder $query) use ($folder, $subfolders): void {
            $query
                ->where('multimedia_file_refn', 'LIKE', 'http:%')
                ->orWhere('multimedia_file_refn', 'LIKE', 'https:%')
                ->orWhere(static function (Builder $query) use ($folder, $subfolders): void {
                    $query->where('multimedia_file_refn', 'LIKE', $folder . '%');
                    if ($subfolders === 'exclude') {
                        $query->where('multimedia_file_refn', 'NOT LIKE', $folder . '/%/%');
                    }
                });
        });

        // Apply search terms
        if ($filter !== '') {
            $query->where(static function (Builder $query) use ($filter): void {
                $query
                    ->whereContains('multimedia_file_refn', $filter)
                    ->whereContains('descriptive_title', $filter, 'or');
            });
        }

        if ($form_type) {
            $query->where('source_media_type', '=', $form_type);
        }

        switch ($sort) {
            case 'file':
                $query->orderBy('multimedia_file_refn');
                break;
            case 'title':
                $query->orderBy('descriptive_title');
                break;
        }

        return $query
            ->get()
            ->map(Media::rowMapper())
            ->filter(GedcomRecord::accessFilter())
            ->all();
    }