$path, 'url' => trailingslashit( $u['baseurl'] ) . 'chatdozo' ); } /** index.html and .htaccess in the folder, through the WordPress filesystem API. */ private static function guard( $path ) { global $wp_filesystem; if ( ! $wp_filesystem ) { require_once ABSPATH . 'wp-admin/includes/file.php'; WP_Filesystem(); } if ( ! $wp_filesystem ) { return; } $wp_filesystem->put_contents( $path . '/index.html', '', FS_CHMOD_FILE ); $wp_filesystem->put_contents( $path . '/.htaccess', "Options -Indexes\n\nDeny from all\n\n", FS_CHMOD_FILE ); } /** wp_handle_upload's upload_dir filter: our own folder, no year/month subfolders. */ public static function upload_dir( $dirs ) { $d = self::dir(); $dirs['path'] = $d['path']; $dirs['url'] = $d['url']; $dirs['subdir'] = '/chatdozo'; return $dirs; } /** A random file name; the original name is kept in the message, not on disk. */ public static function unique_name( $dir, $name, $ext ) { return gmdate( 'Ym' ) . '-' . wp_generate_password( 24, false, false ) . strtolower( (string) $ext ); } /** @return array|\WP_Error { url, type (image|file), name } */ public static function store( array $file ) { if ( empty( $file['tmp_name'] ) ) { return new \WP_Error( 'none', __( 'No file received.', 'chatdozo' ) ); } if ( (int) $file['size'] > self::MAX ) { return new \WP_Error( 'big', __( 'That file is over 8 MB.', 'chatdozo' ) ); } $allowed = array( 'jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp', 'pdf' => 'application/pdf' ); $check = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $allowed ); if ( empty( $check['ext'] ) || empty( $check['type'] ) ) { return new \WP_Error( 'type', __( 'Images and PDFs only.', 'chatdozo' ) ); } require_once ABSPATH . 'wp-admin/includes/file.php'; add_filter( 'upload_dir', array( __CLASS__, 'upload_dir' ) ); $moved = wp_handle_upload( $file, array( 'test_form' => false, 'mimes' => $allowed, 'unique_filename_callback' => array( __CLASS__, 'unique_name' ), ) ); remove_filter( 'upload_dir', array( __CLASS__, 'upload_dir' ) ); if ( ! is_array( $moved ) || ! empty( $moved['error'] ) || empty( $moved['url'] ) ) { return new \WP_Error( 'move', is_array( $moved ) && ! empty( $moved['error'] ) ? (string) $moved['error'] : __( 'Could not save the file.', 'chatdozo' ) ); } return array( 'url' => $moved['url'], 'type' => strpos( (string) $moved['type'], 'image/' ) === 0 ? 'image' : 'file', 'name' => sanitize_file_name( $file['name'] ), ); } public static function remove( $url ) { $d = self::dir(); if ( strpos( (string) $url, $d['url'] . '/' ) !== 0 ) { return; } $name = basename( (string) $url ); if ( preg_match( '/^[0-9]{6}-[A-Za-z0-9]{24}\.[a-z0-9]{3,4}$/', $name ) ) { wp_delete_file( $d['path'] . '/' . $name ); } } }