in_array( $status, array( 'sent', 'failed' ), true ) ? $status : '', 's' => $get( 's' ), 'date_from' => LogRepository::valid_date( $get( 'date_from' ) ), 'date_to' => LogRepository::valid_date( $get( 'date_to' ) ), 'format' => in_array( $format, array( 'html', 'plain' ), true ) ? $format : '', 'orderby' => in_array( $orderby, LogRepository::SORTABLE, true ) ? $orderby : 'sent_at', 'order' => 'asc' === strtolower( $get( 'order' ) ) ? 'ASC' : 'DESC', 'per_page' => in_array( $per_page, self::PER_PAGE_CHOICES, true ) ? $per_page : self::PER_PAGE, 'paged' => max( 1, absint( $get( 'paged' ) ) ), ); // phpcs:enable WordPress.Security.NonceVerification.Recommended // A reversed range is almost always a slip -- swap rather than show nothing. if ( $filters['date_from'] && $filters['date_to'] && $filters['date_from'] > $filters['date_to'] ) { list( $filters['date_from'], $filters['date_to'] ) = array( $filters['date_to'], $filters['date_from'] ); } return $filters; } /** * The filters in the shape LogRepository expects. * * @param array $f Filters from current_filters(). * @return array */ private function repo_args( array $f ): array { return array( 'status' => $f['status'], 'search' => $f['s'], 'date_from' => $f['date_from'], 'date_to' => $f['date_to'], 'format' => $f['format'], ); } /** * Render the log screen. * * @return void */ public function render(): void { if ( ! current_user_can( self::CAP ) ) { wp_die( esc_html__( 'You are not allowed to do this.', 'all-in-one-utilities' ), '', array( 'response' => 403 ) ); } $notice = get_transient( 'aiou_email_log_notice_' . get_current_user_id() ); delete_transient( 'aiou_email_log_notice_' . get_current_user_id() ); $f = $this->current_filters(); $args = $this->repo_args( $f ); $rows = LogRepository::query( $args + array( 'page' => $f['paged'], 'per_page' => $f['per_page'], 'orderby' => $f['orderby'], 'order' => $f['order'], ) ); $total = LogRepository::count( $args ); $total_pages = (int) ceil( $total / $f['per_page'] ); // Tab counts honour every other filter, so they always add up to what the tabs show. $counts = array( '' => LogRepository::count( array( 'status' => '' ) + $args ), 'sent' => LogRepository::count( array( 'status' => 'sent' ) + $args ), 'failed' => LogRepository::count( array( 'status' => 'failed' ) + $args ), ); $day_ago = gmdate( 'Y-m-d', (int) current_time( 'timestamp' ) - DAY_IN_SECONDS ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested -- sent_at is stored in site time. $stats = array( 'all' => LogRepository::count(), 'sent' => LogRepository::count( array( 'status' => 'sent' ) ), 'failed' => LogRepository::count( array( 'status' => 'failed' ) ), 'recent' => LogRepository::count( array( 'date_from' => $day_ago ) ), ); $fail_rate = $stats['all'] ? round( 100 * $stats['failed'] / $stats['all'] ) : 0; $filtered = '' !== $f['s'] || $f['date_from'] || $f['date_to'] || $f['format']; ?>


