*/ public static function files( int $document_id ): array { $out = []; foreach ( self::ids( $document_id ) as $id ) { $path = get_attached_file( $id ); $out[] = [ 'id' => $id, 'name' => basename( (string) $path ) ?: get_the_title( $id ), 'size' => $path && file_exists( $path ) ? size_format( (int) filesize( $path ) ) : '', 'url' => (string) wp_get_attachment_url( $id ), 'path' => (string) $path, ]; } return $out; } /* ---- Builder ---------------------------------------------------- */ private static function field( string $tab ): array { return [ 'tab_id' => $tab, 'name' => 'attachments', 'type' => 'attachments', 'label' => __( 'Attachments', 'easy-invoice' ), 'grid_cols' => 'sm:col-span-6', 'section' => 'notes', 'order' => 9, 'description' => __( 'Files the client can download from the document page and that are sent with the email — a timesheet, a signed contract, delivery photos.', 'easy-invoice' ), ]; } public static function invoiceField( $fields ) { $fields = is_array( $fields ) ? $fields : []; $fields[] = self::field( 'invoice-tab' ); return $fields; } public static function quoteField( $fields ) { $fields = is_array( $fields ) ? $fields : []; $fields[] = self::field( 'quote-tab' ); return $fields; } /** * Persist the field on a quote. * * @param object $quote Quote model. * @param array $data Submitted data. * @return void */ public static function saveQuote( $quote, $data ): void { if ( is_array( $data ) && array_key_exists( 'attachments', $data ) && is_callable( [ $quote, 'setMetaData' ] ) ) { $ids = is_array( $data['attachments'] ) ? $data['attachments'] : explode( ',', (string) $data['attachments'] ); $quote->setMetaData( '_easy_invoice_attachments', implode( ',', array_filter( array_map( 'intval', $ids ) ) ) ); } } /** * The media library on the builders. * * @return void */ public static function media(): void { $page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( in_array( $page, [ 'easy-invoice-builder', 'easy-invoice-new', 'easy-invoice-quote-builder' ], true ) ) { wp_enqueue_media(); } } /** * Field markup: chosen files, an Add button, a hidden CSV of ids. * * @param array $field Field config. * @param mixed $document Model or null. * @return string */ public static function renderField( array $field, $document = null ): string { $id = $document && is_callable( [ $document, 'getId' ] ) ? (int) $document->getId() : 0; $files = $id ? self::files( $id ) : []; $ids = implode( ',', array_map( static function ( $f ) { return $f['id']; }, $files ) ); $html = '
' . esc_html( $field['description'] ) . '
'; } $html .= '