actually i am trying to hook to all available events and log that something happend. my log function is based on the uniform log action.
function hook_log($obj) {
if(is_a($obj, 'Page')) {
// for some templates
if( substr($obj->template(), 0, 4) == 'obj-' ||
substr($obj->template(), 0, 3) == 'db-' ||
in_array($obj->template(), ['home', 'site'] )
) {
Hlprs::log($ev, [
'autoid' => $obj->autoid()->exists() ? $obj->autoid() : false,
'uri' => $obj->uri(),
'site.user' => site()->user() ? site()->user()->username() : false,
]);
}
} else if (is_a($obj, 'File')) {
Hlprs::log($ev, [
'uri' => $page->uri(),
'siteuser' => site()->user() ? site()->user()->username() : false,
]);
} else if (is_a($obj, 'User')) {
Hlprs::log($ev, [
'uri' => $obj->uri(),
'username' => $obj->username(),
'siteuser' => site()->user() ? site()->user()->username() : false,
]);
}
}
used like this. now you see my intention to use the loop.
kirby()->hook('panel.page.create', function($page) {
hook_log($page);
});
kirby()->hook('panel.file.replace', function($file) {
hook_log($file);
});
kirby()->hook('panel.user.update', function($user) {
hook_log($user);
});
the log function is defined in Hlprs class.
public static $LOG_FOLDER = DS.'logs'.DS;
public static $LOG_EXTENSION = '.log';
public static function log($fileURI, $arr) {
$root = kirby()->roots()->index();
// based on uniform action 'log'
$filepath = $root.Hlprs::$LOG_FOLDER.str::lower(str_replace('.', '-', $fileURI)).Hlprs::$LOG_EXTENSION;
$data = '['.date('c').'] '.visitor::ip().' '.visitor::userAgent();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$value = implode(', ', array_filter($value, function ($i) {
return $i !== '';
}));
}
$data .= "\n{$key}: {$value}";
}
$data .= "\n\n";
$success = file_put_contents($filepath, $data, FILE_APPEND | LOCK_EX);
if(!$success) {
throw new Exception('ERROR: failed to write to log');
}
return $success;
}