1 <?php
2
3 4 5 6 7 8 9 10
11
12 13 14 15 16 17 18 19 20
21 class P3LoggableBehavior extends CActiveRecordBehavior {
22
23 private $_oldattributes = array();
24
25 public function afterSave($event) {
26 if (!$this->Owner->isNewRecord) {
27
28
29 $newattributes = $this->Owner->getAttributes();
30 $oldattributes = $this->getOldAttributes();
31
32
33 $hasChanges = false;
34 $fields = "";
35 foreach ($newattributes as $name => $value) {
36 if (!empty($oldattributes)) {
37 $old = $oldattributes[$name];
38 } else {
39 $old = '';
40 }
41 if ($value != $old) {
42 $hasChanges = true;
43 $fields .= $name . ",";
44 }
45 }
46 if ($hasChanges) {
47
48
49 $log = new P2Log;
50 $log->description = 'User ' . Yii::app()->user->Name
51 . ' changed ' . $fields . ' for '
52 . get_class($this->Owner)
53 . ' #' . $this->Owner->getPrimaryKey() . '.';
54 $log->data = CJSON::encode($this->getOldAttributes());
55
56 $log->action = 'CHANGE';
57 $log->model = get_class($this->Owner);
58 $log->modelId = $this->Owner->getPrimaryKey();
59 $log->changes = $fields;
60 $log->createdAt = new CDbExpression('NOW()');
61 $log->createdBy = Yii::app()->user->id;
62 $log->save();
63 }
64 } else {
65 $log = new P2Log;
66 $log->description = 'User ' . Yii::app()->user->Name
67 . ' created ' . get_class($this->Owner)
68 . ' #' . $this->Owner->getPrimaryKey() . '.';
69 $log->action = 'CREATE';
70 $log->model = get_class($this->Owner);
71 $log->modelId = $this->Owner->getPrimaryKey();
72 $log->changes = '';
73 $log->createdAt = new CDbExpression('NOW()');
74 $log->createdBy = Yii::app()->user->id;
75 $log->save();
76 }
77 }
78
79 public function afterDelete($event) {
80 $log = new P2Log;
81 $log->description = 'User ' . Yii::app()->user->Name . ' deleted '
82 . get_class($this->Owner)
83 . ' #' . $this->Owner->getPrimaryKey() . '.';
84 $log->data = CJSON::encode($this->getOldAttributes());
85
86 $log->action = 'DELETE';
87 $log->model = get_class($this->Owner);
88 $log->modelId = $this->Owner->getPrimaryKey();
89 $log->changes = '';
90 $log->createdAt = new CDbExpression('NOW()');
91 $log->createdBy = Yii::app()->user->id;
92 $log->save();
93 }
94
95 public function afterFind($event) {
96
97 $this->setOldAttributes($this->Owner->getAttributes());
98 }
99
100 public function getOldAttributes() {
101 return $this->_oldattributes;
102 }
103
104 public function setOldAttributes($value) {
105 $this->_oldattributes = $value;
106 }
107
108 }
109
110 ?>
111