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