Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add email logs export options( CSV, JSON, TXT) #163

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ public function sendError($data = null, $code = 423)
public function verify()
{
$permission = 'manage_options';
if(!current_user_can($permission)) {
if (!current_user_can($permission)) {
wp_send_json_error([
'message' => __('You do not have permission to do this action', 'fluent-smtp')
]);
die();
}

$nonce = $this->request->get('nonce');
if(!wp_verify_nonce($nonce, FLUENTMAIL)) {
if (!wp_verify_nonce($nonce, FLUENTMAIL)) {
wp_send_json_error([
'message' => __('Security Failed. Please reload the page', 'fluent-smtp')
]);
Expand Down
89 changes: 81 additions & 8 deletions app/Http/Controllers/LoggerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function delete(Request $request, Logger $logger)
$count = count($id);
$subject = $count > 1 ? "{$count} Logs" : 'Log';
}

return $this->sendSuccess([
'message' => "{$subject} deleted successfully."
]);
Expand All @@ -52,7 +52,7 @@ public function retry(Request $request, Logger $logger)
$this->verify();

try {
$this->app->addAction('wp_mail_failed', function($response) use ($logger, $request) {
$this->app->addAction('wp_mail_failed', function ($response) use ($logger, $request) {
$log = $logger->find($id = $request->get('id'));
$log['retries'] = $log['retries'] + 1;
$logger->updateLog($log, ['id' => $id]);
Expand All @@ -71,7 +71,6 @@ public function retry(Request $request, Logger $logger)
}

throw new \Exception('Something went wrong', 400);

} catch (\Exception $e) {
return $this->sendError([
'message' => $e->getMessage()
Expand All @@ -85,7 +84,7 @@ public function retryBulk(Request $request, Logger $logger)
$logIds = $request->get('log_ids', []);

$failedCount = 0;
$this->app->addAction('wp_mail_failed', function($response) use (&$failedCount) {
$this->app->addAction('wp_mail_failed', function ($response) use (&$failedCount) {
$failedCount++;
});

Expand All @@ -101,17 +100,91 @@ public function retryBulk(Request $request, Logger $logger)
}
$message = 'Selected Emails have been proceed to send.';

if($failedCount) {
$message .= ' But '.$failedCount.' emails are reported to failed to send.';
if ($failedCount) {
$message .= ' But ' . $failedCount . ' emails are reported to failed to send.';
}

if($failedInitiated) {
$message .= ' And '.$failedInitiated.' emails are failed to init the emails';
if ($failedInitiated) {
$message .= ' And ' . $failedInitiated . ' emails are failed to init the emails';
}

return $this->sendSuccess([
'message' => $message
]);
}

public function export(Request $request, Logger $logger)
{
$this->verify();
$format = $request->get('format', 'txt'); // csv, txt, json
$results = $logger->getAll();

$filename = 'fsmtp-logs-' . date('Y-m-d-H-i-s') . '.' . $format;
$content = '';
$mime_type = 'text/plain';

switch ($format) {
case 'csv':
$mime_type = 'text/csv';
$content = $this->convertToCSV($results);
break;
case 'txt':
$mime_type = 'text/plain';
foreach ($results as $result) {
$content .= json_encode($result, JSON_PRETTY_PRINT) . "\n\n";
}
break;
case 'json':
$mime_type = 'application/json';
$content = json_encode($results, JSON_PRETTY_PRINT);
break;
default:
break;
}

header('Content-Description: File Transfer');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="' . $filename . '"');
echo $content;
exit();
}

public function convertToCSV(array $objArray)
{
if (!is_array($objArray) || empty($objArray)) {
return null;
}

$headers = implode(',', array_keys($objArray[0])) . "\n";

// Process each row
$rows = array_map(function ($row) {
// Create an array of values
$values = [];

// Process each property in the row
foreach ($row as $key => $value) {
// If the value is an object or array, convert to JSON string
if (is_array($value) || is_object($value)) {
$value = json_encode($value, JSON_PRETTY_PRINT);
}

// Escape any double quotes in the value
if (is_string($value) || is_array($value)) {
$value = str_replace('"', '\"', $value);
}

// Wrap the value in double quotes
$value = '"' . $value . '"';

// Add the value to the array
$values[] = $value;
}
// Join the values with commas and return the row as a string
return implode(',', $values) . "\n";
}, $objArray);

// Join the headers and rows and return as CSV string
return $headers . implode('', $rows);
}
}
1 change: 1 addition & 0 deletions app/Http/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
$app->post('/logs/retry', 'LoggerController@retry');
$app->post('/logs/retry-bulk', 'LoggerController@retryBulk');
$app->post('/logs/delete', 'LoggerController@delete');
$app->get('/logs/export', 'LoggerController@export');


$app->post('install_plugin', 'SettingsController@installPlugin');
Expand Down
13 changes: 9 additions & 4 deletions app/Models/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ public function get($data)
$q->orWhere($column, 'LIKE', '%' . $search . '%');
}
}

});
}
$result = $query->paginate();
Expand All @@ -91,6 +90,15 @@ public function get($data)
return $result;
}

public function getAll()
{
$db = $this->getDb();
$query = $db->table(FLUENT_MAIL_DB_PREFIX . 'email_logs');
$result = $query->get();
$result = $this->formatResult($result);
return $result;
}

protected function buildWhere($data)
{
$where = [];
Expand Down Expand Up @@ -191,7 +199,6 @@ public function add($data)

return $this->getDb()->table(FLUENT_MAIL_DB_PREFIX . 'email_logs')
->insert($data);

} catch (Exception $e) {
return $e;
}
Expand Down Expand Up @@ -395,7 +402,6 @@ public function deleteLogsOlderThan($days)
$date = date('Y-m-d H:i:s', current_time('timestamp') - $days * DAY_IN_SECONDS);
$query = $this->db->prepare("DELETE FROM {$this->table} WHERE `created_at` < %s", $date);
return $this->db->query($query);

} catch (Exception $e) {
if (wp_get_environment_type() != 'production') {
error_log('Message: ' . $e->getMessage());
Expand Down Expand Up @@ -465,5 +471,4 @@ public function getSubjectStat($status, $statDate, $endDate, $limit = 5)

return $this->db->get_results($query, ARRAY_A);
}

}
8 changes: 7 additions & 1 deletion resources/admin/Bits/FluentMail.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ import {
Collapse,
CollapseItem,
Skeleton,
SkeletonItem
SkeletonItem,
Dropdown,
DropdownItem,
DropdownMenu,
} from 'element-ui';

Vue.use(Row);
Expand Down Expand Up @@ -74,6 +77,9 @@ Vue.use(ButtonGroup);
Vue.use(TableColumn);
Vue.use(CheckboxGroup);
Vue.use(Loading.directive);
Vue.use(Dropdown);
Vue.use(DropdownItem);
Vue.use(DropdownMenu);

Vue.prototype.$message = MessageBox.alert;
Vue.prototype.$notify = Notification;
Expand Down
Loading