Skip to content

Instantly share code, notes, and snippets.

@chandrapatel
Last active June 3, 2022 11:02
Show Gist options
  • Save chandrapatel/ba22cd3655097ae65072bb62688e6107 to your computer and use it in GitHub Desktop.
Save chandrapatel/ba22cd3655097ae65072bb62688e6107 to your computer and use it in GitHub Desktop.
Export stream records on daily basis and send email with CSV file.
<?php
/**
* Plugin Name: Export Stream Records
* Description: Export stream records on daily basis and send email with CSV file.
* Author: Chandra Patel
*/
/**
* Schedule daily event to perform export.
*
* @return void
*/
function esr_schedule_event() {
if ( ! function_exists( 'is_plugin_active' ) ) {
include_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if ( ! is_plugin_active( 'stream/stream.php' ) ) {
$timestamp = wp_next_scheduled( 'esr_export' );
wp_unschedule_event( $timestamp, 'esr_export' );
return;
}
if ( ! wp_next_scheduled( 'esr_export' ) ) {
// Get timestamp of morning 8am time.
$date = new DateTimeImmutable( 'tomorrow midnight', wp_timezone() );
$timestamp = $date->getTimestamp();
wp_schedule_event( $timestamp, 'daily', 'esr_export' );
}
}
add_action( 'init', 'esr_schedule_event' );
/**
* Peform export.
*
* @return void
*/
function esr_perform_export() {
$stream_plugin = wp_stream_get_instance();
if ( ! is_object( $stream_plugin ) ) {
return;
}
$date = gmdate( 'Y-m-d', strtotime( 'yesterday' ) );
$args = [
'date_from' => $date,
'date_to' => $date,
'records_per_page' => 10000,
];
$records = $stream_plugin->db->get_records( $args );
// Do not send email if there is no activity for the day.
if ( empty( $records ) ) {
return;
}
$columns = [
'date' => 'Date',
'summary' => 'Summary',
'user_id' => 'User',
'context' => 'Context',
'action' => 'Action',
'ip' => 'IP Address',
];
$columns = $stream_plugin->admin->export->expand_columns( $columns );
$output = [];
foreach ( $records as $item ) {
$output[] = $stream_plugin->admin->export->build_record( $item, $columns );
}
$csv_file_name = sprintf( 'stream-records-%s.csv', $date );
$csv_file_path = sprintf( '%s/%s', untrailingslashit( get_temp_dir() ), $csv_file_name );
$csv_file = fopen( $csv_file_path, 'w' );
fputcsv( $csv_file, $columns );
foreach ( $output as $row ) {
fputcsv( $csv_file, $row );
}
wp_mail(
'[email protected]',
sprintf( 'Stream Records - %s', $date ),
sprintf( 'Find attached CSV report of stream records for %s.', $date ),
sprintf( 'From: %s <no-reply@%s>', esc_html( get_bloginfo( 'name' ) ), esc_html( wp_parse_url( get_bloginfo( 'url' ), PHP_URL_HOST ) ) ) . "\r\n",
[ $csv_file_path ]
);
fclose( $csv_file );
unlink( $csv_file_path );
}
add_action( 'esr_export', 'esr_perform_export' );
@MervinHernandez
Copy link

Fantastic, thank you again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment