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         if (isset($q['on_table']) && !strlen($q['on_table'])) {
73             // empty ontable queries.. these are valid..
74             $this->whereAdd("$tn.on_table = ''");
75         }
76         
77         
78         if (isset($q['query']['person_sum'])) {
79             //DB_DataObject::debugLevel(1);
80             $this->_extra_cols = array('qty' );
81             $this->selectAdd("count($tn.id) as qty");
82             $this->selectAdd("count( distinct $tn.on_id) as uqty");
83             $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
84             $this->groupBy('person_id');
85         }
86          if (isset($q['query']['table_sum'])) {
87             //DB_DataObject::debugLevel(1);
88             $this->_extra_cols = array('qty' , 'uqty');
89             $this->selectAdd("count($tn.id) as qty");
90             $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
91             
92             $this->groupBy('on_table');
93         }
94          if (isset($q['query']['day_sum'])) {
95             //DB_DataObject::debugLevel(1);
96             $this->_extra_cols = array('qty' , 'uqty');
97             $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
98             $this->selectAdd("count($tn.id) as qty");
99             $this->selectAdd("count( distinct $tn.on_id) as uqty");
100             
101             $this->groupBy('on_day');
102         }
103         
104         if (isset($q['_join'])) {
105             //DB_DataObject::DebugLevel(1);
106             $joins = explode(',',$q['_join']);
107             
108             $this->selectAdd(); // ???
109             $distinct = false;
110             
111             foreach($joins as $t) {
112                 $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
113                 $x = DB_DataObject::Factory($t);
114                 if (!is_a($x,'DB_DataObject')) {
115                     continue;
116                 }
117                 $jtn = $x->tableName();
118                 $jk = array_shift($x->keys());
119                 $this->_join .= "
120                 
121                     LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
122                         AND on_table = '{$jtn}'
123                 ";
124                 $keys = array_keys($x->table());
125                 if (isset($q['_join_cols'])) {
126                     $jcs = explode(',',$q['_join_cols'] );
127                     //DB_DataObject::DebugLevel(1);
128                     
129                     foreach($jcs as $jc) { 
130                         if (! in_array($jc, $keys)) {
131                             continue;
132                         }
133                         if ($distinct) { 
134                         
135                        
136                             $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
137                         } else {
138                             $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
139                             $distinct = true;
140                         }
141                         $this->groupBy("on_id_{$jc} ");
142                         $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
143                     }
144                     $this->selectAdd( "MAX(events.event_when) as event_when");
145                     $this->orderBy('event_when DESC');
146                    // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
147                 } else { 
148                     $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
149                 }
150             }
151                 
152                 
153             
154             
155         }
156         
157         if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
158             // example: sales order - has invoices,
159             $ev  =$this->factory('Events');
160             $ev->setFrom(array(
161                 'on_id' => $q['_related_on_id'],
162                 'on_table' => $q['_related_on_table'],
163                                ));
164             $obj = $ev->object();
165             
166             if ($obj && method_exists($obj,'relatedWhere')) {
167                 $ar = $obj->relatedWhere();
168                 $tn = $this->tableName();
169                 
170                 $w = array();
171                 $w[] = "( {$tn}.on_table = '" .
172                         $this->escape($q['_related_on_table']) .
173                         "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
174                     ")";
175                 
176                 
177                 foreach($ar as $k=>$v) {
178                     if (empty($v)) {
179                         continue;
180                     }                
181                      $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
182                     
183                 }
184                 $this->whereAdd(implode(' OR ' , $w));
185             }
186             
187             
188             
189             
190             
191         }
192         // since roo does not support autojoin yet..
193         $this->autoJoinExtra();
194         
195         
196         
197         
198             
199     }
200      
201     function autoJoinExtra()
202     {
203         //$ret = parent::autoJoin();
204         //DB_DataObject::debugLevel(1);
205         
206         // now try and magically join person_table to the right table..
207         $tn = $this->tableName();
208         $pt = DB_DataObject::Factory($this->tableName());
209         $pt->selectAdD();
210         $pt->selectAdD('distinct(person_table) as person_table');
211         $pt->whereAdd('person_table IS NOT NULL AND LENGTH(person_table) > 0');
212         $tbls = $pt->fetchAll('person_table');
213         if (!in_array('Person',$tbls)) {
214             $tbls[] = 'Person';
215         }
216         foreach($tbls as $tbl) {
217             
218             // find all the columns from the joined table..
219             $st = DB_DataObject::Factory($tbl);
220             $tcols = array_keys($st->table());
221             foreach($tcols as $col) {
222                 if ($col == 'passwd') {
223                     continue;
224                 }
225                 $cols[$col]  = isset($cols[$col] ) ? $cols[$col]  : array();
226                 $cols[$col][] = "WHEN {$tn}.person_table = '$tbl'  THEN join_person_table_{$tbl}.{$col}";
227             }
228             // id's are hard coded...
229             $this->_join .= "
230                 LEFT JOIN {$tbl} AS  join_person_table_{$tbl}
231                     ON {$tn}.person_id = join_person_table_{$tbl}.id
232                         AND {$tn}.person_table = '{$tbl}'
233              
234             ";
235         }
236         foreach($cols as $col=>$whens) {
237             
238             $this->selectAdd("
239                     CASE
240                         ". implode("\n", $whens) ." 
241                         ELSE ''
242                     END
243                     as person_table_{$col}"
244             );
245         }
246         //return $ret;
247          
248     }
249     
250     
251     /**
252      * check who is trying to access this. false == access denied..
253      * @return {boolean} true if access is allowed.
254      */
255     function checkPerm($lvl, $au) 
256     {
257         if ($lvl == 'S') {
258             return true;
259         }
260         // listing is controleed by applyfilters..
261         return $au->hasPerm("Admin.Admin_Tab", 'S');
262     }
263     /**
264      * object :
265      * return the object that this relates to.
266      * 
267      * @return {DB_DataObject} related object
268      */
269     function object()
270     {
271         $o = DB_DataObject::factory($this->on_table);
272         $o->get($this->on_id);
273         return $o;
274         
275     }
276     
277     
278     /**
279      * init:
280      * Initialize an event - ready to insert..
281      * 
282      * @param {String} action  - group/name of event
283      * @param {DataObject|false} obj - dataobject action occured on.
284      * @param {String} any remarks 
285      */
286     
287     function init($act, $obj, $remarks)
288     {
289         $ff = HTML_FlexyFramework::get();
290         $pg = $ff->page;
291         $au = $pg->getAuthUser();
292         
293         if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
294             $au = false;
295            // $au = DB_DataObject::Factory('Person'); // not always a person..
296            // $au->get($obj->person_id);
297         } 
298           
299         $this->person_name = $au && !empty($au->name) ? $au->name : '';
300         $this->person_id = $au ? $au->id : -1;
301         $this->person_table = $au ? $au->tableName() : '';
302         $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
303         $this->action = $act;
304         $this->on_table = $obj ? $obj->tableName() : '';
305         $pk = $obj ? $obj->keys()  : false;
306         $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
307         $rem  = array();
308         // should this really go in remarks? - 
309         if ($obj && method_exists($obj,'toEventString')) {
310             $rem[] = $obj->toEventString() ;
311         }
312         $rem[] = $remarks;
313         $this->remarks = implode(' : ', $rem);
314     }
315     
316     /**
317      * Generate an audit for this field.
318      *
319      * @param {DB_DataObject} new data
320      * @param {DB_DataObject} old data
321      * 
322      * @return {int} number of entries logged.
323      */
324     
325     function audit($new, $old = false)
326     {
327         if ($old == $new) {
328             return 0; // they are the same...
329         }
330          
331         $ret = 0;
332         foreach(array_keys($new->table()) as $k) {
333             // should we JSON serialize this?
334             $n = empty($new->$k) ? '' : $new->$k;
335             $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
336             if ($n == $o) {
337                 continue;
338             }
339             $this->auditField($k, $o, $n, $old);
340             $ret++;
341         }
342         return $ret;
343     }
344     /**
345      * Record an audited change, in theory so we can audit data that is not just
346      * database Fields...
347      *
348      * @param {string} $name    table field anme
349      * @param {mixed} $ov  old value
350      * @param {mixed} $onv  new value
351      * @param {mixed} $old  old object (false if we are creating..)
352      */
353     function auditField($name, $ov, $nv, $old=false )
354     {
355         $x = DB_DataObject::factory('core_event_audit');
356         $x->setFrom(array(
357             'event_id' => $this->id,
358             'name' => $name,
359             'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
360             'newvalue' => $nv
361
362         ));
363         $x->insert();
364     
365     }
366 }