Log.class.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Log selected action in database with ip, datetime and optional logged user.
  4. * @author valentin carruesco
  5. * @category Core
  6. * @license copyright
  7. */
  8. class Log extends Entity
  9. {
  10. public $id,$label,$category,$ip;
  11. protected $fields =
  12. array(
  13. 'id' => 'key',
  14. 'label' => 'longstring',
  15. 'category' => 'string',
  16. 'ip' => 'string',
  17. );
  18. public function label(){
  19. return preg_replace_callback('|^\[([^\]]*)\](.*)|i', function($matches){
  20. return '<span class="badge badge-info">'.$matches[1].'</span>'.$matches[2];
  21. }, $this->label);
  22. }
  23. public static function put($label,$category = 'Général') {
  24. global $myUser;
  25. $log = new self();
  26. $log->label = $label;
  27. $log->category = $category;
  28. $log->ip = ip();
  29. $log->save();
  30. }
  31. //Compare deux instances d'une même entité et log les differences entr eles deux dans un format json
  32. public static function compare($old,$new = null,$metafunction=null){
  33. global $myUser;
  34. $log = new self();
  35. $log->label = array();
  36. if(!isset($new) || !isset($old->id) || $old->id==0){
  37. $log->label['action'] = 'create';
  38. $log->label['fields'] = is_object($new) ? $new->toArray(): $old->toArray();
  39. }else if (!$new){
  40. $log->label['action'] = 'delete';
  41. $log->label['fields'] = $old->toArray();
  42. }elseif (is_object($new)){
  43. $log->label['action'] = 'update';
  44. $log->label['fields'] = Entity::compare($old,$new);
  45. }
  46. $log->label['entity'] = $old->tableName();
  47. $log->category = $log->label['entity'].'::compare';
  48. $log->ip = ip();
  49. if(isset($metafunction))
  50. $metafunction($log);
  51. $log->label = json_encode($log->label);
  52. $log->save();
  53. }
  54. public static function clear($delay = 1){
  55. $treshold = time() - ($delay * 86400);
  56. self::delete(array('created:<'=>$treshold));
  57. }
  58. }