DataObjects/Events.php
[Pman.Core] / DataObjects / Events.php
1 <?php
2 /**
3  * Table Definition for Events
4  *
5  * objects can implement relatedWhere(), which should return
6  *    'tablename' => array of ids
7  *
8  * 
9  */
10 require_once 'DB/DataObject.php';
11
12 class Pman_Core_DataObjects_Events extends DB_DataObject 
13 {
14     ###START_AUTOCODE
15     /* the code below is auto generated do not remove the above tag */
16
17     public $__table = 'Events';                          // table name
18     public $id;                              // int(11)  not_null primary_key auto_increment
19     public $person_name;                     // string(128)  
20     public $event_when;                      // datetime(19)  binary
21     public $action;                          // string(32)  
22     public $ipaddr;                          // string(16)  
23     public $on_id;                           // int(11)  
24     public $on_table;                        // string(64)  
25     public $person_id;                       // int(11)  
26     public $remarks;                         // blob(65535)  blob
27
28     
29     /* the code above is auto generated do not remove the tag below */
30     ###END_AUTOCODE
31     
32     
33     
34     
35     //  ------------ROO HOOKS------------------------------------
36     function applyFilters($q, $au)
37     {
38         $tn = $this->tableName();
39         if (!empty($q['query']['from'])) {
40             $dt = date('Y-m-d' , strtotime($q['query']['from']));
41             $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
42         }
43         if (!empty($q['query']['to'])) {
44             $dt = date('Y-m-d' , strtotime($q['query']['to']));
45             $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
46         }
47         /*
48         if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
49             // grouped..
50             DB_DataObject::Debuglevel(1);
51             $this->groupBy('on_id');
52             $this->selectAdd('
53                 (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
54                 ');
55         }
56         */
57         
58         if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
59             //DB_DataObject::DebugLevel(1);
60             // they can only view their changes..
61             $this->person_id = $au->id;
62             
63         }
64         // _join = tablename,tablename...
65         
66         /// on_table=cohead
67         //   &_join=cohead
68         //   &_join_cols=cohead_number
69         //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
70         // max(event_when) is not supported... by any query yet..
71         
72         
73         if (isset($q['_join'])) {
74             //DB_DataObject::DebugLevel(1);
75             $joins = explode(',',$q['_join']);
76             
77             $this->selectAdd(); // ???
78             $distinct = false;
79             
80             foreach($joins as $t) {
81                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
82                 $x = DB_DataObject::Factory($t);
83                 if (!is_a($x,'DB_DataObject')) {
84                     continue;
85                 }
86                 $jtn = $x->tableName();
87                 $jk = array_shift($x->keys());
88                 $this->_join .= "
89                 
90                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
91                         AND on_table = '{$jtn}'
92                 ";
93                 $keys = array_keys($x->table());
94                 if (isset($q['_join_cols'])) {
95                     $jcs = explode(',',$q['_join_cols'] );
96                     //DB_DataObject::DebugLevel(1);
97                     
98                     foreach($jcs as $jc) { 
99                         if (! in_array($jc, $keys)) {
100                             continue;
101                         }
102                         if ($distinct) { 
103                         
104                        
105                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
106                         } else {
107                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
108                             $distinct = true;
109                         }
110                         $this->groupBy("on_id_{$jc} ");
111                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
112                     }
113                     $this->selectAdd( "MAX(events.event_when) as event_when");
114                     $this->orderBy('event_when DESC');
115                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
116                 } else { 
117                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
118                 }
119             }
120                 
121                 
122             
123             
124         }
125         
126         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
127             // example: sales order - has invoices,
128             $ev  =$this->factory('Events');
129             $ev->setFrom(array(
130                 'on_id' => $q['_related_on_id'],
131                 'on_table' => $q['_related_on_table'],
132                                ));
133             $obj = $ev->object();
134             
135             if ($obj && method_exists($obj,'relatedWhere')) {
136                 $ar = $obj->relatedWhere();
137                 $tn = $this->tableName();
138                 
139                 $w = array();
140                 $w[] = "( {$tn}.on_table = '" .
141                         $this->escape($q['_related_on_table']) .
142                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
143                     ")";
144                 
145                 
146                 foreach($ar as $k=>$v) {
147                     if (empty($v)) {
148                         continue;
149                     }                
150                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
151                     
152                 }
153                 $this->whereAdd(implode(' OR ' , $w));
154             }
155             
156             
157             
158             
159             
160         }
161         
162         
163         
164         
165         
166             
167     }
168     /**
169      * check who is trying to access this. false == access denied..
170      * @return {boolean} true if access is allowed.
171      */
172     function checkPerm($lvl, $au) 
173     {
174         if ($lvl == 'S') {
175             return true;
176         }
177         // listing is controleed by applyfilters..
178         return $au->hasPerm("Admin.Admin_Tab", 'S');
179     }
180     /**
181      * object :
182      * return the object that this relates to.
183      * 
184      * @return {DB_DataObject} related object
185      */
186     function object()
187     {
188         $o = DB_DataObject::factory($this->on_table);
189         $o->get($this->on_id);
190         return $o;
191         
192     }
193     
194     
195     /**
196      * init:
197      * Initialize an event - ready to insert..
198      * 
199      * @param {String} action  - group/name of event
200      * @param {DataObject|false} obj - dataobject action occured on.
201      * @param {String} any remarks 
202      */
203     
204     function init($act, $obj, $remarks)
205     {
206         $ff = HTML_FlexyFramework::get();
207         $pg = $ff->page;
208         $au = $pg->getAuthUser();
209         
210         if ($ff->cli && empty($au) && isset($obj->person_id)) {
211             $au = DB_DataObject::Factory('Person'); // not always a person..
212             $au->get($obj->person_id);
213         } 
214          
215          
216          
217         $this->person_name = $au && !empty($au->name) ? $au->name : '';
218         $this->person_id = $au ? $au->id : '';
219         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
220         $this->action = $act;
221         $this->on_table = $obj ? $obj->tableName() : '';
222         $pk = $obj ? $obj->keys()  : false;
223         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
224         $rem  = array();
225         // should this really go in remarks? - 
226         if ($obj && method_exists($obj,'toEventString')) {
227             $rem[] = $obj->toEventString() ;
228         }
229         $rem[] = $remarks;
230         $this->remarks = implode(' : ', $rem);
231     }
232     
233     /**
234      * Generate an audit for this field.
235      *
236      * @param {DB_DataObject} new data
237      * @param {DB_DataObject} old data
238      * 
239      * @return {int} number of entries logged.
240      */
241     
242     function audit($new, $old = false)
243     {
244         if ($old == $new) {
245             return 0; // they are the same...
246         }
247          
248         $ret = 0;
249         foreach(array_keys($new->table()) as $k) {
250             // should we JSON serialize this?
251             $n = empty($new->$k) ? '' : $new->$k;
252             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
253             if ($n == $o) {
254                 continue;
255             }
256             $this->auditField($k, $o, $n, $old);
257             $ret++;
258         }
259         return $ret;
260     }
261     /**
262      * Record an audited change, in theory so we can audit data that is not just
263      * database Fields...
264      *
265      * @param {string} $name    table field anme
266      * @param {mixed} $ov  old value
267      * @param {mixed} $onv  new value
268      * @param {mixed} $old  old object (false if we are creating..)
269      */
270     function auditField($name, $ov, $nv, $old=false )
271     {
272         $x = DB_DataObject::factory('core_event_audit');
273         $x->setFrom(array(
274             'event_id' => $this->id,
275             'name' => $name,
276             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
277             'newvalue' => $nv
278
279         ));
280         $x->insert();
281     
282     }
283 }