/, so the shop manager of one site never sees the files * dropped for another. */ final class IncomingDir { /** * Configured directory. * * @return string|null */ public static function dir(): ?string { $dir = defined( 'CATALOGRELAY_INCOMING_DIR' ) ? (string) CATALOGRELAY_INCOMING_DIR : ''; if ( '' !== $dir && is_multisite() ) { $dir = untrailingslashit( $dir ) . '/' . get_current_blog_id(); } $dir = (string) apply_filters( 'catalogrelay_incoming_dir', $dir, get_current_blog_id() ); if ( '' === $dir || ! is_dir( $dir ) ) { return null; } $real = realpath( $dir ); return false === $real ? null : $real; } /** * Selectable files. * * @return array[] {name, size} */ public static function files(): array { $dir = self::dir(); if ( null === $dir ) { return array(); } $out = array(); foreach ( (array) scandir( $dir ) as $item ) { $path = $dir . '/' . $item; if ( '.' === $item[0] || is_link( $path ) || ! is_file( $path ) || ! self::allowedName( $item ) ) { continue; } $out[] = array( 'name' => $item, 'size' => (int) filesize( $path ), ); } return $out; } /** * Resolve a chosen file name to a safe absolute path. * * @param string $name File name (no directories). * @return string|null */ public static function resolve( string $name ): ?string { $dir = self::dir(); if ( null === $dir || basename( $name ) !== $name || '' === $name || '.' === $name[0] || ! self::allowedName( $name ) ) { return null; } $path = $dir . '/' . $name; if ( is_link( $path ) || ! is_file( $path ) ) { return null; } $real = realpath( $path ); return ( false !== $real && 0 === strpos( $real, $dir . DIRECTORY_SEPARATOR ) ) ? $real : null; } /** * Allowed extensions. * * @param string $name File name. * @return bool */ public static function allowedName( string $name ): bool { return in_array( strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ), array( 'csv', 'tsv', 'txt' ), true ); } }