quick_ranges() as $range ) : $active = $f['date_from'] === $range['from'] && $f['date_to'] === $range['to']; ?>
column_headers( $f ); ?> status; ?> >
sent_at ) ); ?> sent_at ) ); ?> to_address ); ?> subject ? $row->subject : __( '(no subject)', 'all-in-one-utilities' ) ); ?> is_html ) : ?> HTML error ) ) : ?> error, 120, '…' ) ); ?> delete_link( (int) $row->id ); ?>
pagination_links( $f, $total_pages ); ?>
*/ private function quick_ranges(): array { $now = (int) current_time( 'timestamp' ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested -- sent_at is stored in site time. $today = gmdate( 'Y-m-d', $now ); return array( array( 'label' => __( 'Today', 'all-in-one-utilities' ), 'from' => $today, 'to' => $today, ), array( 'label' => __( 'Last 7 days', 'all-in-one-utilities' ), 'from' => gmdate( 'Y-m-d', $now - 6 * DAY_IN_SECONDS ), 'to' => $today, ), array( 'label' => __( 'Last 30 days', 'all-in-one-utilities' ), 'from' => gmdate( 'Y-m-d', $now - 29 * DAY_IN_SECONDS ), 'to' => $today, ), array( 'label' => __( 'This month', 'all-in-one-utilities' ), 'from' => gmdate( 'Y-m-01', $now ), 'to' => $today, ), ); } /** * Build a list URL from the current filters plus overrides, leaving out * anything at its default so links stay short. * * @param array $f Filters from current_filters() (or a subset). * @param array $overrides Values to change. * @return string */ private function list_url( array $f, array $overrides = array() ): string { $f = array_merge( $f, $overrides ); $args = array( 'page' => self::PAGE_SLUG ); foreach ( array( 'status', 's', 'date_from', 'date_to', 'format' ) as $key ) { if ( ! empty( $f[ $key ] ) ) { $args[ $key ] = $f[ $key ]; } } if ( ! empty( $f['orderby'] ) && ( 'sent_at' !== $f['orderby'] || 'ASC' === ( $f['order'] ?? 'DESC' ) ) ) { $args['orderby'] = $f['orderby']; $args['order'] = strtolower( $f['order'] ?? 'DESC' ); } if ( ! empty( $f['per_page'] ) && self::PER_PAGE !== (int) $f['per_page'] ) { $args['per_page'] = (int) $f['per_page']; } if ( ! empty( $f['paged'] ) && (int) $f['paged'] > 1 ) { $args['paged'] = (int) $f['paged']; } return add_query_arg( array_map( 'rawurlencode', $args ), admin_url( 'admin.php' ) ); } /** * The CSV export link for the current filters. * * @param array $f Filters from current_filters(). * @return string */ private function export_url( array $f ): string { $args = array( 'action' => 'aiou_email_log_action', 'task' => 'export', ); foreach ( array( 'status', 's', 'date_from', 'date_to', 'format' ) as $key ) { if ( '' !== $f[ $key ] ) { $args[ $key ] = rawurlencode( $f[ $key ] ); } } return wp_nonce_url( add_query_arg( $args, admin_url( 'admin-post.php' ) ), 'aiou-email-log-export' ); } /** * Render the sortable column header row. * * @param array $f Filters from current_filters(). * @return void */ private function column_headers( array $f ): void { $columns = array( 'status' => __( 'Status', 'all-in-one-utilities' ), 'sent_at' => __( 'Date', 'all-in-one-utilities' ), 'to_address' => __( 'To', 'all-in-one-utilities' ), 'subject' => __( 'Subject', 'all-in-one-utilities' ), ); echo ''; echo ''; foreach ( $columns as $key => $label ) { $current = $f['orderby'] === $key; $next_order = ( $current && 'ASC' === $f['order'] ) ? 'DESC' : 'ASC'; $url = $this->list_url( $f, array( 'orderby' => $key, 'order' => $next_order, 'paged' => 1, ) ); $indicator = ''; $aria = ''; if ( $current ) { $indicator = ' '; $aria = ' aria-sort="' . ( 'ASC' === $f['order'] ? 'ascending' : 'descending' ) . '"'; } echo '' . esc_html( $label ) . $indicator . ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $indicator and $aria are literal HTML fragments built above, not user input. } echo '' . esc_html__( 'Actions', 'all-in-one-utilities' ) . ''; echo ''; } /** * Render one row's "Delete" action link. * * @param int $id Row id. * @return void */ private function delete_link( int $id ): void { $url = wp_nonce_url( add_query_arg( array( 'action' => 'aiou_email_log_action', 'task' => 'delete_one', 'id' => $id, ), admin_url( 'admin-post.php' ) ), 'aiou-email-log-delete-' . $id ); printf( ' %s', esc_url( $url ), esc_html__( 'Delete', 'all-in-one-utilities' ) ); } /** * Render pagination links. * * @param array $f Filters from current_filters(). * @param int $total_pages Total pages. * @return void */ private function pagination_links( array $f, int $total_pages ): void { if ( $total_pages < 2 ) { return; } $links = paginate_links( array( 'base' => str_replace( '999999999', '%#%', $this->list_url( $f, array( 'paged' => 999999999 ) ) ), 'format' => '', 'current' => min( $f['paged'], $total_pages ), 'total' => $total_pages, 'type' => 'plain', 'mid_size' => 1, 'prev_text' => '‹ ' . esc_html__( 'Previous', 'all-in-one-utilities' ), 'next_text' => esc_html__( 'Next', 'all-in-one-utilities' ) . ' ›', ) ); if ( $links ) { echo '
' . $links . '
'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- paginate_links() output is already escaped. } } /** * Handle a delete/clear action. * * @return void */ public function handle_action(): void { if ( ! current_user_can( self::CAP ) ) { wp_die( esc_html__( 'You are not allowed to do this.', 'all-in-one-utilities' ), '', array( 'response' => 403 ) ); } $task = isset( $_REQUEST['task'] ) ? sanitize_key( wp_unslash( $_REQUEST['task'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified per-task below with check_admin_referer(), which needs $task decided first. $redirect = wp_get_referer(); $redirect = $redirect ? $redirect : admin_url( 'admin.php?page=' . self::PAGE_SLUG ); switch ( $task ) { case 'export': check_admin_referer( 'aiou-email-log-export' ); $this->export_csv(); // No break needed: the CSV export always exits. case 'delete_one': $id = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0; check_admin_referer( 'aiou-email-log-delete-' . $id ); LogRepository::delete( array( $id ) ); $this->notice( $redirect, 'success', __( 'Logged email deleted.', 'all-in-one-utilities' ) ); // no break: notice() always redirects and exit()s. case 'delete_selected': check_admin_referer( 'aiou-email-log-bulk' ); $ids = isset( $_POST['ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['ids'] ) ) : array(); if ( empty( $ids ) ) { $this->notice( $redirect, 'error', __( 'No logged emails were selected.', 'all-in-one-utilities' ) ); } LogRepository::delete( $ids ); /* translators: %d: number of deleted rows */ $this->notice( $redirect, 'success', sprintf( _n( '%d logged email deleted.', '%d logged emails deleted.', count( $ids ), 'all-in-one-utilities' ), count( $ids ) ) ); // no break: notice() always redirects and exit()s. case 'clear_all': check_admin_referer( 'aiou-email-log-clear-all' ); LogRepository::delete_all(); $this->notice( $redirect, 'success', __( 'The email log has been cleared.', 'all-in-one-utilities' ) ); // no break: notice() always redirects and exit()s. default: $this->notice( $redirect, 'error', __( 'Unknown action.', 'all-in-one-utilities' ) ); } } /** * Stream the logged emails matching the current filters as a CSV file. * * @return never */ private function export_csv() { $rows = LogRepository::export_rows( $this->repo_args( $this->current_filters() ) ); nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="email-log-' . gmdate( 'Y-m-d' ) . '.csv"' ); $out = fopen( 'php://output', 'w' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- streaming a download, not touching the filesystem. fwrite( $out, "\xEF\xBB\xBF" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite -- UTF-8 BOM, so Excel reads accented characters correctly. fputcsv( $out, array( 'Date', 'Status', 'To', 'Subject', 'Format', 'Error' ), ',', '"', '\\' ); foreach ( $rows as $row ) { fputcsv( $out, array_map( array( $this, 'csv_cell' ), array( $row->sent_at, $row->status, $row->to_address, $row->subject, $row->is_html ? 'HTML' : 'Plain text', (string) $row->error ) ), ',', '"', '\\' ); } fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose exit; } /** * Neutralise spreadsheet formulas (a subject like "=HYPERLINK(...)") so * opening the export in Excel or Sheets can't run anything. * * @param mixed $value Cell value. * @return string */ private function csv_cell( $value ): string { $value = (string) $value; if ( '' !== $value && in_array( $value[0], array( '=', '+', '-', '@', "\t", "\r" ), true ) ) { $value = "'" . $value; } return $value; } /** * Store a one-time notice and redirect back to the log screen. * * @param string $redirect Redirect URL. * @param string $type 'success' or 'error'. * @param string $message Notice text. * @return never */ private function notice( string $redirect, string $type, string $message ) { set_transient( 'aiou_email_log_notice_' . get_current_user_id(), array( 'type' => $type, 'message' => $message, ), MINUTE_IN_SECONDS ); wp_safe_redirect( $redirect ); exit; } /** * AJAX: fetch one logged email's full content for the popup. * * @return void */ public function ajax_view(): void { if ( ! current_user_can( self::CAP ) ) { wp_send_json_error( array( 'message' => __( 'You are not allowed to do this.', 'all-in-one-utilities' ) ), 403 ); } check_ajax_referer( 'aiou-email-log-view' ); $id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; $row = $id ? LogRepository::get( $id ) : null; if ( ! $row ) { wp_send_json_error( array( 'message' => __( 'That logged email could not be found.', 'all-in-one-utilities' ) ), 404 ); } $headers = array(); if ( ! empty( $row->headers ) ) { $headers = array_values( array_filter( preg_split( '/\r\n|\r|\n/', (string) $row->headers ) ) ); } wp_send_json_success( array( 'subject' => (string) $row->subject, 'to' => (string) $row->to_address, 'sent_at' => mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $row->sent_at ), 'status' => (string) $row->status, 'error' => (string) $row->error, 'is_html' => (bool) $row->is_html, 'body' => null === $row->body ? null : (string) $row->body, 'headers' => $headers, ) ); } }