Skip to content

Instantly share code, notes, and snippets.

@kierzniak
Last active February 16, 2018 08:58
Show Gist options
  • Save kierzniak/4a7be33fa9a4a88b3b3bb9908fe26c42 to your computer and use it in GitHub Desktop.
Save kierzniak/4a7be33fa9a4a88b3b3bb9908fe26c42 to your computer and use it in GitHub Desktop.
Save user activity to log file when post is saved
<?php
/**
* Function to save activity to log file when post is saved
*
* @param int $post_id Saved post id
*/
function motivast_add_activity_log_on_post_save( $post_id ) {
$format = '[%s] Post with ID %d was updated by user %s from IP %s';
$log_dir = motivast_get_logs_dir();
$log = $log_dir . '/.debug.log';
$ip = (isset($_SERVER['HTTP_CLIENT_IP'])) ? $_SERVER['HTTP_CLIENT_IP'] : ((isset($_SERVER['HTTP_X_FORWARDE‌​D_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
$current_user = wp_get_current_user();
$stack_trace = motivast_generate_stack_trace();
$action = sprintf($format, date('Y-m-j H:i:s'), $post_id, $current_user->user_login, $ip);
file_put_contents($log, $action, FILE_APPEND);
file_put_contents($log, $stack_trace, FILE_APPEND);
}
add_action( 'save_post', 'motivast_add_activity_log_on_post_save' );
/**
* Get logs directory
*
* If directory does not exists create one.
*
* @return string
*/
function motivast_get_logs_dir() {
$log_dir = WP_CONTENT_DIR . '/logs';
if( !file_exists($log_dir) || !is_dir($log_dir) ) {
mkdir($log_dir, 0755);
}
return $log_dir;
}
// Function from php.net http://php.net/manual/en/function.debug-backtrace.php#112238
function motivast_generate_stack_trace() {
$e = new \Exception();
$trace = explode( "\n" , $e->getTraceAsString() );
// reverse array to make steps line up chronologically
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
array_pop($trace); // remove call to this method
$length = count($trace);
$result = array();
for ($i = 0; $i < $length; $i++) {
$result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
}
$result = implode("\n", $result);
$result = "\n" . $result . "\n";
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment