Skip to content

Instantly share code, notes, and snippets.

@stevygee
Created April 22, 2020 12:34
Show Gist options
  • Save stevygee/d35aec0bb1cfca7fdadb3e65095eab02 to your computer and use it in GitHub Desktop.
Save stevygee/d35aec0bb1cfca7fdadb3e65095eab02 to your computer and use it in GitHub Desktop.
Simple Download Monitor: Filter download logs by date range, group by download ID and count number of downloads
<?php
function sdm_export_download_logs_to_csv( $from, $to ) {
// Check for valid dates (yyyy-mm-dd)
$date_pattern = '/^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/';
if ( 1 !== preg_match( $date_pattern, $from ) || 1 !== preg_match( $date_pattern, $to ) ) {
return false;
}
// Check for valid date range
if( strtotime( $from ) > strtotime( $to ) ) {
return false;
}
// Increment 'to' date by 1 day
$to_nextday = date( "Y-m-d", strtotime( "+1 day", strtotime( $to ) ) );
// Convert date to datetime for query
$from_sql = $from . ' 00:00:00';
$to_sql = $to_nextday . ' 00:00:00';
global $wpdb;
$table_name = $wpdb->prefix . 'sdm_downloads';
$resultset = $wpdb->get_results(
$wpdb->prepare( "SELECT *, COUNT(*) AS count FROM $table_name WHERE date_time >= %s AND date_time < %s GROUP BY post_id", $from_sql, $to_sql )
, OBJECT);
$csv_file_path = WP_SIMPLE_DL_MONITOR_PATH . "sdm-download-logs.csv";
$fp = fopen($csv_file_path, 'w');
$header_names = array("Download ID", "Download Title", "File URL", "From", "To", "Download Count");
fputcsv($fp, $header_names);
foreach ($resultset as $result) {
if (empty($result->purchase_qty)) {
$result->purchase_qty = 1;
}
$fields = array($result->post_id, $result->post_title, $result->file_url, $from, $to, $result->count);
fputcsv($fp, $fields);
}
fclose($fp);
$file_url = WP_SIMPLE_DL_MONITOR_URL . '/sdm-download-logs.csv';
return $file_url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment